@aganzefelicite/responsekit-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4980 @@
1
+ import { __export, formatValue, isDev, rowsToCsv } from './chunk-3FSZRQQU.js';
2
+ import ReactMarkdown from 'react-markdown';
3
+ import remarkGfm from 'remark-gfm';
4
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
+ import { lazy, Suspense, Component, useReducer, useState, useRef, useCallback, useEffect } from 'react';
6
+
7
+ // src/actions.ts
8
+ var noopAction = () => {
9
+ };
10
+ function Markdown({ children, className }) {
11
+ return /* @__PURE__ */ jsx("div", { className: className ?? "rk-markdown", children: /* @__PURE__ */ jsx(
12
+ ReactMarkdown,
13
+ {
14
+ remarkPlugins: [remarkGfm],
15
+ components: {
16
+ a: ({ node: _node, ...props }) => /* @__PURE__ */ jsx("a", { ...props, target: "_blank", rel: "noopener noreferrer" })
17
+ },
18
+ children
19
+ }
20
+ ) });
21
+ }
22
+ function TextBlock({ block }) {
23
+ return /* @__PURE__ */ jsx("div", { className: "rk-block rk-block-text", children: /* @__PURE__ */ jsx(Markdown, { children: block.content }) });
24
+ }
25
+ var TREND_GLYPH = { UP: "\u25B2", DOWN: "\u25BC", STABLE: "\u2192" };
26
+ function KpiBlock({ block }) {
27
+ const items = Array.isArray(block.items) ? block.items : [];
28
+ return /* @__PURE__ */ jsxs("section", { className: "rk-block rk-block-kpi", "aria-label": block.title ?? "KPIs", children: [
29
+ block.title ? /* @__PURE__ */ jsx("h3", { className: "rk-block-title", children: block.title }) : null,
30
+ /* @__PURE__ */ jsx("div", { className: "rk-kpi-grid", children: items.map((item, i) => {
31
+ const display = item.formattedValue ?? formatValue(item.value);
32
+ const trend = item.trend;
33
+ return /* @__PURE__ */ jsxs("div", { className: "rk-kpi-item", children: [
34
+ /* @__PURE__ */ jsx("div", { className: "rk-kpi-label", children: item.label }),
35
+ /* @__PURE__ */ jsx("div", { className: "rk-kpi-value", children: display }),
36
+ trend || typeof item.percentageChange === "number" ? /* @__PURE__ */ jsxs(
37
+ "div",
38
+ {
39
+ className: `rk-kpi-trend rk-kpi-trend-${(trend ?? "STABLE").toLowerCase()}`,
40
+ children: [
41
+ trend ? /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: TREND_GLYPH[trend] }) : null,
42
+ typeof item.percentageChange === "number" ? /* @__PURE__ */ jsxs("span", { children: [
43
+ item.percentageChange > 0 ? "+" : "",
44
+ item.percentageChange,
45
+ "%"
46
+ ] }) : null
47
+ ]
48
+ }
49
+ ) : null
50
+ ] }, `${item.label}-${i}`);
51
+ }) })
52
+ ] });
53
+ }
54
+ var ChartRenderer = lazy(() => import('./ChartRenderer-URPZESVN.js'));
55
+ function ChartBlock({ block }) {
56
+ return /* @__PURE__ */ jsxs("section", { className: "rk-block rk-block-chart", children: [
57
+ block.title ? /* @__PURE__ */ jsx("h3", { className: "rk-block-title", children: block.title }) : null,
58
+ /* @__PURE__ */ jsx(
59
+ Suspense,
60
+ {
61
+ fallback: /* @__PURE__ */ jsx("div", { className: "rk-chart-placeholder", "aria-busy": "true", children: "Loading chart\u2026" }),
62
+ children: /* @__PURE__ */ jsx(ChartRenderer, { block })
63
+ }
64
+ )
65
+ ] });
66
+ }
67
+ function TableBlock({ block, onAction }) {
68
+ const columns = Array.isArray(block.columns) ? block.columns : [];
69
+ const rows = Array.isArray(block.rows) ? block.rows : [];
70
+ const download = () => onAction({
71
+ type: "DOWNLOAD",
72
+ format: "CSV",
73
+ filename: `${block.title ?? "table"}.csv`,
74
+ data: rowsToCsv(columns, rows),
75
+ blockId: block.id
76
+ });
77
+ return /* @__PURE__ */ jsxs("section", { className: "rk-block rk-block-table", children: [
78
+ /* @__PURE__ */ jsxs("div", { className: "rk-block-header", children: [
79
+ block.title ? /* @__PURE__ */ jsx("h3", { className: "rk-block-title", children: block.title }) : null,
80
+ rows.length > 0 ? /* @__PURE__ */ jsx("button", { type: "button", className: "rk-action", onClick: download, children: "Download CSV" }) : null
81
+ ] }),
82
+ /* @__PURE__ */ jsxs("div", { className: "rk-table-scroll", children: [
83
+ /* @__PURE__ */ jsxs("table", { className: "rk-table", children: [
84
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: columns.map((col) => /* @__PURE__ */ jsx("th", { scope: "col", children: col.label }, col.key)) }) }),
85
+ /* @__PURE__ */ jsx("tbody", { children: rows.map((row, r) => /* @__PURE__ */ jsx("tr", { children: columns.map((col) => /* @__PURE__ */ jsx("td", { children: formatValue(row[col.key]) }, col.key)) }, r)) })
86
+ ] }),
87
+ rows.length === 0 ? /* @__PURE__ */ jsx("p", { className: "rk-empty", children: "No data." }) : null
88
+ ] })
89
+ ] });
90
+ }
91
+ var SEVERITY_GLYPH = {
92
+ INFO: "\u2139",
93
+ SUCCESS: "\u2713",
94
+ WARNING: "\u26A0",
95
+ CRITICAL: "\u2715"
96
+ };
97
+ function InsightBlock({ block }) {
98
+ const severity = ["INFO", "SUCCESS", "WARNING", "CRITICAL"].includes(
99
+ block.severity
100
+ ) ? block.severity : "INFO";
101
+ return /* @__PURE__ */ jsxs(
102
+ "aside",
103
+ {
104
+ className: `rk-block rk-block-insight rk-severity-${severity.toLowerCase()}`,
105
+ role: "note",
106
+ children: [
107
+ /* @__PURE__ */ jsx("span", { className: "rk-insight-icon", "aria-hidden": true, children: SEVERITY_GLYPH[severity] }),
108
+ /* @__PURE__ */ jsxs("div", { className: "rk-insight-body", children: [
109
+ /* @__PURE__ */ jsx("div", { className: "rk-insight-title", children: block.title }),
110
+ /* @__PURE__ */ jsx("div", { className: "rk-insight-desc", children: block.description })
111
+ ] })
112
+ ]
113
+ }
114
+ );
115
+ }
116
+ function RecommendationBlock({
117
+ block
118
+ }) {
119
+ const items = Array.isArray(block.items) ? block.items : [];
120
+ return /* @__PURE__ */ jsx("section", { className: "rk-block rk-block-recommendation", children: /* @__PURE__ */ jsx("ul", { className: "rk-recommendation-list", children: items.map((item, i) => /* @__PURE__ */ jsxs("li", { className: "rk-recommendation-item", children: [
121
+ /* @__PURE__ */ jsx("div", { className: "rk-recommendation-title", children: item.title }),
122
+ /* @__PURE__ */ jsx("div", { className: "rk-recommendation-desc", children: item.description })
123
+ ] }, `${item.title}-${i}`)) }) });
124
+ }
125
+ function FilterControl({ filter }) {
126
+ const options = Array.isArray(filter.options) ? filter.options : [];
127
+ switch (filter.filterType) {
128
+ case "SELECT":
129
+ case "MULTI_SELECT":
130
+ return /* @__PURE__ */ jsx("select", { disabled: true, multiple: filter.filterType === "MULTI_SELECT", "aria-label": filter.label, children: options.map((o) => /* @__PURE__ */ jsx("option", { value: o, children: o }, o)) });
131
+ case "DATE_RANGE":
132
+ return /* @__PURE__ */ jsxs("span", { className: "rk-filter-range", children: [
133
+ /* @__PURE__ */ jsx("input", { type: "date", disabled: true, "aria-label": `${filter.label} from` }),
134
+ /* @__PURE__ */ jsx("input", { type: "date", disabled: true, "aria-label": `${filter.label} to` })
135
+ ] });
136
+ case "NUMBER_RANGE":
137
+ return /* @__PURE__ */ jsxs("span", { className: "rk-filter-range", children: [
138
+ /* @__PURE__ */ jsx("input", { type: "number", disabled: true, "aria-label": `${filter.label} min`, placeholder: "min" }),
139
+ /* @__PURE__ */ jsx("input", { type: "number", disabled: true, "aria-label": `${filter.label} max`, placeholder: "max" })
140
+ ] });
141
+ case "SEARCH":
142
+ default:
143
+ return /* @__PURE__ */ jsx("input", { type: "search", disabled: true, "aria-label": filter.label, placeholder: "Search\u2026" });
144
+ }
145
+ }
146
+ function FilterBlock({ block }) {
147
+ const filters = Array.isArray(block.filters) ? block.filters : [];
148
+ return /* @__PURE__ */ jsx("section", { className: "rk-block rk-block-filter", "aria-label": "Filters (read-only)", children: /* @__PURE__ */ jsx("div", { className: "rk-filter-row", children: filters.map((filter, i) => /* @__PURE__ */ jsxs("label", { className: "rk-filter", children: [
149
+ /* @__PURE__ */ jsx("span", { className: "rk-filter-label", children: filter.label }),
150
+ /* @__PURE__ */ jsx(FilterControl, { filter })
151
+ ] }, `${filter.field}-${i}`)) }) });
152
+ }
153
+ function FallbackBlock({ block }) {
154
+ const type = typeof block?.type === "string" ? block.type : "unknown";
155
+ return /* @__PURE__ */ jsxs("div", { className: "rk-block rk-block-fallback", role: "note", children: [
156
+ /* @__PURE__ */ jsxs("div", { className: "rk-fallback-label", children: [
157
+ "Unsupported block: ",
158
+ type
159
+ ] }),
160
+ isDev() ? /* @__PURE__ */ jsxs("details", { className: "rk-fallback-raw", children: [
161
+ /* @__PURE__ */ jsx("summary", { children: "Raw payload (dev only)" }),
162
+ /* @__PURE__ */ jsx("pre", { children: safeStringify(block) })
163
+ ] }) : null
164
+ ] });
165
+ }
166
+ function safeStringify(value) {
167
+ try {
168
+ return JSON.stringify(value, null, 2);
169
+ } catch {
170
+ return String(value);
171
+ }
172
+ }
173
+
174
+ // src/blocks/index.ts
175
+ var defaultBlockComponents = {
176
+ TEXT: TextBlock,
177
+ KPI: KpiBlock,
178
+ CHART: ChartBlock,
179
+ TABLE: TableBlock,
180
+ INSIGHT: InsightBlock,
181
+ RECOMMENDATION: RecommendationBlock,
182
+ FILTER: FilterBlock
183
+ };
184
+
185
+ // src/registry.ts
186
+ var globalRegistry = /* @__PURE__ */ new Map();
187
+ function registerBlock(options) {
188
+ if (!options.override && globalRegistry.has(options.type)) return;
189
+ globalRegistry.set(options.type, options.component);
190
+ }
191
+ function unregisterBlock(type) {
192
+ globalRegistry.delete(type);
193
+ }
194
+ function registeredBlockTypes() {
195
+ return [...globalRegistry.keys()];
196
+ }
197
+ function resolveBlockComponent(type, overrides) {
198
+ return overrides?.[type] ?? globalRegistry.get(type) ?? defaultBlockComponents[type] ?? FallbackBlock;
199
+ }
200
+ var ErrorBoundary = class extends Component {
201
+ constructor() {
202
+ super(...arguments);
203
+ this.state = { error: null };
204
+ }
205
+ static getDerivedStateFromError(error) {
206
+ return { error };
207
+ }
208
+ componentDidCatch(error, info) {
209
+ this.props.onError?.(error, info);
210
+ }
211
+ render() {
212
+ if (this.state.error) return this.props.fallback(this.state.error);
213
+ return this.props.children;
214
+ }
215
+ };
216
+ function AiRenderer({
217
+ response,
218
+ components,
219
+ onAction = noopAction,
220
+ className
221
+ }) {
222
+ if (!response || typeof response !== "object" || !("type" in response)) {
223
+ return /* @__PURE__ */ jsx(ErrorView, { message: "No response to display." });
224
+ }
225
+ return /* @__PURE__ */ jsxs("div", { className: className ?? "rk-response", "data-response-type": response.type, children: [
226
+ renderBody(response, components, onAction),
227
+ /* @__PURE__ */ jsx(MetadataFooter, { metadata: response.metadata, onAction, responseId: response.id })
228
+ ] });
229
+ }
230
+ function renderBody(response, components, onAction) {
231
+ switch (response.type) {
232
+ case "TEXT": {
233
+ const { format, value } = response.content;
234
+ return format === "MARKDOWN" ? /* @__PURE__ */ jsx(Markdown, { children: value }) : /* @__PURE__ */ jsx("p", { className: "rk-text-plain", children: value });
235
+ }
236
+ case "ANALYTICS": {
237
+ const { title, blocks } = response.content;
238
+ const list = Array.isArray(blocks) ? blocks : [];
239
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
240
+ title ? /* @__PURE__ */ jsx("h2", { className: "rk-response-title", children: title }) : null,
241
+ /* @__PURE__ */ jsx("div", { className: "rk-blocks", children: list.map((block, i) => /* @__PURE__ */ jsx(
242
+ BlockSlot,
243
+ {
244
+ block,
245
+ components,
246
+ onAction
247
+ },
248
+ blockKey(block, i)
249
+ )) })
250
+ ] });
251
+ }
252
+ case "ERROR":
253
+ return /* @__PURE__ */ jsx(ErrorView, { message: response.content.message });
254
+ default:
255
+ return /* @__PURE__ */ jsx(ErrorView, { message: "Unsupported response type." });
256
+ }
257
+ }
258
+ function BlockSlot({
259
+ block,
260
+ components,
261
+ onAction
262
+ }) {
263
+ const type = typeof block?.type === "string" ? block.type : "UNKNOWN";
264
+ const Component2 = resolveBlockComponent(type, components);
265
+ return /* @__PURE__ */ jsx(ErrorBoundary, { fallback: () => /* @__PURE__ */ jsx(FallbackBlock, { block, onAction }), children: /* @__PURE__ */ jsx(Component2, { block, onAction }) });
266
+ }
267
+ function ErrorView({ message }) {
268
+ return /* @__PURE__ */ jsxs("div", { className: "rk-block rk-error", role: "alert", children: [
269
+ /* @__PURE__ */ jsx("span", { className: "rk-error-icon", "aria-hidden": true, children: "\u2715" }),
270
+ /* @__PURE__ */ jsx("span", { className: "rk-error-message", children: message })
271
+ ] });
272
+ }
273
+ function MetadataFooter({
274
+ metadata,
275
+ onAction,
276
+ responseId
277
+ }) {
278
+ if (!metadata) return null;
279
+ const { generatedAt, dataSource, refreshable } = metadata;
280
+ if (!generatedAt && !dataSource && !refreshable) return null;
281
+ return /* @__PURE__ */ jsxs("footer", { className: "rk-meta", children: [
282
+ generatedAt ? /* @__PURE__ */ jsx("span", { className: "rk-meta-time", children: formatTime(generatedAt) }) : null,
283
+ dataSource ? /* @__PURE__ */ jsx("span", { className: "rk-meta-source", children: dataSource }) : null,
284
+ refreshable ? /* @__PURE__ */ jsx(
285
+ "button",
286
+ {
287
+ type: "button",
288
+ className: "rk-action rk-meta-refresh",
289
+ onClick: () => onAction({ type: "REFRESH", responseId }),
290
+ children: "Refresh"
291
+ }
292
+ ) : null
293
+ ] });
294
+ }
295
+ function formatTime(iso) {
296
+ const d = new Date(iso);
297
+ return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
298
+ }
299
+ function blockKey(block, index) {
300
+ return typeof block?.id === "string" && block.id ? block.id : `block-${index}`;
301
+ }
302
+
303
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
304
+ var external_exports = {};
305
+ __export(external_exports, {
306
+ BRAND: () => BRAND,
307
+ DIRTY: () => DIRTY,
308
+ EMPTY_PATH: () => EMPTY_PATH,
309
+ INVALID: () => INVALID,
310
+ NEVER: () => NEVER,
311
+ OK: () => OK,
312
+ ParseStatus: () => ParseStatus,
313
+ Schema: () => ZodType,
314
+ ZodAny: () => ZodAny,
315
+ ZodArray: () => ZodArray,
316
+ ZodBigInt: () => ZodBigInt,
317
+ ZodBoolean: () => ZodBoolean,
318
+ ZodBranded: () => ZodBranded,
319
+ ZodCatch: () => ZodCatch,
320
+ ZodDate: () => ZodDate,
321
+ ZodDefault: () => ZodDefault,
322
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
323
+ ZodEffects: () => ZodEffects,
324
+ ZodEnum: () => ZodEnum,
325
+ ZodError: () => ZodError,
326
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
327
+ ZodFunction: () => ZodFunction,
328
+ ZodIntersection: () => ZodIntersection,
329
+ ZodIssueCode: () => ZodIssueCode,
330
+ ZodLazy: () => ZodLazy,
331
+ ZodLiteral: () => ZodLiteral,
332
+ ZodMap: () => ZodMap,
333
+ ZodNaN: () => ZodNaN,
334
+ ZodNativeEnum: () => ZodNativeEnum,
335
+ ZodNever: () => ZodNever,
336
+ ZodNull: () => ZodNull,
337
+ ZodNullable: () => ZodNullable,
338
+ ZodNumber: () => ZodNumber,
339
+ ZodObject: () => ZodObject,
340
+ ZodOptional: () => ZodOptional,
341
+ ZodParsedType: () => ZodParsedType,
342
+ ZodPipeline: () => ZodPipeline,
343
+ ZodPromise: () => ZodPromise,
344
+ ZodReadonly: () => ZodReadonly,
345
+ ZodRecord: () => ZodRecord,
346
+ ZodSchema: () => ZodType,
347
+ ZodSet: () => ZodSet,
348
+ ZodString: () => ZodString,
349
+ ZodSymbol: () => ZodSymbol,
350
+ ZodTransformer: () => ZodEffects,
351
+ ZodTuple: () => ZodTuple,
352
+ ZodType: () => ZodType,
353
+ ZodUndefined: () => ZodUndefined,
354
+ ZodUnion: () => ZodUnion,
355
+ ZodUnknown: () => ZodUnknown,
356
+ ZodVoid: () => ZodVoid,
357
+ addIssueToContext: () => addIssueToContext,
358
+ any: () => anyType,
359
+ array: () => arrayType,
360
+ bigint: () => bigIntType,
361
+ boolean: () => booleanType,
362
+ coerce: () => coerce,
363
+ custom: () => custom,
364
+ date: () => dateType,
365
+ datetimeRegex: () => datetimeRegex,
366
+ defaultErrorMap: () => en_default,
367
+ discriminatedUnion: () => discriminatedUnionType,
368
+ effect: () => effectsType,
369
+ enum: () => enumType,
370
+ function: () => functionType,
371
+ getErrorMap: () => getErrorMap,
372
+ getParsedType: () => getParsedType,
373
+ instanceof: () => instanceOfType,
374
+ intersection: () => intersectionType,
375
+ isAborted: () => isAborted,
376
+ isAsync: () => isAsync,
377
+ isDirty: () => isDirty,
378
+ isValid: () => isValid,
379
+ late: () => late,
380
+ lazy: () => lazyType,
381
+ literal: () => literalType,
382
+ makeIssue: () => makeIssue,
383
+ map: () => mapType,
384
+ nan: () => nanType,
385
+ nativeEnum: () => nativeEnumType,
386
+ never: () => neverType,
387
+ null: () => nullType,
388
+ nullable: () => nullableType,
389
+ number: () => numberType,
390
+ object: () => objectType,
391
+ objectUtil: () => objectUtil,
392
+ oboolean: () => oboolean,
393
+ onumber: () => onumber,
394
+ optional: () => optionalType,
395
+ ostring: () => ostring,
396
+ pipeline: () => pipelineType,
397
+ preprocess: () => preprocessType,
398
+ promise: () => promiseType,
399
+ quotelessJson: () => quotelessJson,
400
+ record: () => recordType,
401
+ set: () => setType,
402
+ setErrorMap: () => setErrorMap,
403
+ strictObject: () => strictObjectType,
404
+ string: () => stringType,
405
+ symbol: () => symbolType,
406
+ transformer: () => effectsType,
407
+ tuple: () => tupleType,
408
+ undefined: () => undefinedType,
409
+ union: () => unionType,
410
+ unknown: () => unknownType,
411
+ util: () => util,
412
+ void: () => voidType
413
+ });
414
+
415
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
416
+ var util;
417
+ (function(util2) {
418
+ util2.assertEqual = (_) => {
419
+ };
420
+ function assertIs(_arg) {
421
+ }
422
+ util2.assertIs = assertIs;
423
+ function assertNever(_x) {
424
+ throw new Error();
425
+ }
426
+ util2.assertNever = assertNever;
427
+ util2.arrayToEnum = (items) => {
428
+ const obj = {};
429
+ for (const item of items) {
430
+ obj[item] = item;
431
+ }
432
+ return obj;
433
+ };
434
+ util2.getValidEnumValues = (obj) => {
435
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
436
+ const filtered = {};
437
+ for (const k of validKeys) {
438
+ filtered[k] = obj[k];
439
+ }
440
+ return util2.objectValues(filtered);
441
+ };
442
+ util2.objectValues = (obj) => {
443
+ return util2.objectKeys(obj).map(function(e) {
444
+ return obj[e];
445
+ });
446
+ };
447
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
448
+ const keys = [];
449
+ for (const key in object) {
450
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
451
+ keys.push(key);
452
+ }
453
+ }
454
+ return keys;
455
+ };
456
+ util2.find = (arr, checker) => {
457
+ for (const item of arr) {
458
+ if (checker(item))
459
+ return item;
460
+ }
461
+ return void 0;
462
+ };
463
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
464
+ function joinValues(array, separator = " | ") {
465
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
466
+ }
467
+ util2.joinValues = joinValues;
468
+ util2.jsonStringifyReplacer = (_, value) => {
469
+ if (typeof value === "bigint") {
470
+ return value.toString();
471
+ }
472
+ return value;
473
+ };
474
+ })(util || (util = {}));
475
+ var objectUtil;
476
+ (function(objectUtil2) {
477
+ objectUtil2.mergeShapes = (first, second) => {
478
+ return {
479
+ ...first,
480
+ ...second
481
+ // second overwrites first
482
+ };
483
+ };
484
+ })(objectUtil || (objectUtil = {}));
485
+ var ZodParsedType = util.arrayToEnum([
486
+ "string",
487
+ "nan",
488
+ "number",
489
+ "integer",
490
+ "float",
491
+ "boolean",
492
+ "date",
493
+ "bigint",
494
+ "symbol",
495
+ "function",
496
+ "undefined",
497
+ "null",
498
+ "array",
499
+ "object",
500
+ "unknown",
501
+ "promise",
502
+ "void",
503
+ "never",
504
+ "map",
505
+ "set"
506
+ ]);
507
+ var getParsedType = (data) => {
508
+ const t = typeof data;
509
+ switch (t) {
510
+ case "undefined":
511
+ return ZodParsedType.undefined;
512
+ case "string":
513
+ return ZodParsedType.string;
514
+ case "number":
515
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
516
+ case "boolean":
517
+ return ZodParsedType.boolean;
518
+ case "function":
519
+ return ZodParsedType.function;
520
+ case "bigint":
521
+ return ZodParsedType.bigint;
522
+ case "symbol":
523
+ return ZodParsedType.symbol;
524
+ case "object":
525
+ if (Array.isArray(data)) {
526
+ return ZodParsedType.array;
527
+ }
528
+ if (data === null) {
529
+ return ZodParsedType.null;
530
+ }
531
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
532
+ return ZodParsedType.promise;
533
+ }
534
+ if (typeof Map !== "undefined" && data instanceof Map) {
535
+ return ZodParsedType.map;
536
+ }
537
+ if (typeof Set !== "undefined" && data instanceof Set) {
538
+ return ZodParsedType.set;
539
+ }
540
+ if (typeof Date !== "undefined" && data instanceof Date) {
541
+ return ZodParsedType.date;
542
+ }
543
+ return ZodParsedType.object;
544
+ default:
545
+ return ZodParsedType.unknown;
546
+ }
547
+ };
548
+
549
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
550
+ var ZodIssueCode = util.arrayToEnum([
551
+ "invalid_type",
552
+ "invalid_literal",
553
+ "custom",
554
+ "invalid_union",
555
+ "invalid_union_discriminator",
556
+ "invalid_enum_value",
557
+ "unrecognized_keys",
558
+ "invalid_arguments",
559
+ "invalid_return_type",
560
+ "invalid_date",
561
+ "invalid_string",
562
+ "too_small",
563
+ "too_big",
564
+ "invalid_intersection_types",
565
+ "not_multiple_of",
566
+ "not_finite"
567
+ ]);
568
+ var quotelessJson = (obj) => {
569
+ const json = JSON.stringify(obj, null, 2);
570
+ return json.replace(/"([^"]+)":/g, "$1:");
571
+ };
572
+ var ZodError = class _ZodError extends Error {
573
+ get errors() {
574
+ return this.issues;
575
+ }
576
+ constructor(issues) {
577
+ super();
578
+ this.issues = [];
579
+ this.addIssue = (sub) => {
580
+ this.issues = [...this.issues, sub];
581
+ };
582
+ this.addIssues = (subs = []) => {
583
+ this.issues = [...this.issues, ...subs];
584
+ };
585
+ const actualProto = new.target.prototype;
586
+ if (Object.setPrototypeOf) {
587
+ Object.setPrototypeOf(this, actualProto);
588
+ } else {
589
+ this.__proto__ = actualProto;
590
+ }
591
+ this.name = "ZodError";
592
+ this.issues = issues;
593
+ }
594
+ format(_mapper) {
595
+ const mapper = _mapper || function(issue) {
596
+ return issue.message;
597
+ };
598
+ const fieldErrors = { _errors: [] };
599
+ const processError = (error) => {
600
+ for (const issue of error.issues) {
601
+ if (issue.code === "invalid_union") {
602
+ issue.unionErrors.map(processError);
603
+ } else if (issue.code === "invalid_return_type") {
604
+ processError(issue.returnTypeError);
605
+ } else if (issue.code === "invalid_arguments") {
606
+ processError(issue.argumentsError);
607
+ } else if (issue.path.length === 0) {
608
+ fieldErrors._errors.push(mapper(issue));
609
+ } else {
610
+ let curr = fieldErrors;
611
+ let i = 0;
612
+ while (i < issue.path.length) {
613
+ const el = issue.path[i];
614
+ const terminal = i === issue.path.length - 1;
615
+ if (!terminal) {
616
+ curr[el] = curr[el] || { _errors: [] };
617
+ } else {
618
+ curr[el] = curr[el] || { _errors: [] };
619
+ curr[el]._errors.push(mapper(issue));
620
+ }
621
+ curr = curr[el];
622
+ i++;
623
+ }
624
+ }
625
+ }
626
+ };
627
+ processError(this);
628
+ return fieldErrors;
629
+ }
630
+ static assert(value) {
631
+ if (!(value instanceof _ZodError)) {
632
+ throw new Error(`Not a ZodError: ${value}`);
633
+ }
634
+ }
635
+ toString() {
636
+ return this.message;
637
+ }
638
+ get message() {
639
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
640
+ }
641
+ get isEmpty() {
642
+ return this.issues.length === 0;
643
+ }
644
+ flatten(mapper = (issue) => issue.message) {
645
+ const fieldErrors = {};
646
+ const formErrors = [];
647
+ for (const sub of this.issues) {
648
+ if (sub.path.length > 0) {
649
+ const firstEl = sub.path[0];
650
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
651
+ fieldErrors[firstEl].push(mapper(sub));
652
+ } else {
653
+ formErrors.push(mapper(sub));
654
+ }
655
+ }
656
+ return { formErrors, fieldErrors };
657
+ }
658
+ get formErrors() {
659
+ return this.flatten();
660
+ }
661
+ };
662
+ ZodError.create = (issues) => {
663
+ const error = new ZodError(issues);
664
+ return error;
665
+ };
666
+
667
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
668
+ var errorMap = (issue, _ctx) => {
669
+ let message;
670
+ switch (issue.code) {
671
+ case ZodIssueCode.invalid_type:
672
+ if (issue.received === ZodParsedType.undefined) {
673
+ message = "Required";
674
+ } else {
675
+ message = `Expected ${issue.expected}, received ${issue.received}`;
676
+ }
677
+ break;
678
+ case ZodIssueCode.invalid_literal:
679
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
680
+ break;
681
+ case ZodIssueCode.unrecognized_keys:
682
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
683
+ break;
684
+ case ZodIssueCode.invalid_union:
685
+ message = `Invalid input`;
686
+ break;
687
+ case ZodIssueCode.invalid_union_discriminator:
688
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
689
+ break;
690
+ case ZodIssueCode.invalid_enum_value:
691
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
692
+ break;
693
+ case ZodIssueCode.invalid_arguments:
694
+ message = `Invalid function arguments`;
695
+ break;
696
+ case ZodIssueCode.invalid_return_type:
697
+ message = `Invalid function return type`;
698
+ break;
699
+ case ZodIssueCode.invalid_date:
700
+ message = `Invalid date`;
701
+ break;
702
+ case ZodIssueCode.invalid_string:
703
+ if (typeof issue.validation === "object") {
704
+ if ("includes" in issue.validation) {
705
+ message = `Invalid input: must include "${issue.validation.includes}"`;
706
+ if (typeof issue.validation.position === "number") {
707
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
708
+ }
709
+ } else if ("startsWith" in issue.validation) {
710
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
711
+ } else if ("endsWith" in issue.validation) {
712
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
713
+ } else {
714
+ util.assertNever(issue.validation);
715
+ }
716
+ } else if (issue.validation !== "regex") {
717
+ message = `Invalid ${issue.validation}`;
718
+ } else {
719
+ message = "Invalid";
720
+ }
721
+ break;
722
+ case ZodIssueCode.too_small:
723
+ if (issue.type === "array")
724
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
725
+ else if (issue.type === "string")
726
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
727
+ else if (issue.type === "number")
728
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
729
+ else if (issue.type === "bigint")
730
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
731
+ else if (issue.type === "date")
732
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
733
+ else
734
+ message = "Invalid input";
735
+ break;
736
+ case ZodIssueCode.too_big:
737
+ if (issue.type === "array")
738
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
739
+ else if (issue.type === "string")
740
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
741
+ else if (issue.type === "number")
742
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
743
+ else if (issue.type === "bigint")
744
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
745
+ else if (issue.type === "date")
746
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
747
+ else
748
+ message = "Invalid input";
749
+ break;
750
+ case ZodIssueCode.custom:
751
+ message = `Invalid input`;
752
+ break;
753
+ case ZodIssueCode.invalid_intersection_types:
754
+ message = `Intersection results could not be merged`;
755
+ break;
756
+ case ZodIssueCode.not_multiple_of:
757
+ message = `Number must be a multiple of ${issue.multipleOf}`;
758
+ break;
759
+ case ZodIssueCode.not_finite:
760
+ message = "Number must be finite";
761
+ break;
762
+ default:
763
+ message = _ctx.defaultError;
764
+ util.assertNever(issue);
765
+ }
766
+ return { message };
767
+ };
768
+ var en_default = errorMap;
769
+
770
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
771
+ var overrideErrorMap = en_default;
772
+ function setErrorMap(map) {
773
+ overrideErrorMap = map;
774
+ }
775
+ function getErrorMap() {
776
+ return overrideErrorMap;
777
+ }
778
+
779
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
780
+ var makeIssue = (params) => {
781
+ const { data, path, errorMaps, issueData } = params;
782
+ const fullPath = [...path, ...issueData.path || []];
783
+ const fullIssue = {
784
+ ...issueData,
785
+ path: fullPath
786
+ };
787
+ if (issueData.message !== void 0) {
788
+ return {
789
+ ...issueData,
790
+ path: fullPath,
791
+ message: issueData.message
792
+ };
793
+ }
794
+ let errorMessage = "";
795
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
796
+ for (const map of maps) {
797
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
798
+ }
799
+ return {
800
+ ...issueData,
801
+ path: fullPath,
802
+ message: errorMessage
803
+ };
804
+ };
805
+ var EMPTY_PATH = [];
806
+ function addIssueToContext(ctx, issueData) {
807
+ const overrideMap = getErrorMap();
808
+ const issue = makeIssue({
809
+ issueData,
810
+ data: ctx.data,
811
+ path: ctx.path,
812
+ errorMaps: [
813
+ ctx.common.contextualErrorMap,
814
+ // contextual error map is first priority
815
+ ctx.schemaErrorMap,
816
+ // then schema-bound map if available
817
+ overrideMap,
818
+ // then global override map
819
+ overrideMap === en_default ? void 0 : en_default
820
+ // then global default map
821
+ ].filter((x) => !!x)
822
+ });
823
+ ctx.common.issues.push(issue);
824
+ }
825
+ var ParseStatus = class _ParseStatus {
826
+ constructor() {
827
+ this.value = "valid";
828
+ }
829
+ dirty() {
830
+ if (this.value === "valid")
831
+ this.value = "dirty";
832
+ }
833
+ abort() {
834
+ if (this.value !== "aborted")
835
+ this.value = "aborted";
836
+ }
837
+ static mergeArray(status, results) {
838
+ const arrayValue = [];
839
+ for (const s of results) {
840
+ if (s.status === "aborted")
841
+ return INVALID;
842
+ if (s.status === "dirty")
843
+ status.dirty();
844
+ arrayValue.push(s.value);
845
+ }
846
+ return { status: status.value, value: arrayValue };
847
+ }
848
+ static async mergeObjectAsync(status, pairs) {
849
+ const syncPairs = [];
850
+ for (const pair of pairs) {
851
+ const key = await pair.key;
852
+ const value = await pair.value;
853
+ syncPairs.push({
854
+ key,
855
+ value
856
+ });
857
+ }
858
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
859
+ }
860
+ static mergeObjectSync(status, pairs) {
861
+ const finalObject = {};
862
+ for (const pair of pairs) {
863
+ const { key, value } = pair;
864
+ if (key.status === "aborted")
865
+ return INVALID;
866
+ if (value.status === "aborted")
867
+ return INVALID;
868
+ if (key.status === "dirty")
869
+ status.dirty();
870
+ if (value.status === "dirty")
871
+ status.dirty();
872
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
873
+ finalObject[key.value] = value.value;
874
+ }
875
+ }
876
+ return { status: status.value, value: finalObject };
877
+ }
878
+ };
879
+ var INVALID = Object.freeze({
880
+ status: "aborted"
881
+ });
882
+ var DIRTY = (value) => ({ status: "dirty", value });
883
+ var OK = (value) => ({ status: "valid", value });
884
+ var isAborted = (x) => x.status === "aborted";
885
+ var isDirty = (x) => x.status === "dirty";
886
+ var isValid = (x) => x.status === "valid";
887
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
888
+
889
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
890
+ var errorUtil;
891
+ (function(errorUtil2) {
892
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
893
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
894
+ })(errorUtil || (errorUtil = {}));
895
+
896
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
897
+ var ParseInputLazyPath = class {
898
+ constructor(parent, value, path, key) {
899
+ this._cachedPath = [];
900
+ this.parent = parent;
901
+ this.data = value;
902
+ this._path = path;
903
+ this._key = key;
904
+ }
905
+ get path() {
906
+ if (!this._cachedPath.length) {
907
+ if (Array.isArray(this._key)) {
908
+ this._cachedPath.push(...this._path, ...this._key);
909
+ } else {
910
+ this._cachedPath.push(...this._path, this._key);
911
+ }
912
+ }
913
+ return this._cachedPath;
914
+ }
915
+ };
916
+ var handleResult = (ctx, result) => {
917
+ if (isValid(result)) {
918
+ return { success: true, data: result.value };
919
+ } else {
920
+ if (!ctx.common.issues.length) {
921
+ throw new Error("Validation failed but no issues detected.");
922
+ }
923
+ return {
924
+ success: false,
925
+ get error() {
926
+ if (this._error)
927
+ return this._error;
928
+ const error = new ZodError(ctx.common.issues);
929
+ this._error = error;
930
+ return this._error;
931
+ }
932
+ };
933
+ }
934
+ };
935
+ function processCreateParams(params) {
936
+ if (!params)
937
+ return {};
938
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
939
+ if (errorMap2 && (invalid_type_error || required_error)) {
940
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
941
+ }
942
+ if (errorMap2)
943
+ return { errorMap: errorMap2, description };
944
+ const customMap = (iss, ctx) => {
945
+ const { message } = params;
946
+ if (iss.code === "invalid_enum_value") {
947
+ return { message: message ?? ctx.defaultError };
948
+ }
949
+ if (typeof ctx.data === "undefined") {
950
+ return { message: message ?? required_error ?? ctx.defaultError };
951
+ }
952
+ if (iss.code !== "invalid_type")
953
+ return { message: ctx.defaultError };
954
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
955
+ };
956
+ return { errorMap: customMap, description };
957
+ }
958
+ var ZodType = class {
959
+ get description() {
960
+ return this._def.description;
961
+ }
962
+ _getType(input) {
963
+ return getParsedType(input.data);
964
+ }
965
+ _getOrReturnCtx(input, ctx) {
966
+ return ctx || {
967
+ common: input.parent.common,
968
+ data: input.data,
969
+ parsedType: getParsedType(input.data),
970
+ schemaErrorMap: this._def.errorMap,
971
+ path: input.path,
972
+ parent: input.parent
973
+ };
974
+ }
975
+ _processInputParams(input) {
976
+ return {
977
+ status: new ParseStatus(),
978
+ ctx: {
979
+ common: input.parent.common,
980
+ data: input.data,
981
+ parsedType: getParsedType(input.data),
982
+ schemaErrorMap: this._def.errorMap,
983
+ path: input.path,
984
+ parent: input.parent
985
+ }
986
+ };
987
+ }
988
+ _parseSync(input) {
989
+ const result = this._parse(input);
990
+ if (isAsync(result)) {
991
+ throw new Error("Synchronous parse encountered promise.");
992
+ }
993
+ return result;
994
+ }
995
+ _parseAsync(input) {
996
+ const result = this._parse(input);
997
+ return Promise.resolve(result);
998
+ }
999
+ parse(data, params) {
1000
+ const result = this.safeParse(data, params);
1001
+ if (result.success)
1002
+ return result.data;
1003
+ throw result.error;
1004
+ }
1005
+ safeParse(data, params) {
1006
+ const ctx = {
1007
+ common: {
1008
+ issues: [],
1009
+ async: params?.async ?? false,
1010
+ contextualErrorMap: params?.errorMap
1011
+ },
1012
+ path: params?.path || [],
1013
+ schemaErrorMap: this._def.errorMap,
1014
+ parent: null,
1015
+ data,
1016
+ parsedType: getParsedType(data)
1017
+ };
1018
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1019
+ return handleResult(ctx, result);
1020
+ }
1021
+ "~validate"(data) {
1022
+ const ctx = {
1023
+ common: {
1024
+ issues: [],
1025
+ async: !!this["~standard"].async
1026
+ },
1027
+ path: [],
1028
+ schemaErrorMap: this._def.errorMap,
1029
+ parent: null,
1030
+ data,
1031
+ parsedType: getParsedType(data)
1032
+ };
1033
+ if (!this["~standard"].async) {
1034
+ try {
1035
+ const result = this._parseSync({ data, path: [], parent: ctx });
1036
+ return isValid(result) ? {
1037
+ value: result.value
1038
+ } : {
1039
+ issues: ctx.common.issues
1040
+ };
1041
+ } catch (err) {
1042
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1043
+ this["~standard"].async = true;
1044
+ }
1045
+ ctx.common = {
1046
+ issues: [],
1047
+ async: true
1048
+ };
1049
+ }
1050
+ }
1051
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1052
+ value: result.value
1053
+ } : {
1054
+ issues: ctx.common.issues
1055
+ });
1056
+ }
1057
+ async parseAsync(data, params) {
1058
+ const result = await this.safeParseAsync(data, params);
1059
+ if (result.success)
1060
+ return result.data;
1061
+ throw result.error;
1062
+ }
1063
+ async safeParseAsync(data, params) {
1064
+ const ctx = {
1065
+ common: {
1066
+ issues: [],
1067
+ contextualErrorMap: params?.errorMap,
1068
+ async: true
1069
+ },
1070
+ path: params?.path || [],
1071
+ schemaErrorMap: this._def.errorMap,
1072
+ parent: null,
1073
+ data,
1074
+ parsedType: getParsedType(data)
1075
+ };
1076
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1077
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1078
+ return handleResult(ctx, result);
1079
+ }
1080
+ refine(check, message) {
1081
+ const getIssueProperties = (val) => {
1082
+ if (typeof message === "string" || typeof message === "undefined") {
1083
+ return { message };
1084
+ } else if (typeof message === "function") {
1085
+ return message(val);
1086
+ } else {
1087
+ return message;
1088
+ }
1089
+ };
1090
+ return this._refinement((val, ctx) => {
1091
+ const result = check(val);
1092
+ const setError = () => ctx.addIssue({
1093
+ code: ZodIssueCode.custom,
1094
+ ...getIssueProperties(val)
1095
+ });
1096
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1097
+ return result.then((data) => {
1098
+ if (!data) {
1099
+ setError();
1100
+ return false;
1101
+ } else {
1102
+ return true;
1103
+ }
1104
+ });
1105
+ }
1106
+ if (!result) {
1107
+ setError();
1108
+ return false;
1109
+ } else {
1110
+ return true;
1111
+ }
1112
+ });
1113
+ }
1114
+ refinement(check, refinementData) {
1115
+ return this._refinement((val, ctx) => {
1116
+ if (!check(val)) {
1117
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1118
+ return false;
1119
+ } else {
1120
+ return true;
1121
+ }
1122
+ });
1123
+ }
1124
+ _refinement(refinement) {
1125
+ return new ZodEffects({
1126
+ schema: this,
1127
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1128
+ effect: { type: "refinement", refinement }
1129
+ });
1130
+ }
1131
+ superRefine(refinement) {
1132
+ return this._refinement(refinement);
1133
+ }
1134
+ constructor(def) {
1135
+ this.spa = this.safeParseAsync;
1136
+ this._def = def;
1137
+ this.parse = this.parse.bind(this);
1138
+ this.safeParse = this.safeParse.bind(this);
1139
+ this.parseAsync = this.parseAsync.bind(this);
1140
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1141
+ this.spa = this.spa.bind(this);
1142
+ this.refine = this.refine.bind(this);
1143
+ this.refinement = this.refinement.bind(this);
1144
+ this.superRefine = this.superRefine.bind(this);
1145
+ this.optional = this.optional.bind(this);
1146
+ this.nullable = this.nullable.bind(this);
1147
+ this.nullish = this.nullish.bind(this);
1148
+ this.array = this.array.bind(this);
1149
+ this.promise = this.promise.bind(this);
1150
+ this.or = this.or.bind(this);
1151
+ this.and = this.and.bind(this);
1152
+ this.transform = this.transform.bind(this);
1153
+ this.brand = this.brand.bind(this);
1154
+ this.default = this.default.bind(this);
1155
+ this.catch = this.catch.bind(this);
1156
+ this.describe = this.describe.bind(this);
1157
+ this.pipe = this.pipe.bind(this);
1158
+ this.readonly = this.readonly.bind(this);
1159
+ this.isNullable = this.isNullable.bind(this);
1160
+ this.isOptional = this.isOptional.bind(this);
1161
+ this["~standard"] = {
1162
+ version: 1,
1163
+ vendor: "zod",
1164
+ validate: (data) => this["~validate"](data)
1165
+ };
1166
+ }
1167
+ optional() {
1168
+ return ZodOptional.create(this, this._def);
1169
+ }
1170
+ nullable() {
1171
+ return ZodNullable.create(this, this._def);
1172
+ }
1173
+ nullish() {
1174
+ return this.nullable().optional();
1175
+ }
1176
+ array() {
1177
+ return ZodArray.create(this);
1178
+ }
1179
+ promise() {
1180
+ return ZodPromise.create(this, this._def);
1181
+ }
1182
+ or(option) {
1183
+ return ZodUnion.create([this, option], this._def);
1184
+ }
1185
+ and(incoming) {
1186
+ return ZodIntersection.create(this, incoming, this._def);
1187
+ }
1188
+ transform(transform) {
1189
+ return new ZodEffects({
1190
+ ...processCreateParams(this._def),
1191
+ schema: this,
1192
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1193
+ effect: { type: "transform", transform }
1194
+ });
1195
+ }
1196
+ default(def) {
1197
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1198
+ return new ZodDefault({
1199
+ ...processCreateParams(this._def),
1200
+ innerType: this,
1201
+ defaultValue: defaultValueFunc,
1202
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1203
+ });
1204
+ }
1205
+ brand() {
1206
+ return new ZodBranded({
1207
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1208
+ type: this,
1209
+ ...processCreateParams(this._def)
1210
+ });
1211
+ }
1212
+ catch(def) {
1213
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1214
+ return new ZodCatch({
1215
+ ...processCreateParams(this._def),
1216
+ innerType: this,
1217
+ catchValue: catchValueFunc,
1218
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1219
+ });
1220
+ }
1221
+ describe(description) {
1222
+ const This = this.constructor;
1223
+ return new This({
1224
+ ...this._def,
1225
+ description
1226
+ });
1227
+ }
1228
+ pipe(target) {
1229
+ return ZodPipeline.create(this, target);
1230
+ }
1231
+ readonly() {
1232
+ return ZodReadonly.create(this);
1233
+ }
1234
+ isOptional() {
1235
+ return this.safeParse(void 0).success;
1236
+ }
1237
+ isNullable() {
1238
+ return this.safeParse(null).success;
1239
+ }
1240
+ };
1241
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1242
+ var cuid2Regex = /^[0-9a-z]+$/;
1243
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1244
+ var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1245
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1246
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1247
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1248
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1249
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1250
+ var emojiRegex;
1251
+ var ipv4Regex = /^(?:(?: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])$/;
1252
+ var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/;
1253
+ var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1254
+ var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1255
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1256
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1257
+ var dateRegexSource = `((\\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])))`;
1258
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1259
+ function timeRegexSource(args) {
1260
+ let secondsRegexSource = `[0-5]\\d`;
1261
+ if (args.precision) {
1262
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1263
+ } else if (args.precision == null) {
1264
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1265
+ }
1266
+ const secondsQuantifier = args.precision ? "+" : "?";
1267
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1268
+ }
1269
+ function timeRegex(args) {
1270
+ return new RegExp(`^${timeRegexSource(args)}$`);
1271
+ }
1272
+ function datetimeRegex(args) {
1273
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1274
+ const opts = [];
1275
+ opts.push(args.local ? `Z?` : `Z`);
1276
+ if (args.offset)
1277
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1278
+ regex = `${regex}(${opts.join("|")})`;
1279
+ return new RegExp(`^${regex}$`);
1280
+ }
1281
+ function isValidIP(ip, version) {
1282
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1283
+ return true;
1284
+ }
1285
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1286
+ return true;
1287
+ }
1288
+ return false;
1289
+ }
1290
+ function isValidJWT(jwt, alg) {
1291
+ if (!jwtRegex.test(jwt))
1292
+ return false;
1293
+ try {
1294
+ const [header] = jwt.split(".");
1295
+ if (!header)
1296
+ return false;
1297
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1298
+ const decoded = JSON.parse(atob(base64));
1299
+ if (typeof decoded !== "object" || decoded === null)
1300
+ return false;
1301
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1302
+ return false;
1303
+ if (!decoded.alg)
1304
+ return false;
1305
+ if (alg && decoded.alg !== alg)
1306
+ return false;
1307
+ return true;
1308
+ } catch {
1309
+ return false;
1310
+ }
1311
+ }
1312
+ function isValidCidr(ip, version) {
1313
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1314
+ return true;
1315
+ }
1316
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1317
+ return true;
1318
+ }
1319
+ return false;
1320
+ }
1321
+ var ZodString = class _ZodString extends ZodType {
1322
+ _parse(input) {
1323
+ if (this._def.coerce) {
1324
+ input.data = String(input.data);
1325
+ }
1326
+ const parsedType = this._getType(input);
1327
+ if (parsedType !== ZodParsedType.string) {
1328
+ const ctx2 = this._getOrReturnCtx(input);
1329
+ addIssueToContext(ctx2, {
1330
+ code: ZodIssueCode.invalid_type,
1331
+ expected: ZodParsedType.string,
1332
+ received: ctx2.parsedType
1333
+ });
1334
+ return INVALID;
1335
+ }
1336
+ const status = new ParseStatus();
1337
+ let ctx = void 0;
1338
+ for (const check of this._def.checks) {
1339
+ if (check.kind === "min") {
1340
+ if (input.data.length < check.value) {
1341
+ ctx = this._getOrReturnCtx(input, ctx);
1342
+ addIssueToContext(ctx, {
1343
+ code: ZodIssueCode.too_small,
1344
+ minimum: check.value,
1345
+ type: "string",
1346
+ inclusive: true,
1347
+ exact: false,
1348
+ message: check.message
1349
+ });
1350
+ status.dirty();
1351
+ }
1352
+ } else if (check.kind === "max") {
1353
+ if (input.data.length > check.value) {
1354
+ ctx = this._getOrReturnCtx(input, ctx);
1355
+ addIssueToContext(ctx, {
1356
+ code: ZodIssueCode.too_big,
1357
+ maximum: check.value,
1358
+ type: "string",
1359
+ inclusive: true,
1360
+ exact: false,
1361
+ message: check.message
1362
+ });
1363
+ status.dirty();
1364
+ }
1365
+ } else if (check.kind === "length") {
1366
+ const tooBig = input.data.length > check.value;
1367
+ const tooSmall = input.data.length < check.value;
1368
+ if (tooBig || tooSmall) {
1369
+ ctx = this._getOrReturnCtx(input, ctx);
1370
+ if (tooBig) {
1371
+ addIssueToContext(ctx, {
1372
+ code: ZodIssueCode.too_big,
1373
+ maximum: check.value,
1374
+ type: "string",
1375
+ inclusive: true,
1376
+ exact: true,
1377
+ message: check.message
1378
+ });
1379
+ } else if (tooSmall) {
1380
+ addIssueToContext(ctx, {
1381
+ code: ZodIssueCode.too_small,
1382
+ minimum: check.value,
1383
+ type: "string",
1384
+ inclusive: true,
1385
+ exact: true,
1386
+ message: check.message
1387
+ });
1388
+ }
1389
+ status.dirty();
1390
+ }
1391
+ } else if (check.kind === "email") {
1392
+ if (!emailRegex.test(input.data)) {
1393
+ ctx = this._getOrReturnCtx(input, ctx);
1394
+ addIssueToContext(ctx, {
1395
+ validation: "email",
1396
+ code: ZodIssueCode.invalid_string,
1397
+ message: check.message
1398
+ });
1399
+ status.dirty();
1400
+ }
1401
+ } else if (check.kind === "emoji") {
1402
+ if (!emojiRegex) {
1403
+ emojiRegex = new RegExp(_emojiRegex, "u");
1404
+ }
1405
+ if (!emojiRegex.test(input.data)) {
1406
+ ctx = this._getOrReturnCtx(input, ctx);
1407
+ addIssueToContext(ctx, {
1408
+ validation: "emoji",
1409
+ code: ZodIssueCode.invalid_string,
1410
+ message: check.message
1411
+ });
1412
+ status.dirty();
1413
+ }
1414
+ } else if (check.kind === "uuid") {
1415
+ if (!uuidRegex.test(input.data)) {
1416
+ ctx = this._getOrReturnCtx(input, ctx);
1417
+ addIssueToContext(ctx, {
1418
+ validation: "uuid",
1419
+ code: ZodIssueCode.invalid_string,
1420
+ message: check.message
1421
+ });
1422
+ status.dirty();
1423
+ }
1424
+ } else if (check.kind === "nanoid") {
1425
+ if (!nanoidRegex.test(input.data)) {
1426
+ ctx = this._getOrReturnCtx(input, ctx);
1427
+ addIssueToContext(ctx, {
1428
+ validation: "nanoid",
1429
+ code: ZodIssueCode.invalid_string,
1430
+ message: check.message
1431
+ });
1432
+ status.dirty();
1433
+ }
1434
+ } else if (check.kind === "cuid") {
1435
+ if (!cuidRegex.test(input.data)) {
1436
+ ctx = this._getOrReturnCtx(input, ctx);
1437
+ addIssueToContext(ctx, {
1438
+ validation: "cuid",
1439
+ code: ZodIssueCode.invalid_string,
1440
+ message: check.message
1441
+ });
1442
+ status.dirty();
1443
+ }
1444
+ } else if (check.kind === "cuid2") {
1445
+ if (!cuid2Regex.test(input.data)) {
1446
+ ctx = this._getOrReturnCtx(input, ctx);
1447
+ addIssueToContext(ctx, {
1448
+ validation: "cuid2",
1449
+ code: ZodIssueCode.invalid_string,
1450
+ message: check.message
1451
+ });
1452
+ status.dirty();
1453
+ }
1454
+ } else if (check.kind === "ulid") {
1455
+ if (!ulidRegex.test(input.data)) {
1456
+ ctx = this._getOrReturnCtx(input, ctx);
1457
+ addIssueToContext(ctx, {
1458
+ validation: "ulid",
1459
+ code: ZodIssueCode.invalid_string,
1460
+ message: check.message
1461
+ });
1462
+ status.dirty();
1463
+ }
1464
+ } else if (check.kind === "url") {
1465
+ try {
1466
+ new URL(input.data);
1467
+ } catch {
1468
+ ctx = this._getOrReturnCtx(input, ctx);
1469
+ addIssueToContext(ctx, {
1470
+ validation: "url",
1471
+ code: ZodIssueCode.invalid_string,
1472
+ message: check.message
1473
+ });
1474
+ status.dirty();
1475
+ }
1476
+ } else if (check.kind === "regex") {
1477
+ check.regex.lastIndex = 0;
1478
+ const testResult = check.regex.test(input.data);
1479
+ if (!testResult) {
1480
+ ctx = this._getOrReturnCtx(input, ctx);
1481
+ addIssueToContext(ctx, {
1482
+ validation: "regex",
1483
+ code: ZodIssueCode.invalid_string,
1484
+ message: check.message
1485
+ });
1486
+ status.dirty();
1487
+ }
1488
+ } else if (check.kind === "trim") {
1489
+ input.data = input.data.trim();
1490
+ } else if (check.kind === "includes") {
1491
+ if (!input.data.includes(check.value, check.position)) {
1492
+ ctx = this._getOrReturnCtx(input, ctx);
1493
+ addIssueToContext(ctx, {
1494
+ code: ZodIssueCode.invalid_string,
1495
+ validation: { includes: check.value, position: check.position },
1496
+ message: check.message
1497
+ });
1498
+ status.dirty();
1499
+ }
1500
+ } else if (check.kind === "toLowerCase") {
1501
+ input.data = input.data.toLowerCase();
1502
+ } else if (check.kind === "toUpperCase") {
1503
+ input.data = input.data.toUpperCase();
1504
+ } else if (check.kind === "startsWith") {
1505
+ if (!input.data.startsWith(check.value)) {
1506
+ ctx = this._getOrReturnCtx(input, ctx);
1507
+ addIssueToContext(ctx, {
1508
+ code: ZodIssueCode.invalid_string,
1509
+ validation: { startsWith: check.value },
1510
+ message: check.message
1511
+ });
1512
+ status.dirty();
1513
+ }
1514
+ } else if (check.kind === "endsWith") {
1515
+ if (!input.data.endsWith(check.value)) {
1516
+ ctx = this._getOrReturnCtx(input, ctx);
1517
+ addIssueToContext(ctx, {
1518
+ code: ZodIssueCode.invalid_string,
1519
+ validation: { endsWith: check.value },
1520
+ message: check.message
1521
+ });
1522
+ status.dirty();
1523
+ }
1524
+ } else if (check.kind === "datetime") {
1525
+ const regex = datetimeRegex(check);
1526
+ if (!regex.test(input.data)) {
1527
+ ctx = this._getOrReturnCtx(input, ctx);
1528
+ addIssueToContext(ctx, {
1529
+ code: ZodIssueCode.invalid_string,
1530
+ validation: "datetime",
1531
+ message: check.message
1532
+ });
1533
+ status.dirty();
1534
+ }
1535
+ } else if (check.kind === "date") {
1536
+ const regex = dateRegex;
1537
+ if (!regex.test(input.data)) {
1538
+ ctx = this._getOrReturnCtx(input, ctx);
1539
+ addIssueToContext(ctx, {
1540
+ code: ZodIssueCode.invalid_string,
1541
+ validation: "date",
1542
+ message: check.message
1543
+ });
1544
+ status.dirty();
1545
+ }
1546
+ } else if (check.kind === "time") {
1547
+ const regex = timeRegex(check);
1548
+ if (!regex.test(input.data)) {
1549
+ ctx = this._getOrReturnCtx(input, ctx);
1550
+ addIssueToContext(ctx, {
1551
+ code: ZodIssueCode.invalid_string,
1552
+ validation: "time",
1553
+ message: check.message
1554
+ });
1555
+ status.dirty();
1556
+ }
1557
+ } else if (check.kind === "duration") {
1558
+ if (!durationRegex.test(input.data)) {
1559
+ ctx = this._getOrReturnCtx(input, ctx);
1560
+ addIssueToContext(ctx, {
1561
+ validation: "duration",
1562
+ code: ZodIssueCode.invalid_string,
1563
+ message: check.message
1564
+ });
1565
+ status.dirty();
1566
+ }
1567
+ } else if (check.kind === "ip") {
1568
+ if (!isValidIP(input.data, check.version)) {
1569
+ ctx = this._getOrReturnCtx(input, ctx);
1570
+ addIssueToContext(ctx, {
1571
+ validation: "ip",
1572
+ code: ZodIssueCode.invalid_string,
1573
+ message: check.message
1574
+ });
1575
+ status.dirty();
1576
+ }
1577
+ } else if (check.kind === "jwt") {
1578
+ if (!isValidJWT(input.data, check.alg)) {
1579
+ ctx = this._getOrReturnCtx(input, ctx);
1580
+ addIssueToContext(ctx, {
1581
+ validation: "jwt",
1582
+ code: ZodIssueCode.invalid_string,
1583
+ message: check.message
1584
+ });
1585
+ status.dirty();
1586
+ }
1587
+ } else if (check.kind === "cidr") {
1588
+ if (!isValidCidr(input.data, check.version)) {
1589
+ ctx = this._getOrReturnCtx(input, ctx);
1590
+ addIssueToContext(ctx, {
1591
+ validation: "cidr",
1592
+ code: ZodIssueCode.invalid_string,
1593
+ message: check.message
1594
+ });
1595
+ status.dirty();
1596
+ }
1597
+ } else if (check.kind === "base64") {
1598
+ if (!base64Regex.test(input.data)) {
1599
+ ctx = this._getOrReturnCtx(input, ctx);
1600
+ addIssueToContext(ctx, {
1601
+ validation: "base64",
1602
+ code: ZodIssueCode.invalid_string,
1603
+ message: check.message
1604
+ });
1605
+ status.dirty();
1606
+ }
1607
+ } else if (check.kind === "base64url") {
1608
+ if (!base64urlRegex.test(input.data)) {
1609
+ ctx = this._getOrReturnCtx(input, ctx);
1610
+ addIssueToContext(ctx, {
1611
+ validation: "base64url",
1612
+ code: ZodIssueCode.invalid_string,
1613
+ message: check.message
1614
+ });
1615
+ status.dirty();
1616
+ }
1617
+ } else {
1618
+ util.assertNever(check);
1619
+ }
1620
+ }
1621
+ return { status: status.value, value: input.data };
1622
+ }
1623
+ _regex(regex, validation, message) {
1624
+ return this.refinement((data) => regex.test(data), {
1625
+ validation,
1626
+ code: ZodIssueCode.invalid_string,
1627
+ ...errorUtil.errToObj(message)
1628
+ });
1629
+ }
1630
+ _addCheck(check) {
1631
+ return new _ZodString({
1632
+ ...this._def,
1633
+ checks: [...this._def.checks, check]
1634
+ });
1635
+ }
1636
+ email(message) {
1637
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1638
+ }
1639
+ url(message) {
1640
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1641
+ }
1642
+ emoji(message) {
1643
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1644
+ }
1645
+ uuid(message) {
1646
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1647
+ }
1648
+ nanoid(message) {
1649
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1650
+ }
1651
+ cuid(message) {
1652
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1653
+ }
1654
+ cuid2(message) {
1655
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1656
+ }
1657
+ ulid(message) {
1658
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1659
+ }
1660
+ base64(message) {
1661
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1662
+ }
1663
+ base64url(message) {
1664
+ return this._addCheck({
1665
+ kind: "base64url",
1666
+ ...errorUtil.errToObj(message)
1667
+ });
1668
+ }
1669
+ jwt(options) {
1670
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1671
+ }
1672
+ ip(options) {
1673
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1674
+ }
1675
+ cidr(options) {
1676
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1677
+ }
1678
+ datetime(options) {
1679
+ if (typeof options === "string") {
1680
+ return this._addCheck({
1681
+ kind: "datetime",
1682
+ precision: null,
1683
+ offset: false,
1684
+ local: false,
1685
+ message: options
1686
+ });
1687
+ }
1688
+ return this._addCheck({
1689
+ kind: "datetime",
1690
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1691
+ offset: options?.offset ?? false,
1692
+ local: options?.local ?? false,
1693
+ ...errorUtil.errToObj(options?.message)
1694
+ });
1695
+ }
1696
+ date(message) {
1697
+ return this._addCheck({ kind: "date", message });
1698
+ }
1699
+ time(options) {
1700
+ if (typeof options === "string") {
1701
+ return this._addCheck({
1702
+ kind: "time",
1703
+ precision: null,
1704
+ message: options
1705
+ });
1706
+ }
1707
+ return this._addCheck({
1708
+ kind: "time",
1709
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1710
+ ...errorUtil.errToObj(options?.message)
1711
+ });
1712
+ }
1713
+ duration(message) {
1714
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1715
+ }
1716
+ regex(regex, message) {
1717
+ return this._addCheck({
1718
+ kind: "regex",
1719
+ regex,
1720
+ ...errorUtil.errToObj(message)
1721
+ });
1722
+ }
1723
+ includes(value, options) {
1724
+ return this._addCheck({
1725
+ kind: "includes",
1726
+ value,
1727
+ position: options?.position,
1728
+ ...errorUtil.errToObj(options?.message)
1729
+ });
1730
+ }
1731
+ startsWith(value, message) {
1732
+ return this._addCheck({
1733
+ kind: "startsWith",
1734
+ value,
1735
+ ...errorUtil.errToObj(message)
1736
+ });
1737
+ }
1738
+ endsWith(value, message) {
1739
+ return this._addCheck({
1740
+ kind: "endsWith",
1741
+ value,
1742
+ ...errorUtil.errToObj(message)
1743
+ });
1744
+ }
1745
+ min(minLength, message) {
1746
+ return this._addCheck({
1747
+ kind: "min",
1748
+ value: minLength,
1749
+ ...errorUtil.errToObj(message)
1750
+ });
1751
+ }
1752
+ max(maxLength, message) {
1753
+ return this._addCheck({
1754
+ kind: "max",
1755
+ value: maxLength,
1756
+ ...errorUtil.errToObj(message)
1757
+ });
1758
+ }
1759
+ length(len, message) {
1760
+ return this._addCheck({
1761
+ kind: "length",
1762
+ value: len,
1763
+ ...errorUtil.errToObj(message)
1764
+ });
1765
+ }
1766
+ /**
1767
+ * Equivalent to `.min(1)`
1768
+ */
1769
+ nonempty(message) {
1770
+ return this.min(1, errorUtil.errToObj(message));
1771
+ }
1772
+ trim() {
1773
+ return new _ZodString({
1774
+ ...this._def,
1775
+ checks: [...this._def.checks, { kind: "trim" }]
1776
+ });
1777
+ }
1778
+ toLowerCase() {
1779
+ return new _ZodString({
1780
+ ...this._def,
1781
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1782
+ });
1783
+ }
1784
+ toUpperCase() {
1785
+ return new _ZodString({
1786
+ ...this._def,
1787
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1788
+ });
1789
+ }
1790
+ get isDatetime() {
1791
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1792
+ }
1793
+ get isDate() {
1794
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1795
+ }
1796
+ get isTime() {
1797
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1798
+ }
1799
+ get isDuration() {
1800
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1801
+ }
1802
+ get isEmail() {
1803
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1804
+ }
1805
+ get isURL() {
1806
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1807
+ }
1808
+ get isEmoji() {
1809
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1810
+ }
1811
+ get isUUID() {
1812
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1813
+ }
1814
+ get isNANOID() {
1815
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1816
+ }
1817
+ get isCUID() {
1818
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1819
+ }
1820
+ get isCUID2() {
1821
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1822
+ }
1823
+ get isULID() {
1824
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1825
+ }
1826
+ get isIP() {
1827
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1828
+ }
1829
+ get isCIDR() {
1830
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1831
+ }
1832
+ get isBase64() {
1833
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1834
+ }
1835
+ get isBase64url() {
1836
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1837
+ }
1838
+ get minLength() {
1839
+ let min = null;
1840
+ for (const ch of this._def.checks) {
1841
+ if (ch.kind === "min") {
1842
+ if (min === null || ch.value > min)
1843
+ min = ch.value;
1844
+ }
1845
+ }
1846
+ return min;
1847
+ }
1848
+ get maxLength() {
1849
+ let max = null;
1850
+ for (const ch of this._def.checks) {
1851
+ if (ch.kind === "max") {
1852
+ if (max === null || ch.value < max)
1853
+ max = ch.value;
1854
+ }
1855
+ }
1856
+ return max;
1857
+ }
1858
+ };
1859
+ ZodString.create = (params) => {
1860
+ return new ZodString({
1861
+ checks: [],
1862
+ typeName: ZodFirstPartyTypeKind.ZodString,
1863
+ coerce: params?.coerce ?? false,
1864
+ ...processCreateParams(params)
1865
+ });
1866
+ };
1867
+ function floatSafeRemainder(val, step) {
1868
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1869
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1870
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1871
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1872
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1873
+ return valInt % stepInt / 10 ** decCount;
1874
+ }
1875
+ var ZodNumber = class _ZodNumber extends ZodType {
1876
+ constructor() {
1877
+ super(...arguments);
1878
+ this.min = this.gte;
1879
+ this.max = this.lte;
1880
+ this.step = this.multipleOf;
1881
+ }
1882
+ _parse(input) {
1883
+ if (this._def.coerce) {
1884
+ input.data = Number(input.data);
1885
+ }
1886
+ const parsedType = this._getType(input);
1887
+ if (parsedType !== ZodParsedType.number) {
1888
+ const ctx2 = this._getOrReturnCtx(input);
1889
+ addIssueToContext(ctx2, {
1890
+ code: ZodIssueCode.invalid_type,
1891
+ expected: ZodParsedType.number,
1892
+ received: ctx2.parsedType
1893
+ });
1894
+ return INVALID;
1895
+ }
1896
+ let ctx = void 0;
1897
+ const status = new ParseStatus();
1898
+ for (const check of this._def.checks) {
1899
+ if (check.kind === "int") {
1900
+ if (!util.isInteger(input.data)) {
1901
+ ctx = this._getOrReturnCtx(input, ctx);
1902
+ addIssueToContext(ctx, {
1903
+ code: ZodIssueCode.invalid_type,
1904
+ expected: "integer",
1905
+ received: "float",
1906
+ message: check.message
1907
+ });
1908
+ status.dirty();
1909
+ }
1910
+ } else if (check.kind === "min") {
1911
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1912
+ if (tooSmall) {
1913
+ ctx = this._getOrReturnCtx(input, ctx);
1914
+ addIssueToContext(ctx, {
1915
+ code: ZodIssueCode.too_small,
1916
+ minimum: check.value,
1917
+ type: "number",
1918
+ inclusive: check.inclusive,
1919
+ exact: false,
1920
+ message: check.message
1921
+ });
1922
+ status.dirty();
1923
+ }
1924
+ } else if (check.kind === "max") {
1925
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1926
+ if (tooBig) {
1927
+ ctx = this._getOrReturnCtx(input, ctx);
1928
+ addIssueToContext(ctx, {
1929
+ code: ZodIssueCode.too_big,
1930
+ maximum: check.value,
1931
+ type: "number",
1932
+ inclusive: check.inclusive,
1933
+ exact: false,
1934
+ message: check.message
1935
+ });
1936
+ status.dirty();
1937
+ }
1938
+ } else if (check.kind === "multipleOf") {
1939
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1940
+ ctx = this._getOrReturnCtx(input, ctx);
1941
+ addIssueToContext(ctx, {
1942
+ code: ZodIssueCode.not_multiple_of,
1943
+ multipleOf: check.value,
1944
+ message: check.message
1945
+ });
1946
+ status.dirty();
1947
+ }
1948
+ } else if (check.kind === "finite") {
1949
+ if (!Number.isFinite(input.data)) {
1950
+ ctx = this._getOrReturnCtx(input, ctx);
1951
+ addIssueToContext(ctx, {
1952
+ code: ZodIssueCode.not_finite,
1953
+ message: check.message
1954
+ });
1955
+ status.dirty();
1956
+ }
1957
+ } else {
1958
+ util.assertNever(check);
1959
+ }
1960
+ }
1961
+ return { status: status.value, value: input.data };
1962
+ }
1963
+ gte(value, message) {
1964
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1965
+ }
1966
+ gt(value, message) {
1967
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1968
+ }
1969
+ lte(value, message) {
1970
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1971
+ }
1972
+ lt(value, message) {
1973
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1974
+ }
1975
+ setLimit(kind, value, inclusive, message) {
1976
+ return new _ZodNumber({
1977
+ ...this._def,
1978
+ checks: [
1979
+ ...this._def.checks,
1980
+ {
1981
+ kind,
1982
+ value,
1983
+ inclusive,
1984
+ message: errorUtil.toString(message)
1985
+ }
1986
+ ]
1987
+ });
1988
+ }
1989
+ _addCheck(check) {
1990
+ return new _ZodNumber({
1991
+ ...this._def,
1992
+ checks: [...this._def.checks, check]
1993
+ });
1994
+ }
1995
+ int(message) {
1996
+ return this._addCheck({
1997
+ kind: "int",
1998
+ message: errorUtil.toString(message)
1999
+ });
2000
+ }
2001
+ positive(message) {
2002
+ return this._addCheck({
2003
+ kind: "min",
2004
+ value: 0,
2005
+ inclusive: false,
2006
+ message: errorUtil.toString(message)
2007
+ });
2008
+ }
2009
+ negative(message) {
2010
+ return this._addCheck({
2011
+ kind: "max",
2012
+ value: 0,
2013
+ inclusive: false,
2014
+ message: errorUtil.toString(message)
2015
+ });
2016
+ }
2017
+ nonpositive(message) {
2018
+ return this._addCheck({
2019
+ kind: "max",
2020
+ value: 0,
2021
+ inclusive: true,
2022
+ message: errorUtil.toString(message)
2023
+ });
2024
+ }
2025
+ nonnegative(message) {
2026
+ return this._addCheck({
2027
+ kind: "min",
2028
+ value: 0,
2029
+ inclusive: true,
2030
+ message: errorUtil.toString(message)
2031
+ });
2032
+ }
2033
+ multipleOf(value, message) {
2034
+ return this._addCheck({
2035
+ kind: "multipleOf",
2036
+ value,
2037
+ message: errorUtil.toString(message)
2038
+ });
2039
+ }
2040
+ finite(message) {
2041
+ return this._addCheck({
2042
+ kind: "finite",
2043
+ message: errorUtil.toString(message)
2044
+ });
2045
+ }
2046
+ safe(message) {
2047
+ return this._addCheck({
2048
+ kind: "min",
2049
+ inclusive: true,
2050
+ value: Number.MIN_SAFE_INTEGER,
2051
+ message: errorUtil.toString(message)
2052
+ })._addCheck({
2053
+ kind: "max",
2054
+ inclusive: true,
2055
+ value: Number.MAX_SAFE_INTEGER,
2056
+ message: errorUtil.toString(message)
2057
+ });
2058
+ }
2059
+ get minValue() {
2060
+ let min = null;
2061
+ for (const ch of this._def.checks) {
2062
+ if (ch.kind === "min") {
2063
+ if (min === null || ch.value > min)
2064
+ min = ch.value;
2065
+ }
2066
+ }
2067
+ return min;
2068
+ }
2069
+ get maxValue() {
2070
+ let max = null;
2071
+ for (const ch of this._def.checks) {
2072
+ if (ch.kind === "max") {
2073
+ if (max === null || ch.value < max)
2074
+ max = ch.value;
2075
+ }
2076
+ }
2077
+ return max;
2078
+ }
2079
+ get isInt() {
2080
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
2081
+ }
2082
+ get isFinite() {
2083
+ let max = null;
2084
+ let min = null;
2085
+ for (const ch of this._def.checks) {
2086
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2087
+ return true;
2088
+ } else if (ch.kind === "min") {
2089
+ if (min === null || ch.value > min)
2090
+ min = ch.value;
2091
+ } else if (ch.kind === "max") {
2092
+ if (max === null || ch.value < max)
2093
+ max = ch.value;
2094
+ }
2095
+ }
2096
+ return Number.isFinite(min) && Number.isFinite(max);
2097
+ }
2098
+ };
2099
+ ZodNumber.create = (params) => {
2100
+ return new ZodNumber({
2101
+ checks: [],
2102
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2103
+ coerce: params?.coerce || false,
2104
+ ...processCreateParams(params)
2105
+ });
2106
+ };
2107
+ var ZodBigInt = class _ZodBigInt extends ZodType {
2108
+ constructor() {
2109
+ super(...arguments);
2110
+ this.min = this.gte;
2111
+ this.max = this.lte;
2112
+ }
2113
+ _parse(input) {
2114
+ if (this._def.coerce) {
2115
+ try {
2116
+ input.data = BigInt(input.data);
2117
+ } catch {
2118
+ return this._getInvalidInput(input);
2119
+ }
2120
+ }
2121
+ const parsedType = this._getType(input);
2122
+ if (parsedType !== ZodParsedType.bigint) {
2123
+ return this._getInvalidInput(input);
2124
+ }
2125
+ let ctx = void 0;
2126
+ const status = new ParseStatus();
2127
+ for (const check of this._def.checks) {
2128
+ if (check.kind === "min") {
2129
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2130
+ if (tooSmall) {
2131
+ ctx = this._getOrReturnCtx(input, ctx);
2132
+ addIssueToContext(ctx, {
2133
+ code: ZodIssueCode.too_small,
2134
+ type: "bigint",
2135
+ minimum: check.value,
2136
+ inclusive: check.inclusive,
2137
+ message: check.message
2138
+ });
2139
+ status.dirty();
2140
+ }
2141
+ } else if (check.kind === "max") {
2142
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2143
+ if (tooBig) {
2144
+ ctx = this._getOrReturnCtx(input, ctx);
2145
+ addIssueToContext(ctx, {
2146
+ code: ZodIssueCode.too_big,
2147
+ type: "bigint",
2148
+ maximum: check.value,
2149
+ inclusive: check.inclusive,
2150
+ message: check.message
2151
+ });
2152
+ status.dirty();
2153
+ }
2154
+ } else if (check.kind === "multipleOf") {
2155
+ if (input.data % check.value !== BigInt(0)) {
2156
+ ctx = this._getOrReturnCtx(input, ctx);
2157
+ addIssueToContext(ctx, {
2158
+ code: ZodIssueCode.not_multiple_of,
2159
+ multipleOf: check.value,
2160
+ message: check.message
2161
+ });
2162
+ status.dirty();
2163
+ }
2164
+ } else {
2165
+ util.assertNever(check);
2166
+ }
2167
+ }
2168
+ return { status: status.value, value: input.data };
2169
+ }
2170
+ _getInvalidInput(input) {
2171
+ const ctx = this._getOrReturnCtx(input);
2172
+ addIssueToContext(ctx, {
2173
+ code: ZodIssueCode.invalid_type,
2174
+ expected: ZodParsedType.bigint,
2175
+ received: ctx.parsedType
2176
+ });
2177
+ return INVALID;
2178
+ }
2179
+ gte(value, message) {
2180
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2181
+ }
2182
+ gt(value, message) {
2183
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2184
+ }
2185
+ lte(value, message) {
2186
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2187
+ }
2188
+ lt(value, message) {
2189
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2190
+ }
2191
+ setLimit(kind, value, inclusive, message) {
2192
+ return new _ZodBigInt({
2193
+ ...this._def,
2194
+ checks: [
2195
+ ...this._def.checks,
2196
+ {
2197
+ kind,
2198
+ value,
2199
+ inclusive,
2200
+ message: errorUtil.toString(message)
2201
+ }
2202
+ ]
2203
+ });
2204
+ }
2205
+ _addCheck(check) {
2206
+ return new _ZodBigInt({
2207
+ ...this._def,
2208
+ checks: [...this._def.checks, check]
2209
+ });
2210
+ }
2211
+ positive(message) {
2212
+ return this._addCheck({
2213
+ kind: "min",
2214
+ value: BigInt(0),
2215
+ inclusive: false,
2216
+ message: errorUtil.toString(message)
2217
+ });
2218
+ }
2219
+ negative(message) {
2220
+ return this._addCheck({
2221
+ kind: "max",
2222
+ value: BigInt(0),
2223
+ inclusive: false,
2224
+ message: errorUtil.toString(message)
2225
+ });
2226
+ }
2227
+ nonpositive(message) {
2228
+ return this._addCheck({
2229
+ kind: "max",
2230
+ value: BigInt(0),
2231
+ inclusive: true,
2232
+ message: errorUtil.toString(message)
2233
+ });
2234
+ }
2235
+ nonnegative(message) {
2236
+ return this._addCheck({
2237
+ kind: "min",
2238
+ value: BigInt(0),
2239
+ inclusive: true,
2240
+ message: errorUtil.toString(message)
2241
+ });
2242
+ }
2243
+ multipleOf(value, message) {
2244
+ return this._addCheck({
2245
+ kind: "multipleOf",
2246
+ value,
2247
+ message: errorUtil.toString(message)
2248
+ });
2249
+ }
2250
+ get minValue() {
2251
+ let min = null;
2252
+ for (const ch of this._def.checks) {
2253
+ if (ch.kind === "min") {
2254
+ if (min === null || ch.value > min)
2255
+ min = ch.value;
2256
+ }
2257
+ }
2258
+ return min;
2259
+ }
2260
+ get maxValue() {
2261
+ let max = null;
2262
+ for (const ch of this._def.checks) {
2263
+ if (ch.kind === "max") {
2264
+ if (max === null || ch.value < max)
2265
+ max = ch.value;
2266
+ }
2267
+ }
2268
+ return max;
2269
+ }
2270
+ };
2271
+ ZodBigInt.create = (params) => {
2272
+ return new ZodBigInt({
2273
+ checks: [],
2274
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2275
+ coerce: params?.coerce ?? false,
2276
+ ...processCreateParams(params)
2277
+ });
2278
+ };
2279
+ var ZodBoolean = class extends ZodType {
2280
+ _parse(input) {
2281
+ if (this._def.coerce) {
2282
+ input.data = Boolean(input.data);
2283
+ }
2284
+ const parsedType = this._getType(input);
2285
+ if (parsedType !== ZodParsedType.boolean) {
2286
+ const ctx = this._getOrReturnCtx(input);
2287
+ addIssueToContext(ctx, {
2288
+ code: ZodIssueCode.invalid_type,
2289
+ expected: ZodParsedType.boolean,
2290
+ received: ctx.parsedType
2291
+ });
2292
+ return INVALID;
2293
+ }
2294
+ return OK(input.data);
2295
+ }
2296
+ };
2297
+ ZodBoolean.create = (params) => {
2298
+ return new ZodBoolean({
2299
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2300
+ coerce: params?.coerce || false,
2301
+ ...processCreateParams(params)
2302
+ });
2303
+ };
2304
+ var ZodDate = class _ZodDate extends ZodType {
2305
+ _parse(input) {
2306
+ if (this._def.coerce) {
2307
+ input.data = new Date(input.data);
2308
+ }
2309
+ const parsedType = this._getType(input);
2310
+ if (parsedType !== ZodParsedType.date) {
2311
+ const ctx2 = this._getOrReturnCtx(input);
2312
+ addIssueToContext(ctx2, {
2313
+ code: ZodIssueCode.invalid_type,
2314
+ expected: ZodParsedType.date,
2315
+ received: ctx2.parsedType
2316
+ });
2317
+ return INVALID;
2318
+ }
2319
+ if (Number.isNaN(input.data.getTime())) {
2320
+ const ctx2 = this._getOrReturnCtx(input);
2321
+ addIssueToContext(ctx2, {
2322
+ code: ZodIssueCode.invalid_date
2323
+ });
2324
+ return INVALID;
2325
+ }
2326
+ const status = new ParseStatus();
2327
+ let ctx = void 0;
2328
+ for (const check of this._def.checks) {
2329
+ if (check.kind === "min") {
2330
+ if (input.data.getTime() < check.value) {
2331
+ ctx = this._getOrReturnCtx(input, ctx);
2332
+ addIssueToContext(ctx, {
2333
+ code: ZodIssueCode.too_small,
2334
+ message: check.message,
2335
+ inclusive: true,
2336
+ exact: false,
2337
+ minimum: check.value,
2338
+ type: "date"
2339
+ });
2340
+ status.dirty();
2341
+ }
2342
+ } else if (check.kind === "max") {
2343
+ if (input.data.getTime() > check.value) {
2344
+ ctx = this._getOrReturnCtx(input, ctx);
2345
+ addIssueToContext(ctx, {
2346
+ code: ZodIssueCode.too_big,
2347
+ message: check.message,
2348
+ inclusive: true,
2349
+ exact: false,
2350
+ maximum: check.value,
2351
+ type: "date"
2352
+ });
2353
+ status.dirty();
2354
+ }
2355
+ } else {
2356
+ util.assertNever(check);
2357
+ }
2358
+ }
2359
+ return {
2360
+ status: status.value,
2361
+ value: new Date(input.data.getTime())
2362
+ };
2363
+ }
2364
+ _addCheck(check) {
2365
+ return new _ZodDate({
2366
+ ...this._def,
2367
+ checks: [...this._def.checks, check]
2368
+ });
2369
+ }
2370
+ min(minDate, message) {
2371
+ return this._addCheck({
2372
+ kind: "min",
2373
+ value: minDate.getTime(),
2374
+ message: errorUtil.toString(message)
2375
+ });
2376
+ }
2377
+ max(maxDate, message) {
2378
+ return this._addCheck({
2379
+ kind: "max",
2380
+ value: maxDate.getTime(),
2381
+ message: errorUtil.toString(message)
2382
+ });
2383
+ }
2384
+ get minDate() {
2385
+ let min = null;
2386
+ for (const ch of this._def.checks) {
2387
+ if (ch.kind === "min") {
2388
+ if (min === null || ch.value > min)
2389
+ min = ch.value;
2390
+ }
2391
+ }
2392
+ return min != null ? new Date(min) : null;
2393
+ }
2394
+ get maxDate() {
2395
+ let max = null;
2396
+ for (const ch of this._def.checks) {
2397
+ if (ch.kind === "max") {
2398
+ if (max === null || ch.value < max)
2399
+ max = ch.value;
2400
+ }
2401
+ }
2402
+ return max != null ? new Date(max) : null;
2403
+ }
2404
+ };
2405
+ ZodDate.create = (params) => {
2406
+ return new ZodDate({
2407
+ checks: [],
2408
+ coerce: params?.coerce || false,
2409
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2410
+ ...processCreateParams(params)
2411
+ });
2412
+ };
2413
+ var ZodSymbol = class extends ZodType {
2414
+ _parse(input) {
2415
+ const parsedType = this._getType(input);
2416
+ if (parsedType !== ZodParsedType.symbol) {
2417
+ const ctx = this._getOrReturnCtx(input);
2418
+ addIssueToContext(ctx, {
2419
+ code: ZodIssueCode.invalid_type,
2420
+ expected: ZodParsedType.symbol,
2421
+ received: ctx.parsedType
2422
+ });
2423
+ return INVALID;
2424
+ }
2425
+ return OK(input.data);
2426
+ }
2427
+ };
2428
+ ZodSymbol.create = (params) => {
2429
+ return new ZodSymbol({
2430
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2431
+ ...processCreateParams(params)
2432
+ });
2433
+ };
2434
+ var ZodUndefined = class extends ZodType {
2435
+ _parse(input) {
2436
+ const parsedType = this._getType(input);
2437
+ if (parsedType !== ZodParsedType.undefined) {
2438
+ const ctx = this._getOrReturnCtx(input);
2439
+ addIssueToContext(ctx, {
2440
+ code: ZodIssueCode.invalid_type,
2441
+ expected: ZodParsedType.undefined,
2442
+ received: ctx.parsedType
2443
+ });
2444
+ return INVALID;
2445
+ }
2446
+ return OK(input.data);
2447
+ }
2448
+ };
2449
+ ZodUndefined.create = (params) => {
2450
+ return new ZodUndefined({
2451
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2452
+ ...processCreateParams(params)
2453
+ });
2454
+ };
2455
+ var ZodNull = class extends ZodType {
2456
+ _parse(input) {
2457
+ const parsedType = this._getType(input);
2458
+ if (parsedType !== ZodParsedType.null) {
2459
+ const ctx = this._getOrReturnCtx(input);
2460
+ addIssueToContext(ctx, {
2461
+ code: ZodIssueCode.invalid_type,
2462
+ expected: ZodParsedType.null,
2463
+ received: ctx.parsedType
2464
+ });
2465
+ return INVALID;
2466
+ }
2467
+ return OK(input.data);
2468
+ }
2469
+ };
2470
+ ZodNull.create = (params) => {
2471
+ return new ZodNull({
2472
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2473
+ ...processCreateParams(params)
2474
+ });
2475
+ };
2476
+ var ZodAny = class extends ZodType {
2477
+ constructor() {
2478
+ super(...arguments);
2479
+ this._any = true;
2480
+ }
2481
+ _parse(input) {
2482
+ return OK(input.data);
2483
+ }
2484
+ };
2485
+ ZodAny.create = (params) => {
2486
+ return new ZodAny({
2487
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2488
+ ...processCreateParams(params)
2489
+ });
2490
+ };
2491
+ var ZodUnknown = class extends ZodType {
2492
+ constructor() {
2493
+ super(...arguments);
2494
+ this._unknown = true;
2495
+ }
2496
+ _parse(input) {
2497
+ return OK(input.data);
2498
+ }
2499
+ };
2500
+ ZodUnknown.create = (params) => {
2501
+ return new ZodUnknown({
2502
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2503
+ ...processCreateParams(params)
2504
+ });
2505
+ };
2506
+ var ZodNever = class extends ZodType {
2507
+ _parse(input) {
2508
+ const ctx = this._getOrReturnCtx(input);
2509
+ addIssueToContext(ctx, {
2510
+ code: ZodIssueCode.invalid_type,
2511
+ expected: ZodParsedType.never,
2512
+ received: ctx.parsedType
2513
+ });
2514
+ return INVALID;
2515
+ }
2516
+ };
2517
+ ZodNever.create = (params) => {
2518
+ return new ZodNever({
2519
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2520
+ ...processCreateParams(params)
2521
+ });
2522
+ };
2523
+ var ZodVoid = class extends ZodType {
2524
+ _parse(input) {
2525
+ const parsedType = this._getType(input);
2526
+ if (parsedType !== ZodParsedType.undefined) {
2527
+ const ctx = this._getOrReturnCtx(input);
2528
+ addIssueToContext(ctx, {
2529
+ code: ZodIssueCode.invalid_type,
2530
+ expected: ZodParsedType.void,
2531
+ received: ctx.parsedType
2532
+ });
2533
+ return INVALID;
2534
+ }
2535
+ return OK(input.data);
2536
+ }
2537
+ };
2538
+ ZodVoid.create = (params) => {
2539
+ return new ZodVoid({
2540
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2541
+ ...processCreateParams(params)
2542
+ });
2543
+ };
2544
+ var ZodArray = class _ZodArray extends ZodType {
2545
+ _parse(input) {
2546
+ const { ctx, status } = this._processInputParams(input);
2547
+ const def = this._def;
2548
+ if (ctx.parsedType !== ZodParsedType.array) {
2549
+ addIssueToContext(ctx, {
2550
+ code: ZodIssueCode.invalid_type,
2551
+ expected: ZodParsedType.array,
2552
+ received: ctx.parsedType
2553
+ });
2554
+ return INVALID;
2555
+ }
2556
+ if (def.exactLength !== null) {
2557
+ const tooBig = ctx.data.length > def.exactLength.value;
2558
+ const tooSmall = ctx.data.length < def.exactLength.value;
2559
+ if (tooBig || tooSmall) {
2560
+ addIssueToContext(ctx, {
2561
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2562
+ minimum: tooSmall ? def.exactLength.value : void 0,
2563
+ maximum: tooBig ? def.exactLength.value : void 0,
2564
+ type: "array",
2565
+ inclusive: true,
2566
+ exact: true,
2567
+ message: def.exactLength.message
2568
+ });
2569
+ status.dirty();
2570
+ }
2571
+ }
2572
+ if (def.minLength !== null) {
2573
+ if (ctx.data.length < def.minLength.value) {
2574
+ addIssueToContext(ctx, {
2575
+ code: ZodIssueCode.too_small,
2576
+ minimum: def.minLength.value,
2577
+ type: "array",
2578
+ inclusive: true,
2579
+ exact: false,
2580
+ message: def.minLength.message
2581
+ });
2582
+ status.dirty();
2583
+ }
2584
+ }
2585
+ if (def.maxLength !== null) {
2586
+ if (ctx.data.length > def.maxLength.value) {
2587
+ addIssueToContext(ctx, {
2588
+ code: ZodIssueCode.too_big,
2589
+ maximum: def.maxLength.value,
2590
+ type: "array",
2591
+ inclusive: true,
2592
+ exact: false,
2593
+ message: def.maxLength.message
2594
+ });
2595
+ status.dirty();
2596
+ }
2597
+ }
2598
+ if (ctx.common.async) {
2599
+ return Promise.all([...ctx.data].map((item, i) => {
2600
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2601
+ })).then((result2) => {
2602
+ return ParseStatus.mergeArray(status, result2);
2603
+ });
2604
+ }
2605
+ const result = [...ctx.data].map((item, i) => {
2606
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2607
+ });
2608
+ return ParseStatus.mergeArray(status, result);
2609
+ }
2610
+ get element() {
2611
+ return this._def.type;
2612
+ }
2613
+ min(minLength, message) {
2614
+ return new _ZodArray({
2615
+ ...this._def,
2616
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2617
+ });
2618
+ }
2619
+ max(maxLength, message) {
2620
+ return new _ZodArray({
2621
+ ...this._def,
2622
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2623
+ });
2624
+ }
2625
+ length(len, message) {
2626
+ return new _ZodArray({
2627
+ ...this._def,
2628
+ exactLength: { value: len, message: errorUtil.toString(message) }
2629
+ });
2630
+ }
2631
+ nonempty(message) {
2632
+ return this.min(1, message);
2633
+ }
2634
+ };
2635
+ ZodArray.create = (schema, params) => {
2636
+ return new ZodArray({
2637
+ type: schema,
2638
+ minLength: null,
2639
+ maxLength: null,
2640
+ exactLength: null,
2641
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2642
+ ...processCreateParams(params)
2643
+ });
2644
+ };
2645
+ function deepPartialify(schema) {
2646
+ if (schema instanceof ZodObject) {
2647
+ const newShape = {};
2648
+ for (const key in schema.shape) {
2649
+ const fieldSchema = schema.shape[key];
2650
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2651
+ }
2652
+ return new ZodObject({
2653
+ ...schema._def,
2654
+ shape: () => newShape
2655
+ });
2656
+ } else if (schema instanceof ZodArray) {
2657
+ return new ZodArray({
2658
+ ...schema._def,
2659
+ type: deepPartialify(schema.element)
2660
+ });
2661
+ } else if (schema instanceof ZodOptional) {
2662
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2663
+ } else if (schema instanceof ZodNullable) {
2664
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2665
+ } else if (schema instanceof ZodTuple) {
2666
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2667
+ } else {
2668
+ return schema;
2669
+ }
2670
+ }
2671
+ var ZodObject = class _ZodObject extends ZodType {
2672
+ constructor() {
2673
+ super(...arguments);
2674
+ this._cached = null;
2675
+ this.nonstrict = this.passthrough;
2676
+ this.augment = this.extend;
2677
+ }
2678
+ _getCached() {
2679
+ if (this._cached !== null)
2680
+ return this._cached;
2681
+ const shape = this._def.shape();
2682
+ const keys = util.objectKeys(shape);
2683
+ this._cached = { shape, keys };
2684
+ return this._cached;
2685
+ }
2686
+ _parse(input) {
2687
+ const parsedType = this._getType(input);
2688
+ if (parsedType !== ZodParsedType.object) {
2689
+ const ctx2 = this._getOrReturnCtx(input);
2690
+ addIssueToContext(ctx2, {
2691
+ code: ZodIssueCode.invalid_type,
2692
+ expected: ZodParsedType.object,
2693
+ received: ctx2.parsedType
2694
+ });
2695
+ return INVALID;
2696
+ }
2697
+ const { status, ctx } = this._processInputParams(input);
2698
+ const { shape, keys: shapeKeys } = this._getCached();
2699
+ const extraKeys = [];
2700
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2701
+ for (const key in ctx.data) {
2702
+ if (!shapeKeys.includes(key)) {
2703
+ extraKeys.push(key);
2704
+ }
2705
+ }
2706
+ }
2707
+ const pairs = [];
2708
+ for (const key of shapeKeys) {
2709
+ const keyValidator = shape[key];
2710
+ const value = ctx.data[key];
2711
+ pairs.push({
2712
+ key: { status: "valid", value: key },
2713
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2714
+ alwaysSet: key in ctx.data
2715
+ });
2716
+ }
2717
+ if (this._def.catchall instanceof ZodNever) {
2718
+ const unknownKeys = this._def.unknownKeys;
2719
+ if (unknownKeys === "passthrough") {
2720
+ for (const key of extraKeys) {
2721
+ pairs.push({
2722
+ key: { status: "valid", value: key },
2723
+ value: { status: "valid", value: ctx.data[key] }
2724
+ });
2725
+ }
2726
+ } else if (unknownKeys === "strict") {
2727
+ if (extraKeys.length > 0) {
2728
+ addIssueToContext(ctx, {
2729
+ code: ZodIssueCode.unrecognized_keys,
2730
+ keys: extraKeys
2731
+ });
2732
+ status.dirty();
2733
+ }
2734
+ } else if (unknownKeys === "strip") ; else {
2735
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2736
+ }
2737
+ } else {
2738
+ const catchall = this._def.catchall;
2739
+ for (const key of extraKeys) {
2740
+ const value = ctx.data[key];
2741
+ pairs.push({
2742
+ key: { status: "valid", value: key },
2743
+ value: catchall._parse(
2744
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
2745
+ //, ctx.child(key), value, getParsedType(value)
2746
+ ),
2747
+ alwaysSet: key in ctx.data
2748
+ });
2749
+ }
2750
+ }
2751
+ if (ctx.common.async) {
2752
+ return Promise.resolve().then(async () => {
2753
+ const syncPairs = [];
2754
+ for (const pair of pairs) {
2755
+ const key = await pair.key;
2756
+ const value = await pair.value;
2757
+ syncPairs.push({
2758
+ key,
2759
+ value,
2760
+ alwaysSet: pair.alwaysSet
2761
+ });
2762
+ }
2763
+ return syncPairs;
2764
+ }).then((syncPairs) => {
2765
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2766
+ });
2767
+ } else {
2768
+ return ParseStatus.mergeObjectSync(status, pairs);
2769
+ }
2770
+ }
2771
+ get shape() {
2772
+ return this._def.shape();
2773
+ }
2774
+ strict(message) {
2775
+ errorUtil.errToObj;
2776
+ return new _ZodObject({
2777
+ ...this._def,
2778
+ unknownKeys: "strict",
2779
+ ...message !== void 0 ? {
2780
+ errorMap: (issue, ctx) => {
2781
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2782
+ if (issue.code === "unrecognized_keys")
2783
+ return {
2784
+ message: errorUtil.errToObj(message).message ?? defaultError
2785
+ };
2786
+ return {
2787
+ message: defaultError
2788
+ };
2789
+ }
2790
+ } : {}
2791
+ });
2792
+ }
2793
+ strip() {
2794
+ return new _ZodObject({
2795
+ ...this._def,
2796
+ unknownKeys: "strip"
2797
+ });
2798
+ }
2799
+ passthrough() {
2800
+ return new _ZodObject({
2801
+ ...this._def,
2802
+ unknownKeys: "passthrough"
2803
+ });
2804
+ }
2805
+ // const AugmentFactory =
2806
+ // <Def extends ZodObjectDef>(def: Def) =>
2807
+ // <Augmentation extends ZodRawShape>(
2808
+ // augmentation: Augmentation
2809
+ // ): ZodObject<
2810
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2811
+ // Def["unknownKeys"],
2812
+ // Def["catchall"]
2813
+ // > => {
2814
+ // return new ZodObject({
2815
+ // ...def,
2816
+ // shape: () => ({
2817
+ // ...def.shape(),
2818
+ // ...augmentation,
2819
+ // }),
2820
+ // }) as any;
2821
+ // };
2822
+ extend(augmentation) {
2823
+ return new _ZodObject({
2824
+ ...this._def,
2825
+ shape: () => ({
2826
+ ...this._def.shape(),
2827
+ ...augmentation
2828
+ })
2829
+ });
2830
+ }
2831
+ /**
2832
+ * Prior to zod@1.0.12 there was a bug in the
2833
+ * inferred type of merged objects. Please
2834
+ * upgrade if you are experiencing issues.
2835
+ */
2836
+ merge(merging) {
2837
+ const merged = new _ZodObject({
2838
+ unknownKeys: merging._def.unknownKeys,
2839
+ catchall: merging._def.catchall,
2840
+ shape: () => ({
2841
+ ...this._def.shape(),
2842
+ ...merging._def.shape()
2843
+ }),
2844
+ typeName: ZodFirstPartyTypeKind.ZodObject
2845
+ });
2846
+ return merged;
2847
+ }
2848
+ // merge<
2849
+ // Incoming extends AnyZodObject,
2850
+ // Augmentation extends Incoming["shape"],
2851
+ // NewOutput extends {
2852
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2853
+ // ? Augmentation[k]["_output"]
2854
+ // : k extends keyof Output
2855
+ // ? Output[k]
2856
+ // : never;
2857
+ // },
2858
+ // NewInput extends {
2859
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2860
+ // ? Augmentation[k]["_input"]
2861
+ // : k extends keyof Input
2862
+ // ? Input[k]
2863
+ // : never;
2864
+ // }
2865
+ // >(
2866
+ // merging: Incoming
2867
+ // ): ZodObject<
2868
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2869
+ // Incoming["_def"]["unknownKeys"],
2870
+ // Incoming["_def"]["catchall"],
2871
+ // NewOutput,
2872
+ // NewInput
2873
+ // > {
2874
+ // const merged: any = new ZodObject({
2875
+ // unknownKeys: merging._def.unknownKeys,
2876
+ // catchall: merging._def.catchall,
2877
+ // shape: () =>
2878
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2879
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2880
+ // }) as any;
2881
+ // return merged;
2882
+ // }
2883
+ setKey(key, schema) {
2884
+ return this.augment({ [key]: schema });
2885
+ }
2886
+ // merge<Incoming extends AnyZodObject>(
2887
+ // merging: Incoming
2888
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2889
+ // ZodObject<
2890
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2891
+ // Incoming["_def"]["unknownKeys"],
2892
+ // Incoming["_def"]["catchall"]
2893
+ // > {
2894
+ // // const mergedShape = objectUtil.mergeShapes(
2895
+ // // this._def.shape(),
2896
+ // // merging._def.shape()
2897
+ // // );
2898
+ // const merged: any = new ZodObject({
2899
+ // unknownKeys: merging._def.unknownKeys,
2900
+ // catchall: merging._def.catchall,
2901
+ // shape: () =>
2902
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2903
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2904
+ // }) as any;
2905
+ // return merged;
2906
+ // }
2907
+ catchall(index) {
2908
+ return new _ZodObject({
2909
+ ...this._def,
2910
+ catchall: index
2911
+ });
2912
+ }
2913
+ pick(mask) {
2914
+ const shape = {};
2915
+ for (const key of util.objectKeys(mask)) {
2916
+ if (mask[key] && this.shape[key]) {
2917
+ shape[key] = this.shape[key];
2918
+ }
2919
+ }
2920
+ return new _ZodObject({
2921
+ ...this._def,
2922
+ shape: () => shape
2923
+ });
2924
+ }
2925
+ omit(mask) {
2926
+ const shape = {};
2927
+ for (const key of util.objectKeys(this.shape)) {
2928
+ if (!mask[key]) {
2929
+ shape[key] = this.shape[key];
2930
+ }
2931
+ }
2932
+ return new _ZodObject({
2933
+ ...this._def,
2934
+ shape: () => shape
2935
+ });
2936
+ }
2937
+ /**
2938
+ * @deprecated
2939
+ */
2940
+ deepPartial() {
2941
+ return deepPartialify(this);
2942
+ }
2943
+ partial(mask) {
2944
+ const newShape = {};
2945
+ for (const key of util.objectKeys(this.shape)) {
2946
+ const fieldSchema = this.shape[key];
2947
+ if (mask && !mask[key]) {
2948
+ newShape[key] = fieldSchema;
2949
+ } else {
2950
+ newShape[key] = fieldSchema.optional();
2951
+ }
2952
+ }
2953
+ return new _ZodObject({
2954
+ ...this._def,
2955
+ shape: () => newShape
2956
+ });
2957
+ }
2958
+ required(mask) {
2959
+ const newShape = {};
2960
+ for (const key of util.objectKeys(this.shape)) {
2961
+ if (mask && !mask[key]) {
2962
+ newShape[key] = this.shape[key];
2963
+ } else {
2964
+ const fieldSchema = this.shape[key];
2965
+ let newField = fieldSchema;
2966
+ while (newField instanceof ZodOptional) {
2967
+ newField = newField._def.innerType;
2968
+ }
2969
+ newShape[key] = newField;
2970
+ }
2971
+ }
2972
+ return new _ZodObject({
2973
+ ...this._def,
2974
+ shape: () => newShape
2975
+ });
2976
+ }
2977
+ keyof() {
2978
+ return createZodEnum(util.objectKeys(this.shape));
2979
+ }
2980
+ };
2981
+ ZodObject.create = (shape, params) => {
2982
+ return new ZodObject({
2983
+ shape: () => shape,
2984
+ unknownKeys: "strip",
2985
+ catchall: ZodNever.create(),
2986
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2987
+ ...processCreateParams(params)
2988
+ });
2989
+ };
2990
+ ZodObject.strictCreate = (shape, params) => {
2991
+ return new ZodObject({
2992
+ shape: () => shape,
2993
+ unknownKeys: "strict",
2994
+ catchall: ZodNever.create(),
2995
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2996
+ ...processCreateParams(params)
2997
+ });
2998
+ };
2999
+ ZodObject.lazycreate = (shape, params) => {
3000
+ return new ZodObject({
3001
+ shape,
3002
+ unknownKeys: "strip",
3003
+ catchall: ZodNever.create(),
3004
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3005
+ ...processCreateParams(params)
3006
+ });
3007
+ };
3008
+ var ZodUnion = class extends ZodType {
3009
+ _parse(input) {
3010
+ const { ctx } = this._processInputParams(input);
3011
+ const options = this._def.options;
3012
+ function handleResults(results) {
3013
+ for (const result of results) {
3014
+ if (result.result.status === "valid") {
3015
+ return result.result;
3016
+ }
3017
+ }
3018
+ for (const result of results) {
3019
+ if (result.result.status === "dirty") {
3020
+ ctx.common.issues.push(...result.ctx.common.issues);
3021
+ return result.result;
3022
+ }
3023
+ }
3024
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3025
+ addIssueToContext(ctx, {
3026
+ code: ZodIssueCode.invalid_union,
3027
+ unionErrors
3028
+ });
3029
+ return INVALID;
3030
+ }
3031
+ if (ctx.common.async) {
3032
+ return Promise.all(options.map(async (option) => {
3033
+ const childCtx = {
3034
+ ...ctx,
3035
+ common: {
3036
+ ...ctx.common,
3037
+ issues: []
3038
+ },
3039
+ parent: null
3040
+ };
3041
+ return {
3042
+ result: await option._parseAsync({
3043
+ data: ctx.data,
3044
+ path: ctx.path,
3045
+ parent: childCtx
3046
+ }),
3047
+ ctx: childCtx
3048
+ };
3049
+ })).then(handleResults);
3050
+ } else {
3051
+ let dirty = void 0;
3052
+ const issues = [];
3053
+ for (const option of options) {
3054
+ const childCtx = {
3055
+ ...ctx,
3056
+ common: {
3057
+ ...ctx.common,
3058
+ issues: []
3059
+ },
3060
+ parent: null
3061
+ };
3062
+ const result = option._parseSync({
3063
+ data: ctx.data,
3064
+ path: ctx.path,
3065
+ parent: childCtx
3066
+ });
3067
+ if (result.status === "valid") {
3068
+ return result;
3069
+ } else if (result.status === "dirty" && !dirty) {
3070
+ dirty = { result, ctx: childCtx };
3071
+ }
3072
+ if (childCtx.common.issues.length) {
3073
+ issues.push(childCtx.common.issues);
3074
+ }
3075
+ }
3076
+ if (dirty) {
3077
+ ctx.common.issues.push(...dirty.ctx.common.issues);
3078
+ return dirty.result;
3079
+ }
3080
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
3081
+ addIssueToContext(ctx, {
3082
+ code: ZodIssueCode.invalid_union,
3083
+ unionErrors
3084
+ });
3085
+ return INVALID;
3086
+ }
3087
+ }
3088
+ get options() {
3089
+ return this._def.options;
3090
+ }
3091
+ };
3092
+ ZodUnion.create = (types, params) => {
3093
+ return new ZodUnion({
3094
+ options: types,
3095
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
3096
+ ...processCreateParams(params)
3097
+ });
3098
+ };
3099
+ var getDiscriminator = (type) => {
3100
+ if (type instanceof ZodLazy) {
3101
+ return getDiscriminator(type.schema);
3102
+ } else if (type instanceof ZodEffects) {
3103
+ return getDiscriminator(type.innerType());
3104
+ } else if (type instanceof ZodLiteral) {
3105
+ return [type.value];
3106
+ } else if (type instanceof ZodEnum) {
3107
+ return type.options;
3108
+ } else if (type instanceof ZodNativeEnum) {
3109
+ return util.objectValues(type.enum);
3110
+ } else if (type instanceof ZodDefault) {
3111
+ return getDiscriminator(type._def.innerType);
3112
+ } else if (type instanceof ZodUndefined) {
3113
+ return [void 0];
3114
+ } else if (type instanceof ZodNull) {
3115
+ return [null];
3116
+ } else if (type instanceof ZodOptional) {
3117
+ return [void 0, ...getDiscriminator(type.unwrap())];
3118
+ } else if (type instanceof ZodNullable) {
3119
+ return [null, ...getDiscriminator(type.unwrap())];
3120
+ } else if (type instanceof ZodBranded) {
3121
+ return getDiscriminator(type.unwrap());
3122
+ } else if (type instanceof ZodReadonly) {
3123
+ return getDiscriminator(type.unwrap());
3124
+ } else if (type instanceof ZodCatch) {
3125
+ return getDiscriminator(type._def.innerType);
3126
+ } else {
3127
+ return [];
3128
+ }
3129
+ };
3130
+ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
3131
+ _parse(input) {
3132
+ const { ctx } = this._processInputParams(input);
3133
+ if (ctx.parsedType !== ZodParsedType.object) {
3134
+ addIssueToContext(ctx, {
3135
+ code: ZodIssueCode.invalid_type,
3136
+ expected: ZodParsedType.object,
3137
+ received: ctx.parsedType
3138
+ });
3139
+ return INVALID;
3140
+ }
3141
+ const discriminator = this.discriminator;
3142
+ const discriminatorValue = ctx.data[discriminator];
3143
+ const option = this.optionsMap.get(discriminatorValue);
3144
+ if (!option) {
3145
+ addIssueToContext(ctx, {
3146
+ code: ZodIssueCode.invalid_union_discriminator,
3147
+ options: Array.from(this.optionsMap.keys()),
3148
+ path: [discriminator]
3149
+ });
3150
+ return INVALID;
3151
+ }
3152
+ if (ctx.common.async) {
3153
+ return option._parseAsync({
3154
+ data: ctx.data,
3155
+ path: ctx.path,
3156
+ parent: ctx
3157
+ });
3158
+ } else {
3159
+ return option._parseSync({
3160
+ data: ctx.data,
3161
+ path: ctx.path,
3162
+ parent: ctx
3163
+ });
3164
+ }
3165
+ }
3166
+ get discriminator() {
3167
+ return this._def.discriminator;
3168
+ }
3169
+ get options() {
3170
+ return this._def.options;
3171
+ }
3172
+ get optionsMap() {
3173
+ return this._def.optionsMap;
3174
+ }
3175
+ /**
3176
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
3177
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
3178
+ * have a different value for each object in the union.
3179
+ * @param discriminator the name of the discriminator property
3180
+ * @param types an array of object schemas
3181
+ * @param params
3182
+ */
3183
+ static create(discriminator, options, params) {
3184
+ const optionsMap = /* @__PURE__ */ new Map();
3185
+ for (const type of options) {
3186
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3187
+ if (!discriminatorValues.length) {
3188
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3189
+ }
3190
+ for (const value of discriminatorValues) {
3191
+ if (optionsMap.has(value)) {
3192
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3193
+ }
3194
+ optionsMap.set(value, type);
3195
+ }
3196
+ }
3197
+ return new _ZodDiscriminatedUnion({
3198
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3199
+ discriminator,
3200
+ options,
3201
+ optionsMap,
3202
+ ...processCreateParams(params)
3203
+ });
3204
+ }
3205
+ };
3206
+ function mergeValues(a, b) {
3207
+ const aType = getParsedType(a);
3208
+ const bType = getParsedType(b);
3209
+ if (a === b) {
3210
+ return { valid: true, data: a };
3211
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3212
+ const bKeys = util.objectKeys(b);
3213
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3214
+ const newObj = { ...a, ...b };
3215
+ for (const key of sharedKeys) {
3216
+ const sharedValue = mergeValues(a[key], b[key]);
3217
+ if (!sharedValue.valid) {
3218
+ return { valid: false };
3219
+ }
3220
+ newObj[key] = sharedValue.data;
3221
+ }
3222
+ return { valid: true, data: newObj };
3223
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3224
+ if (a.length !== b.length) {
3225
+ return { valid: false };
3226
+ }
3227
+ const newArray = [];
3228
+ for (let index = 0; index < a.length; index++) {
3229
+ const itemA = a[index];
3230
+ const itemB = b[index];
3231
+ const sharedValue = mergeValues(itemA, itemB);
3232
+ if (!sharedValue.valid) {
3233
+ return { valid: false };
3234
+ }
3235
+ newArray.push(sharedValue.data);
3236
+ }
3237
+ return { valid: true, data: newArray };
3238
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3239
+ return { valid: true, data: a };
3240
+ } else {
3241
+ return { valid: false };
3242
+ }
3243
+ }
3244
+ var ZodIntersection = class extends ZodType {
3245
+ _parse(input) {
3246
+ const { status, ctx } = this._processInputParams(input);
3247
+ const handleParsed = (parsedLeft, parsedRight) => {
3248
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3249
+ return INVALID;
3250
+ }
3251
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3252
+ if (!merged.valid) {
3253
+ addIssueToContext(ctx, {
3254
+ code: ZodIssueCode.invalid_intersection_types
3255
+ });
3256
+ return INVALID;
3257
+ }
3258
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3259
+ status.dirty();
3260
+ }
3261
+ return { status: status.value, value: merged.data };
3262
+ };
3263
+ if (ctx.common.async) {
3264
+ return Promise.all([
3265
+ this._def.left._parseAsync({
3266
+ data: ctx.data,
3267
+ path: ctx.path,
3268
+ parent: ctx
3269
+ }),
3270
+ this._def.right._parseAsync({
3271
+ data: ctx.data,
3272
+ path: ctx.path,
3273
+ parent: ctx
3274
+ })
3275
+ ]).then(([left, right]) => handleParsed(left, right));
3276
+ } else {
3277
+ return handleParsed(this._def.left._parseSync({
3278
+ data: ctx.data,
3279
+ path: ctx.path,
3280
+ parent: ctx
3281
+ }), this._def.right._parseSync({
3282
+ data: ctx.data,
3283
+ path: ctx.path,
3284
+ parent: ctx
3285
+ }));
3286
+ }
3287
+ }
3288
+ };
3289
+ ZodIntersection.create = (left, right, params) => {
3290
+ return new ZodIntersection({
3291
+ left,
3292
+ right,
3293
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3294
+ ...processCreateParams(params)
3295
+ });
3296
+ };
3297
+ var ZodTuple = class _ZodTuple extends ZodType {
3298
+ _parse(input) {
3299
+ const { status, ctx } = this._processInputParams(input);
3300
+ if (ctx.parsedType !== ZodParsedType.array) {
3301
+ addIssueToContext(ctx, {
3302
+ code: ZodIssueCode.invalid_type,
3303
+ expected: ZodParsedType.array,
3304
+ received: ctx.parsedType
3305
+ });
3306
+ return INVALID;
3307
+ }
3308
+ if (ctx.data.length < this._def.items.length) {
3309
+ addIssueToContext(ctx, {
3310
+ code: ZodIssueCode.too_small,
3311
+ minimum: this._def.items.length,
3312
+ inclusive: true,
3313
+ exact: false,
3314
+ type: "array"
3315
+ });
3316
+ return INVALID;
3317
+ }
3318
+ const rest = this._def.rest;
3319
+ if (!rest && ctx.data.length > this._def.items.length) {
3320
+ addIssueToContext(ctx, {
3321
+ code: ZodIssueCode.too_big,
3322
+ maximum: this._def.items.length,
3323
+ inclusive: true,
3324
+ exact: false,
3325
+ type: "array"
3326
+ });
3327
+ status.dirty();
3328
+ }
3329
+ const items = [...ctx.data].map((item, itemIndex) => {
3330
+ const schema = this._def.items[itemIndex] || this._def.rest;
3331
+ if (!schema)
3332
+ return null;
3333
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3334
+ }).filter((x) => !!x);
3335
+ if (ctx.common.async) {
3336
+ return Promise.all(items).then((results) => {
3337
+ return ParseStatus.mergeArray(status, results);
3338
+ });
3339
+ } else {
3340
+ return ParseStatus.mergeArray(status, items);
3341
+ }
3342
+ }
3343
+ get items() {
3344
+ return this._def.items;
3345
+ }
3346
+ rest(rest) {
3347
+ return new _ZodTuple({
3348
+ ...this._def,
3349
+ rest
3350
+ });
3351
+ }
3352
+ };
3353
+ ZodTuple.create = (schemas, params) => {
3354
+ if (!Array.isArray(schemas)) {
3355
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3356
+ }
3357
+ return new ZodTuple({
3358
+ items: schemas,
3359
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3360
+ rest: null,
3361
+ ...processCreateParams(params)
3362
+ });
3363
+ };
3364
+ var ZodRecord = class _ZodRecord extends ZodType {
3365
+ get keySchema() {
3366
+ return this._def.keyType;
3367
+ }
3368
+ get valueSchema() {
3369
+ return this._def.valueType;
3370
+ }
3371
+ _parse(input) {
3372
+ const { status, ctx } = this._processInputParams(input);
3373
+ if (ctx.parsedType !== ZodParsedType.object) {
3374
+ addIssueToContext(ctx, {
3375
+ code: ZodIssueCode.invalid_type,
3376
+ expected: ZodParsedType.object,
3377
+ received: ctx.parsedType
3378
+ });
3379
+ return INVALID;
3380
+ }
3381
+ const pairs = [];
3382
+ const keyType = this._def.keyType;
3383
+ const valueType = this._def.valueType;
3384
+ for (const key in ctx.data) {
3385
+ pairs.push({
3386
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3387
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3388
+ alwaysSet: key in ctx.data
3389
+ });
3390
+ }
3391
+ if (ctx.common.async) {
3392
+ return ParseStatus.mergeObjectAsync(status, pairs);
3393
+ } else {
3394
+ return ParseStatus.mergeObjectSync(status, pairs);
3395
+ }
3396
+ }
3397
+ get element() {
3398
+ return this._def.valueType;
3399
+ }
3400
+ static create(first, second, third) {
3401
+ if (second instanceof ZodType) {
3402
+ return new _ZodRecord({
3403
+ keyType: first,
3404
+ valueType: second,
3405
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3406
+ ...processCreateParams(third)
3407
+ });
3408
+ }
3409
+ return new _ZodRecord({
3410
+ keyType: ZodString.create(),
3411
+ valueType: first,
3412
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3413
+ ...processCreateParams(second)
3414
+ });
3415
+ }
3416
+ };
3417
+ var ZodMap = class extends ZodType {
3418
+ get keySchema() {
3419
+ return this._def.keyType;
3420
+ }
3421
+ get valueSchema() {
3422
+ return this._def.valueType;
3423
+ }
3424
+ _parse(input) {
3425
+ const { status, ctx } = this._processInputParams(input);
3426
+ if (ctx.parsedType !== ZodParsedType.map) {
3427
+ addIssueToContext(ctx, {
3428
+ code: ZodIssueCode.invalid_type,
3429
+ expected: ZodParsedType.map,
3430
+ received: ctx.parsedType
3431
+ });
3432
+ return INVALID;
3433
+ }
3434
+ const keyType = this._def.keyType;
3435
+ const valueType = this._def.valueType;
3436
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3437
+ return {
3438
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3439
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3440
+ };
3441
+ });
3442
+ if (ctx.common.async) {
3443
+ const finalMap = /* @__PURE__ */ new Map();
3444
+ return Promise.resolve().then(async () => {
3445
+ for (const pair of pairs) {
3446
+ const key = await pair.key;
3447
+ const value = await pair.value;
3448
+ if (key.status === "aborted" || value.status === "aborted") {
3449
+ return INVALID;
3450
+ }
3451
+ if (key.status === "dirty" || value.status === "dirty") {
3452
+ status.dirty();
3453
+ }
3454
+ finalMap.set(key.value, value.value);
3455
+ }
3456
+ return { status: status.value, value: finalMap };
3457
+ });
3458
+ } else {
3459
+ const finalMap = /* @__PURE__ */ new Map();
3460
+ for (const pair of pairs) {
3461
+ const key = pair.key;
3462
+ const value = pair.value;
3463
+ if (key.status === "aborted" || value.status === "aborted") {
3464
+ return INVALID;
3465
+ }
3466
+ if (key.status === "dirty" || value.status === "dirty") {
3467
+ status.dirty();
3468
+ }
3469
+ finalMap.set(key.value, value.value);
3470
+ }
3471
+ return { status: status.value, value: finalMap };
3472
+ }
3473
+ }
3474
+ };
3475
+ ZodMap.create = (keyType, valueType, params) => {
3476
+ return new ZodMap({
3477
+ valueType,
3478
+ keyType,
3479
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3480
+ ...processCreateParams(params)
3481
+ });
3482
+ };
3483
+ var ZodSet = class _ZodSet extends ZodType {
3484
+ _parse(input) {
3485
+ const { status, ctx } = this._processInputParams(input);
3486
+ if (ctx.parsedType !== ZodParsedType.set) {
3487
+ addIssueToContext(ctx, {
3488
+ code: ZodIssueCode.invalid_type,
3489
+ expected: ZodParsedType.set,
3490
+ received: ctx.parsedType
3491
+ });
3492
+ return INVALID;
3493
+ }
3494
+ const def = this._def;
3495
+ if (def.minSize !== null) {
3496
+ if (ctx.data.size < def.minSize.value) {
3497
+ addIssueToContext(ctx, {
3498
+ code: ZodIssueCode.too_small,
3499
+ minimum: def.minSize.value,
3500
+ type: "set",
3501
+ inclusive: true,
3502
+ exact: false,
3503
+ message: def.minSize.message
3504
+ });
3505
+ status.dirty();
3506
+ }
3507
+ }
3508
+ if (def.maxSize !== null) {
3509
+ if (ctx.data.size > def.maxSize.value) {
3510
+ addIssueToContext(ctx, {
3511
+ code: ZodIssueCode.too_big,
3512
+ maximum: def.maxSize.value,
3513
+ type: "set",
3514
+ inclusive: true,
3515
+ exact: false,
3516
+ message: def.maxSize.message
3517
+ });
3518
+ status.dirty();
3519
+ }
3520
+ }
3521
+ const valueType = this._def.valueType;
3522
+ function finalizeSet(elements2) {
3523
+ const parsedSet = /* @__PURE__ */ new Set();
3524
+ for (const element of elements2) {
3525
+ if (element.status === "aborted")
3526
+ return INVALID;
3527
+ if (element.status === "dirty")
3528
+ status.dirty();
3529
+ parsedSet.add(element.value);
3530
+ }
3531
+ return { status: status.value, value: parsedSet };
3532
+ }
3533
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3534
+ if (ctx.common.async) {
3535
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3536
+ } else {
3537
+ return finalizeSet(elements);
3538
+ }
3539
+ }
3540
+ min(minSize, message) {
3541
+ return new _ZodSet({
3542
+ ...this._def,
3543
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3544
+ });
3545
+ }
3546
+ max(maxSize, message) {
3547
+ return new _ZodSet({
3548
+ ...this._def,
3549
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3550
+ });
3551
+ }
3552
+ size(size, message) {
3553
+ return this.min(size, message).max(size, message);
3554
+ }
3555
+ nonempty(message) {
3556
+ return this.min(1, message);
3557
+ }
3558
+ };
3559
+ ZodSet.create = (valueType, params) => {
3560
+ return new ZodSet({
3561
+ valueType,
3562
+ minSize: null,
3563
+ maxSize: null,
3564
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3565
+ ...processCreateParams(params)
3566
+ });
3567
+ };
3568
+ var ZodFunction = class _ZodFunction extends ZodType {
3569
+ constructor() {
3570
+ super(...arguments);
3571
+ this.validate = this.implement;
3572
+ }
3573
+ _parse(input) {
3574
+ const { ctx } = this._processInputParams(input);
3575
+ if (ctx.parsedType !== ZodParsedType.function) {
3576
+ addIssueToContext(ctx, {
3577
+ code: ZodIssueCode.invalid_type,
3578
+ expected: ZodParsedType.function,
3579
+ received: ctx.parsedType
3580
+ });
3581
+ return INVALID;
3582
+ }
3583
+ function makeArgsIssue(args, error) {
3584
+ return makeIssue({
3585
+ data: args,
3586
+ path: ctx.path,
3587
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3588
+ issueData: {
3589
+ code: ZodIssueCode.invalid_arguments,
3590
+ argumentsError: error
3591
+ }
3592
+ });
3593
+ }
3594
+ function makeReturnsIssue(returns, error) {
3595
+ return makeIssue({
3596
+ data: returns,
3597
+ path: ctx.path,
3598
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3599
+ issueData: {
3600
+ code: ZodIssueCode.invalid_return_type,
3601
+ returnTypeError: error
3602
+ }
3603
+ });
3604
+ }
3605
+ const params = { errorMap: ctx.common.contextualErrorMap };
3606
+ const fn = ctx.data;
3607
+ if (this._def.returns instanceof ZodPromise) {
3608
+ const me = this;
3609
+ return OK(async function(...args) {
3610
+ const error = new ZodError([]);
3611
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3612
+ error.addIssue(makeArgsIssue(args, e));
3613
+ throw error;
3614
+ });
3615
+ const result = await Reflect.apply(fn, this, parsedArgs);
3616
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3617
+ error.addIssue(makeReturnsIssue(result, e));
3618
+ throw error;
3619
+ });
3620
+ return parsedReturns;
3621
+ });
3622
+ } else {
3623
+ const me = this;
3624
+ return OK(function(...args) {
3625
+ const parsedArgs = me._def.args.safeParse(args, params);
3626
+ if (!parsedArgs.success) {
3627
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3628
+ }
3629
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3630
+ const parsedReturns = me._def.returns.safeParse(result, params);
3631
+ if (!parsedReturns.success) {
3632
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3633
+ }
3634
+ return parsedReturns.data;
3635
+ });
3636
+ }
3637
+ }
3638
+ parameters() {
3639
+ return this._def.args;
3640
+ }
3641
+ returnType() {
3642
+ return this._def.returns;
3643
+ }
3644
+ args(...items) {
3645
+ return new _ZodFunction({
3646
+ ...this._def,
3647
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3648
+ });
3649
+ }
3650
+ returns(returnType) {
3651
+ return new _ZodFunction({
3652
+ ...this._def,
3653
+ returns: returnType
3654
+ });
3655
+ }
3656
+ implement(func) {
3657
+ const validatedFunc = this.parse(func);
3658
+ return validatedFunc;
3659
+ }
3660
+ strictImplement(func) {
3661
+ const validatedFunc = this.parse(func);
3662
+ return validatedFunc;
3663
+ }
3664
+ static create(args, returns, params) {
3665
+ return new _ZodFunction({
3666
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3667
+ returns: returns || ZodUnknown.create(),
3668
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3669
+ ...processCreateParams(params)
3670
+ });
3671
+ }
3672
+ };
3673
+ var ZodLazy = class extends ZodType {
3674
+ get schema() {
3675
+ return this._def.getter();
3676
+ }
3677
+ _parse(input) {
3678
+ const { ctx } = this._processInputParams(input);
3679
+ const lazySchema = this._def.getter();
3680
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3681
+ }
3682
+ };
3683
+ ZodLazy.create = (getter, params) => {
3684
+ return new ZodLazy({
3685
+ getter,
3686
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3687
+ ...processCreateParams(params)
3688
+ });
3689
+ };
3690
+ var ZodLiteral = class extends ZodType {
3691
+ _parse(input) {
3692
+ if (input.data !== this._def.value) {
3693
+ const ctx = this._getOrReturnCtx(input);
3694
+ addIssueToContext(ctx, {
3695
+ received: ctx.data,
3696
+ code: ZodIssueCode.invalid_literal,
3697
+ expected: this._def.value
3698
+ });
3699
+ return INVALID;
3700
+ }
3701
+ return { status: "valid", value: input.data };
3702
+ }
3703
+ get value() {
3704
+ return this._def.value;
3705
+ }
3706
+ };
3707
+ ZodLiteral.create = (value, params) => {
3708
+ return new ZodLiteral({
3709
+ value,
3710
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3711
+ ...processCreateParams(params)
3712
+ });
3713
+ };
3714
+ function createZodEnum(values, params) {
3715
+ return new ZodEnum({
3716
+ values,
3717
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3718
+ ...processCreateParams(params)
3719
+ });
3720
+ }
3721
+ var ZodEnum = class _ZodEnum extends ZodType {
3722
+ _parse(input) {
3723
+ if (typeof input.data !== "string") {
3724
+ const ctx = this._getOrReturnCtx(input);
3725
+ const expectedValues = this._def.values;
3726
+ addIssueToContext(ctx, {
3727
+ expected: util.joinValues(expectedValues),
3728
+ received: ctx.parsedType,
3729
+ code: ZodIssueCode.invalid_type
3730
+ });
3731
+ return INVALID;
3732
+ }
3733
+ if (!this._cache) {
3734
+ this._cache = new Set(this._def.values);
3735
+ }
3736
+ if (!this._cache.has(input.data)) {
3737
+ const ctx = this._getOrReturnCtx(input);
3738
+ const expectedValues = this._def.values;
3739
+ addIssueToContext(ctx, {
3740
+ received: ctx.data,
3741
+ code: ZodIssueCode.invalid_enum_value,
3742
+ options: expectedValues
3743
+ });
3744
+ return INVALID;
3745
+ }
3746
+ return OK(input.data);
3747
+ }
3748
+ get options() {
3749
+ return this._def.values;
3750
+ }
3751
+ get enum() {
3752
+ const enumValues = {};
3753
+ for (const val of this._def.values) {
3754
+ enumValues[val] = val;
3755
+ }
3756
+ return enumValues;
3757
+ }
3758
+ get Values() {
3759
+ const enumValues = {};
3760
+ for (const val of this._def.values) {
3761
+ enumValues[val] = val;
3762
+ }
3763
+ return enumValues;
3764
+ }
3765
+ get Enum() {
3766
+ const enumValues = {};
3767
+ for (const val of this._def.values) {
3768
+ enumValues[val] = val;
3769
+ }
3770
+ return enumValues;
3771
+ }
3772
+ extract(values, newDef = this._def) {
3773
+ return _ZodEnum.create(values, {
3774
+ ...this._def,
3775
+ ...newDef
3776
+ });
3777
+ }
3778
+ exclude(values, newDef = this._def) {
3779
+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3780
+ ...this._def,
3781
+ ...newDef
3782
+ });
3783
+ }
3784
+ };
3785
+ ZodEnum.create = createZodEnum;
3786
+ var ZodNativeEnum = class extends ZodType {
3787
+ _parse(input) {
3788
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3789
+ const ctx = this._getOrReturnCtx(input);
3790
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3791
+ const expectedValues = util.objectValues(nativeEnumValues);
3792
+ addIssueToContext(ctx, {
3793
+ expected: util.joinValues(expectedValues),
3794
+ received: ctx.parsedType,
3795
+ code: ZodIssueCode.invalid_type
3796
+ });
3797
+ return INVALID;
3798
+ }
3799
+ if (!this._cache) {
3800
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
3801
+ }
3802
+ if (!this._cache.has(input.data)) {
3803
+ const expectedValues = util.objectValues(nativeEnumValues);
3804
+ addIssueToContext(ctx, {
3805
+ received: ctx.data,
3806
+ code: ZodIssueCode.invalid_enum_value,
3807
+ options: expectedValues
3808
+ });
3809
+ return INVALID;
3810
+ }
3811
+ return OK(input.data);
3812
+ }
3813
+ get enum() {
3814
+ return this._def.values;
3815
+ }
3816
+ };
3817
+ ZodNativeEnum.create = (values, params) => {
3818
+ return new ZodNativeEnum({
3819
+ values,
3820
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3821
+ ...processCreateParams(params)
3822
+ });
3823
+ };
3824
+ var ZodPromise = class extends ZodType {
3825
+ unwrap() {
3826
+ return this._def.type;
3827
+ }
3828
+ _parse(input) {
3829
+ const { ctx } = this._processInputParams(input);
3830
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3831
+ addIssueToContext(ctx, {
3832
+ code: ZodIssueCode.invalid_type,
3833
+ expected: ZodParsedType.promise,
3834
+ received: ctx.parsedType
3835
+ });
3836
+ return INVALID;
3837
+ }
3838
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3839
+ return OK(promisified.then((data) => {
3840
+ return this._def.type.parseAsync(data, {
3841
+ path: ctx.path,
3842
+ errorMap: ctx.common.contextualErrorMap
3843
+ });
3844
+ }));
3845
+ }
3846
+ };
3847
+ ZodPromise.create = (schema, params) => {
3848
+ return new ZodPromise({
3849
+ type: schema,
3850
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3851
+ ...processCreateParams(params)
3852
+ });
3853
+ };
3854
+ var ZodEffects = class extends ZodType {
3855
+ innerType() {
3856
+ return this._def.schema;
3857
+ }
3858
+ sourceType() {
3859
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3860
+ }
3861
+ _parse(input) {
3862
+ const { status, ctx } = this._processInputParams(input);
3863
+ const effect = this._def.effect || null;
3864
+ const checkCtx = {
3865
+ addIssue: (arg) => {
3866
+ addIssueToContext(ctx, arg);
3867
+ if (arg.fatal) {
3868
+ status.abort();
3869
+ } else {
3870
+ status.dirty();
3871
+ }
3872
+ },
3873
+ get path() {
3874
+ return ctx.path;
3875
+ }
3876
+ };
3877
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3878
+ if (effect.type === "preprocess") {
3879
+ const processed = effect.transform(ctx.data, checkCtx);
3880
+ if (ctx.common.async) {
3881
+ return Promise.resolve(processed).then(async (processed2) => {
3882
+ if (status.value === "aborted")
3883
+ return INVALID;
3884
+ const result = await this._def.schema._parseAsync({
3885
+ data: processed2,
3886
+ path: ctx.path,
3887
+ parent: ctx
3888
+ });
3889
+ if (result.status === "aborted")
3890
+ return INVALID;
3891
+ if (result.status === "dirty")
3892
+ return DIRTY(result.value);
3893
+ if (status.value === "dirty")
3894
+ return DIRTY(result.value);
3895
+ return result;
3896
+ });
3897
+ } else {
3898
+ if (status.value === "aborted")
3899
+ return INVALID;
3900
+ const result = this._def.schema._parseSync({
3901
+ data: processed,
3902
+ path: ctx.path,
3903
+ parent: ctx
3904
+ });
3905
+ if (result.status === "aborted")
3906
+ return INVALID;
3907
+ if (result.status === "dirty")
3908
+ return DIRTY(result.value);
3909
+ if (status.value === "dirty")
3910
+ return DIRTY(result.value);
3911
+ return result;
3912
+ }
3913
+ }
3914
+ if (effect.type === "refinement") {
3915
+ const executeRefinement = (acc) => {
3916
+ const result = effect.refinement(acc, checkCtx);
3917
+ if (ctx.common.async) {
3918
+ return Promise.resolve(result);
3919
+ }
3920
+ if (result instanceof Promise) {
3921
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3922
+ }
3923
+ return acc;
3924
+ };
3925
+ if (ctx.common.async === false) {
3926
+ const inner = this._def.schema._parseSync({
3927
+ data: ctx.data,
3928
+ path: ctx.path,
3929
+ parent: ctx
3930
+ });
3931
+ if (inner.status === "aborted")
3932
+ return INVALID;
3933
+ if (inner.status === "dirty")
3934
+ status.dirty();
3935
+ executeRefinement(inner.value);
3936
+ return { status: status.value, value: inner.value };
3937
+ } else {
3938
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3939
+ if (inner.status === "aborted")
3940
+ return INVALID;
3941
+ if (inner.status === "dirty")
3942
+ status.dirty();
3943
+ return executeRefinement(inner.value).then(() => {
3944
+ return { status: status.value, value: inner.value };
3945
+ });
3946
+ });
3947
+ }
3948
+ }
3949
+ if (effect.type === "transform") {
3950
+ if (ctx.common.async === false) {
3951
+ const base = this._def.schema._parseSync({
3952
+ data: ctx.data,
3953
+ path: ctx.path,
3954
+ parent: ctx
3955
+ });
3956
+ if (!isValid(base))
3957
+ return INVALID;
3958
+ const result = effect.transform(base.value, checkCtx);
3959
+ if (result instanceof Promise) {
3960
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3961
+ }
3962
+ return { status: status.value, value: result };
3963
+ } else {
3964
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3965
+ if (!isValid(base))
3966
+ return INVALID;
3967
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3968
+ status: status.value,
3969
+ value: result
3970
+ }));
3971
+ });
3972
+ }
3973
+ }
3974
+ util.assertNever(effect);
3975
+ }
3976
+ };
3977
+ ZodEffects.create = (schema, effect, params) => {
3978
+ return new ZodEffects({
3979
+ schema,
3980
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3981
+ effect,
3982
+ ...processCreateParams(params)
3983
+ });
3984
+ };
3985
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3986
+ return new ZodEffects({
3987
+ schema,
3988
+ effect: { type: "preprocess", transform: preprocess },
3989
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3990
+ ...processCreateParams(params)
3991
+ });
3992
+ };
3993
+ var ZodOptional = class extends ZodType {
3994
+ _parse(input) {
3995
+ const parsedType = this._getType(input);
3996
+ if (parsedType === ZodParsedType.undefined) {
3997
+ return OK(void 0);
3998
+ }
3999
+ return this._def.innerType._parse(input);
4000
+ }
4001
+ unwrap() {
4002
+ return this._def.innerType;
4003
+ }
4004
+ };
4005
+ ZodOptional.create = (type, params) => {
4006
+ return new ZodOptional({
4007
+ innerType: type,
4008
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
4009
+ ...processCreateParams(params)
4010
+ });
4011
+ };
4012
+ var ZodNullable = class extends ZodType {
4013
+ _parse(input) {
4014
+ const parsedType = this._getType(input);
4015
+ if (parsedType === ZodParsedType.null) {
4016
+ return OK(null);
4017
+ }
4018
+ return this._def.innerType._parse(input);
4019
+ }
4020
+ unwrap() {
4021
+ return this._def.innerType;
4022
+ }
4023
+ };
4024
+ ZodNullable.create = (type, params) => {
4025
+ return new ZodNullable({
4026
+ innerType: type,
4027
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
4028
+ ...processCreateParams(params)
4029
+ });
4030
+ };
4031
+ var ZodDefault = class extends ZodType {
4032
+ _parse(input) {
4033
+ const { ctx } = this._processInputParams(input);
4034
+ let data = ctx.data;
4035
+ if (ctx.parsedType === ZodParsedType.undefined) {
4036
+ data = this._def.defaultValue();
4037
+ }
4038
+ return this._def.innerType._parse({
4039
+ data,
4040
+ path: ctx.path,
4041
+ parent: ctx
4042
+ });
4043
+ }
4044
+ removeDefault() {
4045
+ return this._def.innerType;
4046
+ }
4047
+ };
4048
+ ZodDefault.create = (type, params) => {
4049
+ return new ZodDefault({
4050
+ innerType: type,
4051
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
4052
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4053
+ ...processCreateParams(params)
4054
+ });
4055
+ };
4056
+ var ZodCatch = class extends ZodType {
4057
+ _parse(input) {
4058
+ const { ctx } = this._processInputParams(input);
4059
+ const newCtx = {
4060
+ ...ctx,
4061
+ common: {
4062
+ ...ctx.common,
4063
+ issues: []
4064
+ }
4065
+ };
4066
+ const result = this._def.innerType._parse({
4067
+ data: newCtx.data,
4068
+ path: newCtx.path,
4069
+ parent: {
4070
+ ...newCtx
4071
+ }
4072
+ });
4073
+ if (isAsync(result)) {
4074
+ return result.then((result2) => {
4075
+ return {
4076
+ status: "valid",
4077
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
4078
+ get error() {
4079
+ return new ZodError(newCtx.common.issues);
4080
+ },
4081
+ input: newCtx.data
4082
+ })
4083
+ };
4084
+ });
4085
+ } else {
4086
+ return {
4087
+ status: "valid",
4088
+ value: result.status === "valid" ? result.value : this._def.catchValue({
4089
+ get error() {
4090
+ return new ZodError(newCtx.common.issues);
4091
+ },
4092
+ input: newCtx.data
4093
+ })
4094
+ };
4095
+ }
4096
+ }
4097
+ removeCatch() {
4098
+ return this._def.innerType;
4099
+ }
4100
+ };
4101
+ ZodCatch.create = (type, params) => {
4102
+ return new ZodCatch({
4103
+ innerType: type,
4104
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4105
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4106
+ ...processCreateParams(params)
4107
+ });
4108
+ };
4109
+ var ZodNaN = class extends ZodType {
4110
+ _parse(input) {
4111
+ const parsedType = this._getType(input);
4112
+ if (parsedType !== ZodParsedType.nan) {
4113
+ const ctx = this._getOrReturnCtx(input);
4114
+ addIssueToContext(ctx, {
4115
+ code: ZodIssueCode.invalid_type,
4116
+ expected: ZodParsedType.nan,
4117
+ received: ctx.parsedType
4118
+ });
4119
+ return INVALID;
4120
+ }
4121
+ return { status: "valid", value: input.data };
4122
+ }
4123
+ };
4124
+ ZodNaN.create = (params) => {
4125
+ return new ZodNaN({
4126
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4127
+ ...processCreateParams(params)
4128
+ });
4129
+ };
4130
+ var BRAND = /* @__PURE__ */ Symbol("zod_brand");
4131
+ var ZodBranded = class extends ZodType {
4132
+ _parse(input) {
4133
+ const { ctx } = this._processInputParams(input);
4134
+ const data = ctx.data;
4135
+ return this._def.type._parse({
4136
+ data,
4137
+ path: ctx.path,
4138
+ parent: ctx
4139
+ });
4140
+ }
4141
+ unwrap() {
4142
+ return this._def.type;
4143
+ }
4144
+ };
4145
+ var ZodPipeline = class _ZodPipeline extends ZodType {
4146
+ _parse(input) {
4147
+ const { status, ctx } = this._processInputParams(input);
4148
+ if (ctx.common.async) {
4149
+ const handleAsync = async () => {
4150
+ const inResult = await this._def.in._parseAsync({
4151
+ data: ctx.data,
4152
+ path: ctx.path,
4153
+ parent: ctx
4154
+ });
4155
+ if (inResult.status === "aborted")
4156
+ return INVALID;
4157
+ if (inResult.status === "dirty") {
4158
+ status.dirty();
4159
+ return DIRTY(inResult.value);
4160
+ } else {
4161
+ return this._def.out._parseAsync({
4162
+ data: inResult.value,
4163
+ path: ctx.path,
4164
+ parent: ctx
4165
+ });
4166
+ }
4167
+ };
4168
+ return handleAsync();
4169
+ } else {
4170
+ const inResult = this._def.in._parseSync({
4171
+ data: ctx.data,
4172
+ path: ctx.path,
4173
+ parent: ctx
4174
+ });
4175
+ if (inResult.status === "aborted")
4176
+ return INVALID;
4177
+ if (inResult.status === "dirty") {
4178
+ status.dirty();
4179
+ return {
4180
+ status: "dirty",
4181
+ value: inResult.value
4182
+ };
4183
+ } else {
4184
+ return this._def.out._parseSync({
4185
+ data: inResult.value,
4186
+ path: ctx.path,
4187
+ parent: ctx
4188
+ });
4189
+ }
4190
+ }
4191
+ }
4192
+ static create(a, b) {
4193
+ return new _ZodPipeline({
4194
+ in: a,
4195
+ out: b,
4196
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
4197
+ });
4198
+ }
4199
+ };
4200
+ var ZodReadonly = class extends ZodType {
4201
+ _parse(input) {
4202
+ const result = this._def.innerType._parse(input);
4203
+ const freeze = (data) => {
4204
+ if (isValid(data)) {
4205
+ data.value = Object.freeze(data.value);
4206
+ }
4207
+ return data;
4208
+ };
4209
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4210
+ }
4211
+ unwrap() {
4212
+ return this._def.innerType;
4213
+ }
4214
+ };
4215
+ ZodReadonly.create = (type, params) => {
4216
+ return new ZodReadonly({
4217
+ innerType: type,
4218
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4219
+ ...processCreateParams(params)
4220
+ });
4221
+ };
4222
+ function cleanParams(params, data) {
4223
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4224
+ const p2 = typeof p === "string" ? { message: p } : p;
4225
+ return p2;
4226
+ }
4227
+ function custom(check, _params = {}, fatal) {
4228
+ if (check)
4229
+ return ZodAny.create().superRefine((data, ctx) => {
4230
+ const r = check(data);
4231
+ if (r instanceof Promise) {
4232
+ return r.then((r2) => {
4233
+ if (!r2) {
4234
+ const params = cleanParams(_params, data);
4235
+ const _fatal = params.fatal ?? fatal ?? true;
4236
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4237
+ }
4238
+ });
4239
+ }
4240
+ if (!r) {
4241
+ const params = cleanParams(_params, data);
4242
+ const _fatal = params.fatal ?? fatal ?? true;
4243
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4244
+ }
4245
+ return;
4246
+ });
4247
+ return ZodAny.create();
4248
+ }
4249
+ var late = {
4250
+ object: ZodObject.lazycreate
4251
+ };
4252
+ var ZodFirstPartyTypeKind;
4253
+ (function(ZodFirstPartyTypeKind2) {
4254
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4255
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4256
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4257
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4258
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4259
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4260
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4261
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4262
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4263
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4264
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4265
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4266
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4267
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4268
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4269
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4270
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4271
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4272
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4273
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4274
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4275
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4276
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4277
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4278
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4279
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4280
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4281
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4282
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4283
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4284
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4285
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4286
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4287
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4288
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4289
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4290
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4291
+ var instanceOfType = (cls, params = {
4292
+ message: `Input not instance of ${cls.name}`
4293
+ }) => custom((data) => data instanceof cls, params);
4294
+ var stringType = ZodString.create;
4295
+ var numberType = ZodNumber.create;
4296
+ var nanType = ZodNaN.create;
4297
+ var bigIntType = ZodBigInt.create;
4298
+ var booleanType = ZodBoolean.create;
4299
+ var dateType = ZodDate.create;
4300
+ var symbolType = ZodSymbol.create;
4301
+ var undefinedType = ZodUndefined.create;
4302
+ var nullType = ZodNull.create;
4303
+ var anyType = ZodAny.create;
4304
+ var unknownType = ZodUnknown.create;
4305
+ var neverType = ZodNever.create;
4306
+ var voidType = ZodVoid.create;
4307
+ var arrayType = ZodArray.create;
4308
+ var objectType = ZodObject.create;
4309
+ var strictObjectType = ZodObject.strictCreate;
4310
+ var unionType = ZodUnion.create;
4311
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
4312
+ var intersectionType = ZodIntersection.create;
4313
+ var tupleType = ZodTuple.create;
4314
+ var recordType = ZodRecord.create;
4315
+ var mapType = ZodMap.create;
4316
+ var setType = ZodSet.create;
4317
+ var functionType = ZodFunction.create;
4318
+ var lazyType = ZodLazy.create;
4319
+ var literalType = ZodLiteral.create;
4320
+ var enumType = ZodEnum.create;
4321
+ var nativeEnumType = ZodNativeEnum.create;
4322
+ var promiseType = ZodPromise.create;
4323
+ var effectsType = ZodEffects.create;
4324
+ var optionalType = ZodOptional.create;
4325
+ var nullableType = ZodNullable.create;
4326
+ var preprocessType = ZodEffects.createWithPreprocess;
4327
+ var pipelineType = ZodPipeline.create;
4328
+ var ostring = () => stringType().optional();
4329
+ var onumber = () => numberType().optional();
4330
+ var oboolean = () => booleanType().optional();
4331
+ var coerce = {
4332
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4333
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4334
+ boolean: ((arg) => ZodBoolean.create({
4335
+ ...arg,
4336
+ coerce: true
4337
+ })),
4338
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4339
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4340
+ };
4341
+ var NEVER = INVALID;
4342
+
4343
+ // ../schema/dist/index.js
4344
+ var unknownCounter = 0;
4345
+ var genId = (prefix) => `${prefix}-${Date.now().toString(36)}-${(unknownCounter++).toString(36)}`;
4346
+ var responseTypeSchema = external_exports.enum(["TEXT", "ANALYTICS", "ERROR"]);
4347
+ var textFormatSchema = external_exports.enum(["PLAIN_TEXT", "MARKDOWN"]);
4348
+ var dataSourceSchema = external_exports.enum(["REPLICA_DATABASE", "CACHE", "EXTERNAL_SOURCE"]);
4349
+ var chartTypeSchema = external_exports.enum([
4350
+ "LINE",
4351
+ "BAR",
4352
+ "AREA",
4353
+ "PIE",
4354
+ "DONUT",
4355
+ "SCATTER",
4356
+ "HEATMAP",
4357
+ "STACKED_BAR",
4358
+ "STACKED_AREA"
4359
+ ]);
4360
+ var severitySchema = external_exports.enum(["INFO", "SUCCESS", "WARNING", "CRITICAL"]);
4361
+ var trendSchema = external_exports.enum(["UP", "DOWN", "STABLE"]);
4362
+ var filterTypeSchema = external_exports.enum([
4363
+ "SELECT",
4364
+ "MULTI_SELECT",
4365
+ "DATE_RANGE",
4366
+ "NUMBER_RANGE",
4367
+ "SEARCH"
4368
+ ]);
4369
+ var progressPhaseSchema = external_exports.enum(["THINKING", "RUNNING_TOOL", "COMPOSING"]);
4370
+ var responseMetadataSchema = external_exports.object({
4371
+ generatedAt: external_exports.string().optional(),
4372
+ dataSource: dataSourceSchema.optional(),
4373
+ refreshable: external_exports.boolean().optional()
4374
+ }).passthrough();
4375
+ var kpiItemSchema = external_exports.object({
4376
+ label: external_exports.string(),
4377
+ value: external_exports.unknown(),
4378
+ formattedValue: external_exports.string().optional(),
4379
+ trend: trendSchema.optional(),
4380
+ percentageChange: external_exports.number().optional()
4381
+ });
4382
+ var tableColumnSchema = external_exports.object({
4383
+ key: external_exports.string(),
4384
+ label: external_exports.string()
4385
+ });
4386
+ var recommendationItemSchema = external_exports.object({
4387
+ title: external_exports.string(),
4388
+ description: external_exports.string()
4389
+ });
4390
+ var filterDefSchema = external_exports.object({
4391
+ field: external_exports.string(),
4392
+ label: external_exports.string(),
4393
+ filterType: filterTypeSchema,
4394
+ options: external_exports.array(external_exports.string()).optional()
4395
+ });
4396
+ var dataRow = external_exports.record(external_exports.string(), external_exports.unknown());
4397
+ var textBlockSchema = external_exports.object({
4398
+ id: external_exports.string(),
4399
+ type: external_exports.literal("TEXT"),
4400
+ content: external_exports.string()
4401
+ });
4402
+ var kpiBlockSchema = external_exports.object({
4403
+ id: external_exports.string(),
4404
+ type: external_exports.literal("KPI"),
4405
+ title: external_exports.string().optional(),
4406
+ items: external_exports.array(kpiItemSchema)
4407
+ });
4408
+ var chartBlockSchema = external_exports.object({
4409
+ id: external_exports.string(),
4410
+ type: external_exports.literal("CHART"),
4411
+ title: external_exports.string().optional(),
4412
+ chartType: chartTypeSchema,
4413
+ data: external_exports.array(dataRow)
4414
+ });
4415
+ var tableBlockSchema = external_exports.object({
4416
+ id: external_exports.string(),
4417
+ type: external_exports.literal("TABLE"),
4418
+ title: external_exports.string().optional(),
4419
+ columns: external_exports.array(tableColumnSchema),
4420
+ rows: external_exports.array(dataRow)
4421
+ });
4422
+ var insightBlockSchema = external_exports.object({
4423
+ id: external_exports.string(),
4424
+ type: external_exports.literal("INSIGHT"),
4425
+ severity: severitySchema,
4426
+ title: external_exports.string(),
4427
+ description: external_exports.string()
4428
+ });
4429
+ var recommendationBlockSchema = external_exports.object({
4430
+ id: external_exports.string(),
4431
+ type: external_exports.literal("RECOMMENDATION"),
4432
+ items: external_exports.array(recommendationItemSchema)
4433
+ });
4434
+ var filterBlockSchema = external_exports.object({
4435
+ id: external_exports.string(),
4436
+ type: external_exports.literal("FILTER"),
4437
+ filters: external_exports.array(filterDefSchema)
4438
+ });
4439
+ var knownBlockSchema = external_exports.discriminatedUnion("type", [
4440
+ textBlockSchema,
4441
+ kpiBlockSchema,
4442
+ chartBlockSchema,
4443
+ tableBlockSchema,
4444
+ insightBlockSchema,
4445
+ recommendationBlockSchema,
4446
+ filterBlockSchema
4447
+ ]);
4448
+ var toUnknownBlock = (raw) => {
4449
+ const obj = raw && typeof raw === "object" ? raw : {};
4450
+ return {
4451
+ ...obj,
4452
+ id: typeof obj.id === "string" ? obj.id : genId("block"),
4453
+ type: typeof obj.type === "string" ? obj.type : "UNKNOWN"
4454
+ };
4455
+ };
4456
+ var blockSchema = external_exports.union([
4457
+ knownBlockSchema,
4458
+ external_exports.any().transform(toUnknownBlock)
4459
+ ]);
4460
+ var textResponseSchema = external_exports.object({
4461
+ id: external_exports.string(),
4462
+ type: external_exports.literal("TEXT"),
4463
+ content: external_exports.object({ format: textFormatSchema, value: external_exports.string() }),
4464
+ metadata: responseMetadataSchema.optional()
4465
+ });
4466
+ var analyticsResponseSchema = external_exports.object({
4467
+ id: external_exports.string(),
4468
+ type: external_exports.literal("ANALYTICS"),
4469
+ content: external_exports.object({
4470
+ title: external_exports.string().optional(),
4471
+ // Use the lenient block schema so one malformed block can't sink the whole response.
4472
+ blocks: external_exports.array(blockSchema)
4473
+ }),
4474
+ metadata: responseMetadataSchema.optional()
4475
+ });
4476
+ var errorResponseSchema = external_exports.object({
4477
+ id: external_exports.string(),
4478
+ type: external_exports.literal("ERROR"),
4479
+ content: external_exports.object({ message: external_exports.string() }),
4480
+ metadata: responseMetadataSchema.optional()
4481
+ });
4482
+ var aiResponseSchema = external_exports.discriminatedUnion("type", [
4483
+ textResponseSchema,
4484
+ analyticsResponseSchema,
4485
+ errorResponseSchema
4486
+ ]);
4487
+ var makeErrorResponse = (message, id) => ({
4488
+ id: id ?? genId("error"),
4489
+ type: "ERROR",
4490
+ content: { message }
4491
+ });
4492
+ function parseAiResponse(input) {
4493
+ const result = aiResponseSchema.safeParse(input);
4494
+ if (result.success) return result.data;
4495
+ return makeErrorResponse(
4496
+ "The response could not be displayed (it did not match the expected format)."
4497
+ );
4498
+ }
4499
+ function safeParseAiResponse(input) {
4500
+ return aiResponseSchema.safeParse(input);
4501
+ }
4502
+ function parseBlock(input) {
4503
+ return blockSchema.parse(input);
4504
+ }
4505
+ var progressEventSchema = external_exports.object({
4506
+ phase: progressPhaseSchema,
4507
+ message: external_exports.string().optional(),
4508
+ tool: external_exports.string().optional()
4509
+ });
4510
+ var responseStartSchema = external_exports.object({
4511
+ id: external_exports.string(),
4512
+ type: responseTypeSchema,
4513
+ metadata: responseMetadataSchema.optional(),
4514
+ title: external_exports.string().optional()
4515
+ });
4516
+ var contentEventSchema = external_exports.object({
4517
+ format: textFormatSchema.optional(),
4518
+ value: external_exports.string().optional(),
4519
+ message: external_exports.string().optional()
4520
+ });
4521
+ var responseEndSchema = external_exports.object({
4522
+ status: external_exports.enum(["COMPLETED", "ERROR"])
4523
+ });
4524
+ var errorEventSchema = external_exports.object({
4525
+ message: external_exports.string().optional()
4526
+ });
4527
+ function parseSseEvent(eventName, raw) {
4528
+ let json;
4529
+ try {
4530
+ json = raw.length ? JSON.parse(raw) : {};
4531
+ } catch {
4532
+ return { event: "error", data: { message: "Malformed event payload from server." } };
4533
+ }
4534
+ switch (eventName) {
4535
+ case "progress": {
4536
+ const r = progressEventSchema.safeParse(json);
4537
+ return r.success ? { event: "progress", data: r.data } : { event: "progress", data: { phase: "THINKING" } };
4538
+ }
4539
+ case "response_start": {
4540
+ const r = responseStartSchema.safeParse(json);
4541
+ return r.success ? { event: "response_start", data: r.data } : { event: "error", data: { message: "Invalid response_start event." } };
4542
+ }
4543
+ case "content": {
4544
+ const r = contentEventSchema.safeParse(json);
4545
+ return r.success ? { event: "content", data: r.data } : { event: "content", data: {} };
4546
+ }
4547
+ case "block":
4548
+ return { event: "block", data: blockSchema.parse(json) };
4549
+ case "response_end": {
4550
+ const r = responseEndSchema.safeParse(json);
4551
+ return r.success ? { event: "response_end", data: r.data } : { event: "response_end", data: { status: "COMPLETED" } };
4552
+ }
4553
+ case "error":
4554
+ default: {
4555
+ const r = errorEventSchema.safeParse(json);
4556
+ return { event: "error", data: r.success ? r.data : {} };
4557
+ }
4558
+ }
4559
+ }
4560
+ var initialStreamState = { phase: "idle" };
4561
+ function startResponse(data) {
4562
+ const type = data.type;
4563
+ const base = { id: data.id, metadata: data.metadata };
4564
+ switch (type) {
4565
+ case "ANALYTICS":
4566
+ return { ...base, type: "ANALYTICS", content: { title: data.title, blocks: [] } };
4567
+ case "ERROR":
4568
+ return { ...base, type: "ERROR", content: { message: "" } };
4569
+ case "TEXT":
4570
+ default:
4571
+ return { ...base, type: "TEXT", content: { format: "PLAIN_TEXT", value: "" } };
4572
+ }
4573
+ }
4574
+ function streamReducer(state, event) {
4575
+ switch (event.event) {
4576
+ case "progress":
4577
+ return {
4578
+ ...state,
4579
+ phase: event.data.phase,
4580
+ progressMessage: event.data.message ?? state.progressMessage,
4581
+ tool: event.data.tool
4582
+ };
4583
+ case "response_start":
4584
+ return {
4585
+ ...state,
4586
+ phase: "COMPOSING",
4587
+ tool: void 0,
4588
+ response: startResponse(event.data),
4589
+ error: void 0
4590
+ };
4591
+ case "content": {
4592
+ const response = state.response;
4593
+ if (!response) return state;
4594
+ if (response.type === "TEXT") {
4595
+ return {
4596
+ ...state,
4597
+ response: {
4598
+ ...response,
4599
+ content: {
4600
+ format: event.data.format ?? response.content.format,
4601
+ value: event.data.value ?? response.content.value
4602
+ }
4603
+ }
4604
+ };
4605
+ }
4606
+ if (response.type === "ERROR") {
4607
+ return {
4608
+ ...state,
4609
+ response: {
4610
+ ...response,
4611
+ content: { message: event.data.message ?? response.content.message }
4612
+ }
4613
+ };
4614
+ }
4615
+ return state;
4616
+ }
4617
+ case "block": {
4618
+ const response = state.response;
4619
+ if (!response || response.type !== "ANALYTICS") return state;
4620
+ return {
4621
+ ...state,
4622
+ response: {
4623
+ ...response,
4624
+ content: {
4625
+ ...response.content,
4626
+ blocks: [...response.content.blocks, event.data]
4627
+ }
4628
+ }
4629
+ };
4630
+ }
4631
+ case "response_end": {
4632
+ if (event.data.status === "ERROR") {
4633
+ const message = state.response?.type === "ERROR" && state.response.content.message || state.error || "The request failed.";
4634
+ return { ...state, phase: "error", error: message };
4635
+ }
4636
+ return { ...state, phase: "done", progressMessage: void 0, tool: void 0 };
4637
+ }
4638
+ case "error":
4639
+ return {
4640
+ ...state,
4641
+ phase: "error",
4642
+ error: event.data.message ?? "The stream encountered a fatal error."
4643
+ };
4644
+ default:
4645
+ return state;
4646
+ }
4647
+ }
4648
+
4649
+ // src/sse.ts
4650
+ var trimTrailingSlash = (s) => s.replace(/\/+$/, "");
4651
+ function messageUrl(baseUrl, conversationId) {
4652
+ return `${trimTrailingSlash(baseUrl)}/api/conversations/${encodeURIComponent(
4653
+ conversationId
4654
+ )}/messages`;
4655
+ }
4656
+ async function* streamMessage(options) {
4657
+ const { baseUrl, conversationId, message, headers, signal } = options;
4658
+ const doFetch = options.fetchImpl ?? fetch;
4659
+ let response;
4660
+ try {
4661
+ response = await doFetch(messageUrl(baseUrl, conversationId), {
4662
+ method: "POST",
4663
+ headers: {
4664
+ "Content-Type": "application/json",
4665
+ Accept: "text/event-stream",
4666
+ ...headers
4667
+ },
4668
+ body: JSON.stringify({ message }),
4669
+ signal
4670
+ });
4671
+ } catch (err) {
4672
+ if (isAbort(err)) return;
4673
+ yield { event: "error", data: { message: networkMessage(err) } };
4674
+ return;
4675
+ }
4676
+ if (!response.ok) {
4677
+ yield {
4678
+ event: "error",
4679
+ data: { message: `Request failed (HTTP ${response.status}).` }
4680
+ };
4681
+ return;
4682
+ }
4683
+ if (!response.body) {
4684
+ yield { event: "error", data: { message: "Response has no readable stream body." } };
4685
+ return;
4686
+ }
4687
+ const reader = response.body.getReader();
4688
+ const decoder = new TextDecoder();
4689
+ let buffer = "";
4690
+ try {
4691
+ for (; ; ) {
4692
+ const { value, done } = await reader.read();
4693
+ if (done) break;
4694
+ buffer += decoder.decode(value, { stream: true });
4695
+ let sep;
4696
+ while ((sep = indexOfFrameSeparator(buffer)) !== -1) {
4697
+ const frame = buffer.slice(0, sep);
4698
+ buffer = buffer.slice(frameEnd(buffer, sep));
4699
+ const parsed = parseFrame(frame);
4700
+ if (parsed) yield parseSseEvent(parsed.event, parsed.data);
4701
+ }
4702
+ }
4703
+ const tail = parseFrame(buffer);
4704
+ if (tail) yield parseSseEvent(tail.event, tail.data);
4705
+ } catch (err) {
4706
+ if (isAbort(err)) return;
4707
+ yield { event: "error", data: { message: networkMessage(err) } };
4708
+ } finally {
4709
+ reader.releaseLock?.();
4710
+ }
4711
+ }
4712
+ function indexOfFrameSeparator(buffer) {
4713
+ const lf = buffer.indexOf("\n\n");
4714
+ const crlf = buffer.indexOf("\r\n\r\n");
4715
+ if (lf === -1) return crlf;
4716
+ if (crlf === -1) return lf;
4717
+ return Math.min(lf, crlf);
4718
+ }
4719
+ function frameEnd(buffer, sep) {
4720
+ return buffer.startsWith("\r\n\r\n", sep) ? sep + 4 : sep + 2;
4721
+ }
4722
+ function parseFrame(frame) {
4723
+ const trimmed = frame.replace(/^\r?\n+/, "");
4724
+ if (!trimmed.trim()) return null;
4725
+ let event = "message";
4726
+ const dataLines = [];
4727
+ for (const rawLine of trimmed.split(/\r?\n/)) {
4728
+ if (!rawLine || rawLine.startsWith(":")) continue;
4729
+ const colon = rawLine.indexOf(":");
4730
+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
4731
+ let value = colon === -1 ? "" : rawLine.slice(colon + 1);
4732
+ if (value.startsWith(" ")) value = value.slice(1);
4733
+ if (field === "event") event = value;
4734
+ else if (field === "data") dataLines.push(value);
4735
+ }
4736
+ if (dataLines.length === 0) return null;
4737
+ return { event, data: dataLines.join("\n") };
4738
+ }
4739
+ function isAbort(err) {
4740
+ return err instanceof DOMException && err.name === "AbortError" || typeof err === "object" && err !== null && err.name === "AbortError";
4741
+ }
4742
+ function networkMessage(err) {
4743
+ if (err instanceof Error && err.message) return err.message;
4744
+ return "Network error while streaming the response.";
4745
+ }
4746
+
4747
+ // src/useAiStream.ts
4748
+ function reducer(state, action) {
4749
+ if (action.kind === "reset") return initialStreamState;
4750
+ return streamReducer(state, action.event);
4751
+ }
4752
+ function useAiStream(options) {
4753
+ const { baseUrl, conversationId, message, headers, fetchImpl, enabled = true } = options;
4754
+ const [state, dispatch] = useReducer(reducer, initialStreamState);
4755
+ const [isStreaming, setIsStreaming] = useState(false);
4756
+ const abortRef = useRef(null);
4757
+ const paramsRef = useRef({
4758
+ baseUrl,
4759
+ conversationId,
4760
+ message,
4761
+ headers,
4762
+ fetchImpl
4763
+ });
4764
+ paramsRef.current = { baseUrl, conversationId, message, headers, fetchImpl };
4765
+ const stop = useCallback(() => {
4766
+ abortRef.current?.abort();
4767
+ abortRef.current = null;
4768
+ setIsStreaming(false);
4769
+ }, []);
4770
+ const start = useCallback(() => {
4771
+ const { conversationId: c, message: m } = paramsRef.current;
4772
+ if (!c || !m) return;
4773
+ abortRef.current?.abort();
4774
+ const controller = new AbortController();
4775
+ abortRef.current = controller;
4776
+ dispatch({ kind: "reset" });
4777
+ dispatch({ kind: "event", event: { event: "progress", data: { phase: "THINKING" } } });
4778
+ setIsStreaming(true);
4779
+ void (async () => {
4780
+ try {
4781
+ for await (const evt of streamMessage({
4782
+ ...paramsRef.current,
4783
+ signal: controller.signal
4784
+ })) {
4785
+ if (controller.signal.aborted) break;
4786
+ dispatch({ kind: "event", event: evt });
4787
+ }
4788
+ } finally {
4789
+ if (abortRef.current === controller) {
4790
+ abortRef.current = null;
4791
+ setIsStreaming(false);
4792
+ }
4793
+ }
4794
+ })();
4795
+ }, []);
4796
+ useEffect(() => {
4797
+ if (!enabled) return;
4798
+ if (!conversationId || !message) return;
4799
+ start();
4800
+ return () => stop();
4801
+ }, [enabled, baseUrl, conversationId, message]);
4802
+ return { ...state, isStreaming, start, stop };
4803
+ }
4804
+ function AiStream({
4805
+ components,
4806
+ onAction = noopAction,
4807
+ className,
4808
+ renderLoading,
4809
+ renderError,
4810
+ ...streamOptions
4811
+ }) {
4812
+ const state = useAiStream(streamOptions);
4813
+ const { phase, response, error } = state;
4814
+ const busy = phase !== "done" && phase !== "error";
4815
+ return /* @__PURE__ */ jsxs("div", { className: className ?? "rk-stream", "data-phase": phase, children: [
4816
+ response ? /* @__PURE__ */ jsx(AiRenderer, { response, components, onAction }) : null,
4817
+ busy ? renderLoading?.(state) ?? /* @__PURE__ */ jsx(DefaultLoading, { state }) : null,
4818
+ phase === "error" && !response ? renderError?.(error ?? "Something went wrong.") ?? /* @__PURE__ */ jsx("div", { className: "rk-block rk-error", role: "alert", children: error ?? "Something went wrong." }) : null
4819
+ ] });
4820
+ }
4821
+ var PHASE_LABEL = {
4822
+ idle: "Starting\u2026",
4823
+ THINKING: "Thinking\u2026",
4824
+ RUNNING_TOOL: "Running tools\u2026",
4825
+ COMPOSING: "Composing\u2026"
4826
+ };
4827
+ function DefaultLoading({ state }) {
4828
+ const label = state.progressMessage ?? (state.phase === "RUNNING_TOOL" && state.tool ? `Running ${state.tool}\u2026` : PHASE_LABEL[state.phase] ?? "Working\u2026");
4829
+ return /* @__PURE__ */ jsxs("div", { className: "rk-loading", role: "status", "aria-live": "polite", children: [
4830
+ /* @__PURE__ */ jsx("span", { className: "rk-spinner", "aria-hidden": true }),
4831
+ /* @__PURE__ */ jsx("span", { className: "rk-loading-label", children: label })
4832
+ ] });
4833
+ }
4834
+
4835
+ // src/conversations.ts
4836
+ var trimTrailingSlash2 = (s) => s.replace(/\/+$/, "");
4837
+ async function request(method, path, opts, body) {
4838
+ const doFetch = opts.fetchImpl ?? fetch;
4839
+ const res = await doFetch(`${trimTrailingSlash2(opts.baseUrl)}${path}`, {
4840
+ method,
4841
+ headers: {
4842
+ Accept: "application/json",
4843
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
4844
+ ...opts.headers
4845
+ },
4846
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
4847
+ signal: opts.signal
4848
+ });
4849
+ if (!res.ok) {
4850
+ throw new Error(`${method} ${path} failed (HTTP ${res.status}).`);
4851
+ }
4852
+ return res;
4853
+ }
4854
+ async function asJson(res) {
4855
+ const text = await res.text();
4856
+ return text ? JSON.parse(text) : void 0;
4857
+ }
4858
+ async function createConversation(opts) {
4859
+ const res = await request("POST", "/api/conversations", opts, { title: opts.title });
4860
+ return asJson(res);
4861
+ }
4862
+ async function listConversations(opts) {
4863
+ const res = await request("GET", "/api/conversations", opts);
4864
+ return asJson(res);
4865
+ }
4866
+ async function getConversation(opts) {
4867
+ const res = await request(
4868
+ "GET",
4869
+ `/api/conversations/${encodeURIComponent(opts.conversationId)}`,
4870
+ opts
4871
+ );
4872
+ return asJson(res);
4873
+ }
4874
+ async function renameConversation(opts) {
4875
+ const res = await request(
4876
+ "PATCH",
4877
+ `/api/conversations/${encodeURIComponent(opts.conversationId)}`,
4878
+ opts,
4879
+ { title: opts.title }
4880
+ );
4881
+ return asJson(res);
4882
+ }
4883
+ async function deleteConversation(opts) {
4884
+ await request("DELETE", `/api/conversations/${encodeURIComponent(opts.conversationId)}`, opts);
4885
+ }
4886
+ async function getMessages(opts) {
4887
+ const res = await request(
4888
+ "GET",
4889
+ `/api/conversations/${encodeURIComponent(opts.conversationId)}/messages`,
4890
+ opts
4891
+ );
4892
+ return asJson(res);
4893
+ }
4894
+
4895
+ // src/useChat.ts
4896
+ var turnSeq = 0;
4897
+ function useChat(options) {
4898
+ const { baseUrl, conversationId: initialId, titleFor, headers, fetchImpl } = options;
4899
+ const [conversationId, setConversationId] = useState(initialId);
4900
+ const [turns, setTurns] = useState([]);
4901
+ const [isStreaming, setIsStreaming] = useState(false);
4902
+ const [error, setError] = useState(void 0);
4903
+ const abortRef = useRef(null);
4904
+ const paramsRef = useRef({ baseUrl, conversationId: initialId, titleFor, headers, fetchImpl });
4905
+ paramsRef.current = { baseUrl, conversationId, titleFor, headers, fetchImpl };
4906
+ const stop = useCallback(() => {
4907
+ abortRef.current?.abort();
4908
+ abortRef.current = null;
4909
+ setIsStreaming(false);
4910
+ }, []);
4911
+ const reset = useCallback(() => {
4912
+ stop();
4913
+ setTurns([]);
4914
+ setError(void 0);
4915
+ }, [stop]);
4916
+ const newConversation = useCallback(() => {
4917
+ stop();
4918
+ setTurns([]);
4919
+ setError(void 0);
4920
+ setConversationId(void 0);
4921
+ }, [stop]);
4922
+ const send = useCallback(async (message) => {
4923
+ const text = message.trim();
4924
+ const b = paramsRef.current.baseUrl;
4925
+ if (!text) return;
4926
+ setError(void 0);
4927
+ let cid = paramsRef.current.conversationId;
4928
+ if (!cid) {
4929
+ try {
4930
+ const title = paramsRef.current.titleFor?.(text) ?? text.slice(0, 60);
4931
+ const conversation = await createConversation({
4932
+ baseUrl: b,
4933
+ title,
4934
+ headers: paramsRef.current.headers,
4935
+ fetchImpl: paramsRef.current.fetchImpl
4936
+ });
4937
+ if (!conversation.id) throw new Error("Backend did not return a conversation id.");
4938
+ cid = conversation.id;
4939
+ setConversationId(cid);
4940
+ } catch (e) {
4941
+ setError(e instanceof Error ? e.message : "Failed to create conversation.");
4942
+ return;
4943
+ }
4944
+ }
4945
+ abortRef.current?.abort();
4946
+ const controller = new AbortController();
4947
+ abortRef.current = controller;
4948
+ const turnId = `turn-${turnSeq++}`;
4949
+ setTurns((prev) => [
4950
+ ...prev,
4951
+ { id: turnId, userMessage: text, state: { ...initialStreamState, phase: "THINKING" } }
4952
+ ]);
4953
+ setIsStreaming(true);
4954
+ const updateTurn = (reduce) => setTurns((prev) => prev.map((t) => t.id === turnId ? { ...t, state: reduce(t.state) } : t));
4955
+ try {
4956
+ for await (const evt of streamMessage({
4957
+ baseUrl: b,
4958
+ conversationId: cid,
4959
+ message: text,
4960
+ headers: paramsRef.current.headers,
4961
+ fetchImpl: paramsRef.current.fetchImpl,
4962
+ signal: controller.signal
4963
+ })) {
4964
+ if (controller.signal.aborted) break;
4965
+ updateTurn((s) => streamReducer(s, evt));
4966
+ }
4967
+ } finally {
4968
+ if (abortRef.current === controller) {
4969
+ abortRef.current = null;
4970
+ setIsStreaming(false);
4971
+ }
4972
+ }
4973
+ }, []);
4974
+ useEffect(() => () => abortRef.current?.abort(), []);
4975
+ return { conversationId, turns, isStreaming, error, send, stop, reset, newConversation };
4976
+ }
4977
+
4978
+ export { AiRenderer, AiStream, ChartBlock, ErrorBoundary, ErrorView, FallbackBlock, FilterBlock, InsightBlock, KpiBlock, Markdown, RecommendationBlock, TableBlock, TextBlock, aiResponseSchema, analyticsResponseSchema, blockSchema, chartBlockSchema, chartTypeSchema, contentEventSchema, createConversation, dataSourceSchema, defaultBlockComponents, deleteConversation, errorEventSchema, errorResponseSchema, filterBlockSchema, filterDefSchema, filterTypeSchema, getConversation, getMessages, initialStreamState, insightBlockSchema, knownBlockSchema, kpiBlockSchema, kpiItemSchema, listConversations, makeErrorResponse, messageUrl, noopAction, parseAiResponse, parseBlock, parseSseEvent, progressEventSchema, progressPhaseSchema, recommendationBlockSchema, recommendationItemSchema, registerBlock, registeredBlockTypes, renameConversation, resolveBlockComponent, responseEndSchema, responseMetadataSchema, responseStartSchema, responseTypeSchema, safeParseAiResponse, severitySchema, streamMessage, streamReducer, tableBlockSchema, tableColumnSchema, textBlockSchema, textFormatSchema, textResponseSchema, trendSchema, unregisterBlock, useAiStream, useChat };
4979
+ //# sourceMappingURL=index.js.map
4980
+ //# sourceMappingURL=index.js.map