nolo-cli 0.30.0 → 0.31.0-alpha.1

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