zaileys 1.0.0 β†’ 1.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Zeative Media
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,353 @@
1
+ <div align='center'>
2
+ <img alt="Zaileys - Simplify Typescript/Javascript WhatsApp NodeJS API" src="https://socialify.git.ci/zeative/zaileys/image?description=1&amp;descriptionEditable=Zaileys%20is%20a%20simplified%20version%20of%20the%20Baileys%20package%20%0Awhich%20is%20easier%20and%20faster.&amp;font=KoHo&amp;forks=1&amp;issues=1&amp;language=1&amp;name=1&amp;owner=1&amp;pattern=Circuit%20Board&amp;pulls=1&amp;stargazers=1&amp;theme=Auto">
3
+ </div>
4
+
5
+ <h1 align="center">Zaileys - Simplify Typescript/Javascript WhatsApp NodeJS API</h1>
6
+
7
+ <div align='center'>
8
+
9
+ [![NPM Version](https://img.shields.io/npm/v/zaileys.svg)](https://www.npmjs.com/package/zaileys)
10
+ [![NPM Downloads](https://img.shields.io/npm/dw/zaileys?label=npm&color=%23CB3837)](https://www.npmjs.com/package/zaileys)
11
+ [![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/zeative/zaileys)](https://www.npmjs.com/package/zaileys)
12
+ [![GitHub License](https://img.shields.io/github/license/zeative/zaileys)](https://github.com/zeative/zaileys)
13
+ [![GitHub Repo stars](https://img.shields.io/github/stars/zeative/zaileys)](https://github.com/zeative/zaileys)
14
+ [![GitHub forks](https://img.shields.io/github/forks/zeative/zaileys)](https://github.com/zeative/zaileys)
15
+
16
+ </div>
17
+
18
+ > [!NOTE]
19
+ > Join whatsapp community for latest info [WhatsApp Channel](https://whatsapp.com/channel/0029VazENbmInlqHIWzgn33h)
20
+
21
+ > **Zaileys** is a simplified, high-performance wrapper around the Baileys library for building WhatsApp bots and integrations with TypeScript/JavaScript. Designed for simplicity, speed, and scalabilityβ€”perfect for beginners and pros alike.
22
+
23
+ ## πŸ“‹ Table of Contents
24
+
25
+ 1. [πŸš€ Features](#πŸš€-features)
26
+ 2. [πŸ’» Installation](#πŸ’»-installation)
27
+ 3. [⚑ Quick Start](#⚑-quick-start)
28
+ - [Simplify Version](#simplify-version)
29
+ 4. [πŸ” Core Concepts](#πŸ”-core-concepts)
30
+ - [Sessions & Authentication](#sessions--authentication)
31
+ - [Citation Concept](#citation-concept)
32
+ 5. [πŸ“ Examples](#πŸ“-examples)
33
+ 6. [πŸ“’ Event Handling](#πŸ“’-event-handling)
34
+ 7. [πŸ‘Ύ Worker Actions](#πŸ‘Ύ-worker-actions)
35
+ - [Sending Messages](#sending-messages)
36
+ - [Sending Media](#sending-media)
37
+ - [Presence Update](#presence-update)
38
+ - [Get Profile](#get-profile)
39
+ - [Reject Call](#reject-call)
40
+ 8. [🐞 Issues & Feedback](#🐞-issues--feedback)
41
+ 9. [❀️ Funding & Support](#❀️-funding--support)
42
+ 10. [πŸ“„ License](#πŸ“„-license)
43
+ 11. [πŸ™ Acknowledgements](#πŸ™-acknowledgements)
44
+
45
+ ## πŸš€ Features
46
+
47
+ - 🎯 **Simplified API**: Minimal boilerplateβ€”get up and running in minutes.
48
+ - πŸ”’ **Secure Multi-Device**: Full multi-device support via Baileys.
49
+ - βš™οΈ **Modular & Extensible**: Plug-and-play middleware, transports, and storage layers.
50
+ - ~~πŸ“ˆ **Built-in Logging**: Integrated with Pino for structured logs.~~
51
+ - πŸ“Ÿ **Live QRs**: Automatically generate and display WhatsApp QR codes in terminal.
52
+ - πŸ› οΈ **TypeScript First**: Full type definitions (`.d.ts`) and zero-config TS support.
53
+
54
+ ## πŸ’» Installation
55
+
56
+ Install with your preferred package manager:
57
+
58
+ ```bash
59
+ npm install zaileys
60
+ # or
61
+ yarn add zaileys
62
+ # or
63
+ pnpm add zaileys
64
+
65
+ # just install, don't run with these runtime
66
+ bun add zaileys
67
+ deno add npm:zaileys
68
+ ```
69
+
70
+ > ❗ **Compatibility Notice**
71
+ >
72
+ > - Zaileys does **not** support **Deno** and **Bun** runtimes at runtime due to `better-sqlite3` incompatibility. You may install dependencies with these runtimes, but execution requires **Node.js**.
73
+ > - Supports both **CommonJS (CJS)** and **ECMAScript Modules (ESM)**.
74
+
75
+ Ensure you are running Node.js **>= 18** as specified in `package.json`.
76
+
77
+ ## ⚑ Quick Start
78
+
79
+ Basic usage of Zaileys based on [`test/example.ts`](https://github.com/zeative/zaileys/blob/main/test/example.ts):
80
+
81
+ ```ts
82
+ // cjs
83
+ // const Client = require("zaileys");
84
+
85
+ // esm
86
+ import Client from "zaileys";
87
+
88
+ // the configuration below is the default
89
+ const wa = new Client({
90
+ prefix: "/", // command prefix
91
+ phoneNumber: 628123456789, // bot phone number for pairing
92
+ authType: "pairing", // authentication method: 'pairing' | 'qr'
93
+ ignoreMe: true, // ignore messages sent by the bot
94
+ showLogs: true, // enable message logs
95
+ autoMentions: true, // automatically user mentions
96
+ autoOnline: true, // automatically set status to online
97
+ autoRead: true, // automatically mark messages as read
98
+ autoPresence: true, // manage presence updates 'typing' or 'recording'
99
+ autoRejectCall: true, // automatically reject incoming calls
100
+ database: {
101
+ type: "sqlite", // database type: 'sqlite' | 'postgresql' | 'mysql'
102
+ connection: { url: "./session/zaileys.db" },
103
+ },
104
+ citation: {
105
+ // your own keys; will generate ctx.citation.is<Key> booleans
106
+ author: async () => {
107
+ // const res = await fetch(...)
108
+ return [628123456789];
109
+ },
110
+ myGroup: () => [120099],
111
+ vipUsers: () => [628123456789],
112
+ },
113
+ });
114
+
115
+ // Connection updates
116
+ wa.on("connection", (ctx) => {
117
+ //
118
+ });
119
+
120
+ // Message events
121
+ wa.on("messages", async (ctx) => {
122
+ // Example: checking generated flags
123
+ if (!ctx.citation?.isAuthor) return;
124
+ if (ctx.citation.isVipUsers) {
125
+ // VIP handling
126
+ }
127
+
128
+ if (ctx.text === "test") {
129
+ wa.text("Helloo", { roomId: ctx.roomId });
130
+ }
131
+ });
132
+
133
+ // Call events
134
+ wa.on("calls", (ctx) => {
135
+ //
136
+ });
137
+ ```
138
+
139
+ ### Simplify Version
140
+
141
+ ```js
142
+ // auth with pairing code
143
+ const wa = new Client({
144
+ phoneNumber: 628123456789,
145
+ authType: "pairing",
146
+ });
147
+
148
+ // auth with qr
149
+ const wa = new Client({
150
+ authType: "qr",
151
+ });
152
+
153
+ wa.on("messages", (ctx) => {
154
+ wa.reply("hello");
155
+ });
156
+ ```
157
+
158
+ ## πŸ“ Examples
159
+
160
+ Refer to [`test/example.ts`](https://github.com/zeative/zaileys/blob/main/test/example.ts) for complete example usage.
161
+
162
+ ## πŸ” Core Concepts
163
+
164
+ ### Sessions & Authentication
165
+
166
+ Zaileys persists authentication credentials and session data in a configurable database (`sqlite`, `postgresql`, or `mysql`), ensuring seamless reconnection without repeated QR scans or pairing codes. This database-driven approach enhances flexibility by:
167
+
168
+ - **Unified Storage**: Store session data and authentication credentials in a single, structured database, enabling easy backup, migration, and scalability.
169
+ - **Flexible Data Management**: Query and manage session data directly via SQL, allowing custom integrations and advanced use cases.
170
+
171
+ Configure the database in the `Client` options:
172
+
173
+ ```js
174
+ const wa = new Client({
175
+ database: {
176
+ type: "sqlite", // or 'postgresql' | 'mysql'
177
+ connection: { url: "./session/zaileys.db" }, // sqlite file path
178
+ },
179
+ });
180
+ ```
181
+
182
+ #### Citation Concept
183
+
184
+ Zaileys provides a flexible **citation** mechanism. Define any metadata provider functions under the `citation` option. Each key will automatically generate a boolean on `ctx.citation`, prefixed with `is` and formatted in camelCase.
185
+
186
+ Providers can be **async** or **sync**, and Zaileys will await Promises:
187
+
188
+ ```ts
189
+ citation: {
190
+ // async provider
191
+ authorAsync: async () => await fetchAuthorizedAuthors(),
192
+ // sync provider
193
+ vipList: () => [1234567890]
194
+ }
195
+ ```
196
+
197
+ Results in:
198
+
199
+ - `ctx.citation.isAuthorAsync`
200
+ - `ctx.citation.isVipList`
201
+
202
+ Use them in handlers:
203
+
204
+ ```ts
205
+ wa.on("messages", (ctx) => {
206
+ if (!ctx.citation?.isAuthorAsync) return;
207
+ if (ctx.citation.isVipList) {
208
+ // VIP logic
209
+ }
210
+ });
211
+ ```
212
+
213
+ ## πŸ“’ Event Handling
214
+
215
+ ```js
216
+ // Connection updates
217
+ wa.on("connection", (ctx) => {});
218
+
219
+ // Message events
220
+ wa.on("messages", (ctx) => {});
221
+
222
+ // Call events
223
+ wa.on("calls", (ctx) => {});
224
+ ```
225
+
226
+ ## πŸ‘Ύ Worker Actions
227
+
228
+ ### Sending Messages
229
+
230
+ ```js
231
+ const roomId = ctx.roomId;
232
+ const message = ctx.message;
233
+
234
+ // sending text message
235
+ wa.text("Hallo test", { roomId });
236
+
237
+ // sending reply message
238
+ wa.text("Test reply", { roomId, quoted: message });
239
+
240
+ // sending text message as forwarded
241
+ wa.text("Test forwarded", { roomId, asForwarded: true });
242
+
243
+ // sending reply message as verified number
244
+ wa.text("Test verified reply", { roomId, quoted: message, verifiedReply: "whatsapp" });
245
+
246
+ // also combine verified number and forwarded
247
+ wa.text("Test verified reply", { roomId, quoted: message, verifiedReply: "meta", asForwarded: true });
248
+
249
+ // sending view once message
250
+ // support: image, video, audio
251
+ wa.text({ image: "https://github.com/zaadevofc.png", text: "Test view once" }, { roomId, asViewOnce: true });
252
+
253
+ // sending reaction message
254
+ // empty string for removing reaction
255
+ wa.reaction("🐞", { message });
256
+
257
+ // editing message
258
+ const msg1 = await wa.text("Test edit", { roomId });
259
+ wa.edit("Editing success", { message: msg1?.message });
260
+
261
+ // deleting message
262
+ const msg2 = await wa.text("Test delete", { roomId });
263
+ wa.delete("Deleting success", { message: msg2?.message });
264
+
265
+ // sending location message
266
+ wa.location({ latitude: 24.121231, longitude: 55.1121221, ...other }, { roomId });
267
+
268
+ // sending contact message
269
+ wa.contact({ fullname: "Kejaa", whatsAppNumber: 628123456789, ...other }, { roomId });
270
+
271
+ // sending polling message
272
+ wa.poll({ name: "Are you love me?", answers: ["yes", "maybe", "no"] }, { roomId });
273
+ ```
274
+
275
+ ### Sending Media
276
+
277
+ ```js
278
+ // sending image message
279
+ wa.text({ image: "https://github.com/zaadevofc.png", text: "Test image message" }, { roomId });
280
+ // buffer
281
+ wa.text({ image: fs.readFileSync("example/file.png"), text: "Test image message" }, { roomId });
282
+
283
+ // sending sticker message
284
+ wa.text({ sticker: "https://github.com/zaadevofc.png" }, { roomId });
285
+
286
+ // sending gif message
287
+ wa.text({ gif: "https://qu.ax/nTFwh.mp4" }, { roomId });
288
+
289
+ // sending video message
290
+ wa.text({ video: "https://qu.ax/nTFwh.mp4", text: "Test video message" }, { roomId });
291
+
292
+ // sending video note message
293
+ wa.text({ videoNote: "https://qu.ax/nTFwh.mp4" }, { roomId });
294
+
295
+ // sending audio message
296
+ // use .ogg format for better device support
297
+ wa.text({ audio: "https://qu.ax/oeSCG.ogg" }, { roomId });
298
+
299
+ // sending voice note message
300
+ // use .ogg format for better device support
301
+ wa.text({ audioNote: "https://qu.ax/oeSCG.ogg" }, { roomId });
302
+ ```
303
+
304
+ ### Presence Update
305
+
306
+ ```js
307
+ // available presence types:
308
+ // typing | recording | online | offline | paused
309
+ wa.presence("typing", { roomId });
310
+ ```
311
+
312
+ ### Get Profile
313
+
314
+ ```js
315
+ // get user profile
316
+ wa.profile("6281223456789@s.whatsapp.net");
317
+
318
+ // get group profile
319
+ wa.profile("1209999@g.us");
320
+ ```
321
+
322
+ ### Reject Call
323
+
324
+ ```js
325
+ wa.on("calls", (ctx) => {
326
+ wa.rejectCall({ callId: ctx.callId, callerId: ctx.callerId });
327
+
328
+ // for simplify
329
+ wa.rejectCall(ctx);
330
+ });
331
+ ```
332
+
333
+ ## 🐞 Issues & Feedback
334
+
335
+ If you encounter any problems or have feature requests, please open an issue:
336
+ [https://github.com/zeative/zaileys/issues](https://github.com/zeative/zaileys/issues)
337
+
338
+ ## ❀️ Funding & Support
339
+
340
+ If you find Zaileys useful, consider supporting development:
341
+
342
+ - [Buy me a coffee β˜•](https://saweria.co/zaadevofc)
343
+ - ⭐ Star the repo on GitHub
344
+
345
+ ## πŸ“„ License
346
+
347
+ Distributed under the **MIT License**. See [`LICENSE`](https://github.com/zeative/zaileys/blob/main/LICENSE) for details.
348
+
349
+ ## πŸ™ Acknowledgements
350
+
351
+ This project stands on the shoulders of the original [Baileys](https://github.com/WhiskeySockets/Baileys) library by Whiskey Sockets. Thank you for your incredible work and inspiration!"
352
+
353
+ > Happy coding! πŸš€
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=require("baileys"),t=require("events"),s=require("figlet"),a=require("node-cache"),n=require("ora"),i=require("pino"),r=require("better-sqlite3"),o=require("fs"),d=require("kysely"),c=require("mysql2"),u=require("path"),l=require("pg"),p=require("url"),h=require("stream"),m=require("crypto"),f=require("libsignal");function g(e){return e&&e.__esModule?e:{default:e}}var y,v,_,b=g(e),w=g(s),x=g(a),k=g(n),C=g(i),I=g(r),T=g(c),N=g(u),S=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},M=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},O=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,Z=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>Z(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?Z(s,t):s]))):e;(v=y||(y={})).assertEqual=e=>e,v.assertIs=function(e){},v.assertNever=function(e){throw new Error},v.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},v.getValidEnumValues=e=>{const t=v.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return v.objectValues(s)},v.objectValues=e=>v.objectKeys(e).map((function(t){return e[t]})),v.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},v.find=(e,t)=>{for(const s of e)if(t(s))return s},v.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,v.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},v.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(_||(_={})).mergeShapes=(e,t)=>({...e,...t});var A=y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),E=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:null===e?A.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?A.promise:"undefined"!=typeof Map&&e instanceof Map?A.map:"undefined"!=typeof Set&&e instanceof Set?A.set:"undefined"!=typeof Date&&e instanceof Date?A.date:A.object;default:return A.unknown}},j=y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),P=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,a=0;for(;a<n.path.length;){const s=n.path[a];a===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],a++}}};return a(this),s}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,y.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};P.create=e=>new P(e);var R=(e,t)=>{let s;switch(e.code){case j.invalid_type:s=e.received===A.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,y.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:s=`Unrecognized key(s) in object: ${y.joinValues(e.keys,", ")}`;break;case j.invalid_union:s="Invalid input";break;case j.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${y.joinValues(e.options)}`;break;case j.invalid_enum_value:s=`Invalid enum value. Expected ${y.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:s="Invalid function arguments";break;case j.invalid_return_type:s="Invalid function return type";break;case j.invalid_date:s="Invalid date";break;case j.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:y.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case j.too_small:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case j.too_big:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case j.custom:s="Invalid input";break;case j.invalid_intersection_types:s="Intersection results could not be merged";break;case j.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:s="Number must be finite";break;default:s=t.defaultError,y.assertNever(e)}return{message:s}},$=R;function F(){return $}var U=e=>{const{data:t,path:s,errorMaps:a,issueData:n}=e,i=[...s,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=a.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}};function D(e,t){const s=F(),a=U({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===R?void 0:R].filter((e=>!!e))});e.common.issues.push(a)}var L,q,z,V,B=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const a of t){if("aborted"===a.status)return K;"dirty"===a.status&&e.dirty(),s.push(a.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){const a=[];for(const e of s){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return e.mergeObjectSync(t,a)}static mergeObjectSync(e,t){const s={};for(const a of t){const{key:t,value:n}=a;if("aborted"===t.status)return K;if("aborted"===n.status)return K;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!a.alwaysSet||(s[t.value]=n.value)}return{status:e.value,value:s}}},K=Object.freeze({status:"aborted"}),J=e=>({status:"dirty",value:e}),W=e=>({status:"valid",value:e}),Y=e=>"aborted"===e.status,G=e=>"dirty"===e.status,H=e=>"valid"===e.status,Q=e=>"undefined"!=typeof Promise&&e instanceof Promise;function X(e,t,s,a){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function ee(e,t,s,a,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}(q=L||(L={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},q.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;var te=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},se=(e,t)=>{if(H(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new P(e.common.issues);return this._error=t,this._error}}};function ae(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:a,description:n}=e;if(t&&(s||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,r;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:a)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(r=null!=o?o:s)&&void 0!==r?r:n.defaultError}},description:n}}var ne,ie=class{get description(){return this._def.description}_getType(e){return E(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new B,ctx:{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Q(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;const a={common:{issues:[],async:null!==(s=null==t?void 0:t.async)&&void 0!==s&&s,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)},n=this._parseSync({data:e,path:a.path,parent:a});return se(a,n)}"~validate"(e){var t,s;const a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:a});return H(t)?{value:t.value}:{issues:a.common.issues}}catch(e){(null===(s=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===s?void 0:s.includes("encountered"))&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then((e=>H(e)?{value:e.value}:{issues:a.common.issues}))}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(Q(a)?a:Promise.resolve(a));return se(s,n)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,a)=>{const n=e(t),i=()=>a.addIssue({code:j.custom,...s(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((s,a)=>!!e(s)||(a.addIssue("function"==typeof t?t(s,a):t),!1)))}_refinement(e){return new nt({schema:this,typeName:gt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return it.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return at.create(this,this._def)}or(e){return qe.create([this,e],this._def)}and(e){return Ke.create(this,e,this._def)}transform(e){return new nt({...ae(this._def),schema:this,typeName:gt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ot({...ae(this._def),innerType:this,defaultValue:t,typeName:gt.ZodDefault})}brand(){return new lt({typeName:gt.ZodBranded,type:this,...ae(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new dt({...ae(this._def),innerType:this,catchValue:t,typeName:gt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},re=/^c[^\s-]{8,}$/i,oe=/^[0-9a-z]+$/,de=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ce=/^[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,ue=/^[a-z0-9_-]{21}$/i,le=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pe=/^[-+]?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)?)??$/,he=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,me=/^(?:(?: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])$/,fe=/^(?:(?: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])$/,ge=/^(([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]))$/,ye=/^(([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])$/,ve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,be="((\\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])))",we=new RegExp(`^${be}$`);function xe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function ke(e){let t=`${be}T${xe(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Ce(e,t){if(!le.test(e))return!1;try{const[s]=e.split("."),a=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(a));return"object"==typeof n&&null!==n&&(!(!n.typ||!n.alg)&&(!t||n.alg===t))}catch(e){return!1}}function Ie(e,t){return!("v4"!==t&&t||!fe.test(e))||!("v6"!==t&&t||!ye.test(e))}var Te=class e extends ie{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==A.string){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.string,received:t.parsedType}),K}const t=new B;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const a=e.data.length>i.value,n=e.data.length<i.value;(a||n)&&(s=this._getOrReturnCtx(e,s),a?D(s,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&D(s,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)he.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"email",code:j.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)ne||(ne=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ne.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"emoji",code:j.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)ce.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"uuid",code:j.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ue.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"nanoid",code:j.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)re.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid",code:j.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)oe.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid2",code:j.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)de.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ulid",code:j.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(a){s=this._getOrReturnCtx(e,s),D(s,{validation:"url",code:j.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"regex",code:j.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),D(s,{code:j.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),D(s,{code:j.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),D(s,{code:j.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){ke(i).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:j.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){we.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:j.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${xe(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:j.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?pe.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"duration",code:j.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!me.test(a))&&("v6"!==n&&n||!ge.test(a))&&(s=this._getOrReturnCtx(e,s),D(s,{validation:"ip",code:j.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ce(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"jwt",code:j.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Ie(e.data,i.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cidr",code:j.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?ve.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64",code:j.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?_e.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64url",code:j.invalid_string,message:i.message}),t.dirty()):y.assertNever(i);var a,n;return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement((t=>e.test(t)),{validation:t,code:j.invalid_string,...L.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.errToObj(e)})}datetime(e){var t,s;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(s=null==e?void 0:e.local)&&void 0!==s&&s,...L.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...L.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...L.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...L.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...L.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...L.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...L.errToObj(t)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Ne(e,t){const s=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=s>a?s:a;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}Te.create=e=>{var t;return new Te({checks:[],typeName:gt.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...ae(e)})};var Se=class e extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==A.number){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.number,received:t.parsedType}),K}let t;const s=new B;for(const a of this._def.checks)if("int"===a.kind)y.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),D(t,{code:j.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),D(t,{code:j.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),D(t,{code:j.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==Ne(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),D(t,{code:j.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),D(t,{code:j.not_finite,message:a.message}),s.dirty()):y.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,L.toString(t))}gt(e,t){return this.setLimit("min",e,!1,L.toString(t))}lte(e,t){return this.setLimit("max",e,!0,L.toString(t))}lt(e,t){return this.setLimit("max",e,!1,L.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:L.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&y.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Se.create=e=>new Se({checks:[],typeName:gt.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...ae(e)});var Me=class e extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==A.bigint)return this._getInvalidInput(e);let t;const s=new B;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),D(t,{code:j.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),D(t,{code:j.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),D(t,{code:j.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):y.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.bigint,received:t.parsedType}),K}gte(e,t){return this.setLimit("min",e,!0,L.toString(t))}gt(e,t){return this.setLimit("min",e,!1,L.toString(t))}lte(e,t){return this.setLimit("max",e,!0,L.toString(t))}lt(e,t){return this.setLimit("max",e,!1,L.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:L.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Me.create=e=>{var t;return new Me({checks:[],typeName:gt.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...ae(e)})};var Oe=class extends ie{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==A.boolean){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.boolean,received:t.parsedType}),K}return W(e.data)}};Oe.create=e=>new Oe({typeName:gt.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...ae(e)});var Ze=class e extends ie{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==A.date){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.date,received:t.parsedType}),K}if(isNaN(e.data.getTime())){return D(this._getOrReturnCtx(e),{code:j.invalid_date}),K}const t=new B;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:j.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:j.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):y.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};Ze.create=e=>new Ze({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:gt.ZodDate,...ae(e)});var Ae=class extends ie{_parse(e){if(this._getType(e)!==A.symbol){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.symbol,received:t.parsedType}),K}return W(e.data)}};Ae.create=e=>new Ae({typeName:gt.ZodSymbol,...ae(e)});var Ee=class extends ie{_parse(e){if(this._getType(e)!==A.undefined){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.undefined,received:t.parsedType}),K}return W(e.data)}};Ee.create=e=>new Ee({typeName:gt.ZodUndefined,...ae(e)});var je=class extends ie{_parse(e){if(this._getType(e)!==A.null){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.null,received:t.parsedType}),K}return W(e.data)}};je.create=e=>new je({typeName:gt.ZodNull,...ae(e)});var Pe=class extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return W(e.data)}};Pe.create=e=>new Pe({typeName:gt.ZodAny,...ae(e)});var Re=class extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return W(e.data)}};Re.create=e=>new Re({typeName:gt.ZodUnknown,...ae(e)});var $e=class extends ie{_parse(e){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.never,received:t.parsedType}),K}};$e.create=e=>new $e({typeName:gt.ZodNever,...ae(e)});var Fe=class extends ie{_parse(e){if(this._getType(e)!==A.undefined){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.void,received:t.parsedType}),K}return W(e.data)}};Fe.create=e=>new Fe({typeName:gt.ZodVoid,...ae(e)});var Ue=class e extends ie{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==A.array)return D(t,{code:j.invalid_type,expected:A.array,received:t.parsedType}),K;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(D(t,{code:e?j.too_big:j.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(D(t,{code:j.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(D(t,{code:j.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map(((e,s)=>a.type._parseAsync(new te(t,e,t.path,s))))).then((e=>B.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new te(t,e,t.path,s))));return B.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:L.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:L.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:L.toString(s)}})}nonempty(e){return this.min(1,e)}};function De(e){if(e instanceof Le){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=it.create(De(a))}return new Le({...e._def,shape:()=>t})}return e instanceof Ue?new Ue({...e._def,type:De(e.element)}):e instanceof it?it.create(De(e.unwrap())):e instanceof rt?rt.create(De(e.unwrap())):e instanceof Je?Je.create(e.items.map((e=>De(e)))):e}Ue.create=(e,t)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:gt.ZodArray,...ae(t)});var Le=class e extends ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=y.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==A.object){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.object,received:t.parsedType}),K}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof $e&&"strip"===this._def.unknownKeys))for(const e in s.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=a[e],n=s.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new te(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof $e){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)i.length>0&&(D(s,{code:j.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const a=s.data[t];r.push({key:{status:"valid",value:t},value:e._parse(new te(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of r){const s=await t.key,a=await t.value;e.push({key:s,value:a,alwaysSet:t.alwaysSet})}return e})).then((e=>B.mergeObjectSync(t,e))):B.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return L.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,s)=>{var a,n,i,r;const o=null!==(i=null===(n=(a=this._def).errorMap)||void 0===n?void 0:n.call(a,e,s).message)&&void 0!==i?i:s.defaultError;return"unrecognized_keys"===e.code?{message:null!==(r=L.errToObj(t).message)&&void 0!==r?r:o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:gt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const s={};return y.objectKeys(t).forEach((e=>{t[e]&&this.shape[e]&&(s[e]=this.shape[e])})),new e({...this._def,shape:()=>s})}omit(t){const s={};return y.objectKeys(this.shape).forEach((e=>{t[e]||(s[e]=this.shape[e])})),new e({...this._def,shape:()=>s})}deepPartial(){return De(this)}partial(t){const s={};return y.objectKeys(this.shape).forEach((e=>{const a=this.shape[e];t&&!t[e]?s[e]=a:s[e]=a.optional()})),new e({...this._def,shape:()=>s})}required(t){const s={};return y.objectKeys(this.shape).forEach((e=>{if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof it;)t=t._def.innerType;s[e]=t}})),new e({...this._def,shape:()=>s})}keyof(){return et(y.objectKeys(this.shape))}};Le.create=(e,t)=>new Le({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)}),Le.strictCreate=(e,t)=>new Le({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)}),Le.lazycreate=(e,t)=>new Le({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)});var qe=class extends ie{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map((async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map((e=>new P(e.ctx.common.issues)));return D(t,{code:j.invalid_union,unionErrors:s}),K}));{let e;const a=[];for(const n of s){const s={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:s});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=a.map((e=>new P(e)));return D(t,{code:j.invalid_union,unionErrors:n}),K}}get options(){return this._def.options}};qe.create=(e,t)=>new qe({options:e,typeName:gt.ZodUnion,...ae(t)});var ze=e=>e instanceof Qe?ze(e.schema):e instanceof nt?ze(e.innerType()):e instanceof Xe?[e.value]:e instanceof tt?e.options:e instanceof st?y.objectValues(e.enum):e instanceof ot?ze(e._def.innerType):e instanceof Ee?[void 0]:e instanceof je?[null]:e instanceof it?[void 0,...ze(e.unwrap())]:e instanceof rt?[null,...ze(e.unwrap())]:e instanceof lt||e instanceof ht?ze(e.unwrap()):e instanceof dt?ze(e._def.innerType):[],Ve=class e extends ie{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.object)return D(t,{code:j.invalid_type,expected:A.object,received:t.parsedType}),K;const s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(D(t,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,a){const n=new Map;for(const e of s){const s=ze(e.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of s){if(n.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,e)}}return new e({typeName:gt.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ae(a)})}};function Be(e,t){const s=E(e),a=E(t);if(e===t)return{valid:!0,data:e};if(s===A.object&&a===A.object){const s=y.objectKeys(t),a=y.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=Be(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===A.array&&a===A.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=Be(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===A.date&&a===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ke=class extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(Y(e)||Y(a))return K;const n=Be(e.value,a.value);return n.valid?((G(e)||G(a))&&t.dirty(),{status:t.value,value:n.data}):(D(s,{code:j.invalid_intersection_types}),K)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then((([e,t])=>a(e,t))):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Ke.create=(e,t,s)=>new Ke({left:e,right:t,typeName:gt.ZodIntersection,...ae(s)});var Je=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==A.array)return D(s,{code:j.invalid_type,expected:A.array,received:s.parsedType}),K;if(s.data.length<this._def.items.length)return D(s,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&s.data.length>this._def.items.length&&(D(s,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map(((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new te(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>B.mergeArray(t,e))):B.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Je.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Je({items:e,typeName:gt.ZodTuple,rest:null,...ae(t)})};var We=class e extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==A.object)return D(s,{code:j.invalid_type,expected:A.object,received:s.parsedType}),K;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new te(s,e,s.path,e)),value:i._parse(new te(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?B.mergeObjectAsync(t,a):B.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof ie?{keyType:t,valueType:s,typeName:gt.ZodRecord,...ae(a)}:{keyType:Te.create(),valueType:t,typeName:gt.ZodRecord,...ae(s)})}},Ye=class extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==A.map)return D(s,{code:j.invalid_type,expected:A.map,received:s.parsedType}),K;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new te(s,e,s.path,[i,"key"])),value:n._parse(new te(s,t,s.path,[i,"value"]))})));if(s.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const s of i){const a=await s.key,n=await s.value;if("aborted"===a.status||"aborted"===n.status)return K;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const s of i){const a=s.key,n=s.value;if("aborted"===a.status||"aborted"===n.status)return K;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};Ye.create=(e,t,s)=>new Ye({valueType:t,keyType:e,typeName:gt.ZodMap,...ae(s)});var Ge=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==A.set)return D(s,{code:j.invalid_type,expected:A.set,received:s.parsedType}),K;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(D(s,{code:j.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&s.data.size>a.maxSize.value&&(D(s,{code:j.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const s=new Set;for(const a of e){if("aborted"===a.status)return K;"dirty"===a.status&&t.dirty(),s.add(a.value)}return{status:t.value,value:s}}const r=[...s.data.values()].map(((e,t)=>n._parse(new te(s,e,s.path,t))));return s.common.async?Promise.all(r).then((e=>i(e))):i(r)}min(t,s){return new e({...this._def,minSize:{value:t,message:L.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:L.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ge.create=(e,t)=>new Ge({valueType:e,minSize:null,maxSize:null,typeName:gt.ZodSet,...ae(t)});var He=class e extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.function)return D(t,{code:j.invalid_type,expected:A.function,received:t.parsedType}),K;function s(e,s){return U({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,F(),R].filter((e=>!!e)),issueData:{code:j.invalid_arguments,argumentsError:s}})}function a(e,s){return U({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,F(),R].filter((e=>!!e)),issueData:{code:j.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof at){const e=this;return W((async function(...t){const r=new P([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(s(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(a(d,e)),r}))}))}{const e=this;return W((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new P([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new P([a(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Je.create(t).rest(Re.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,a){return new e({args:t||Je.create([]).rest(Re.create()),returns:s||Re.create(),typeName:gt.ZodFunction,...ae(a)})}},Qe=class extends ie{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Qe.create=(e,t)=>new Qe({getter:e,typeName:gt.ZodLazy,...ae(t)});var Xe=class extends ie{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return D(t,{received:t.data,code:j.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};function et(e,t){return new tt({values:e,typeName:gt.ZodEnum,...ae(t)})}Xe.create=(e,t)=>new Xe({value:e,typeName:gt.ZodLiteral,...ae(t)});var tt=class e extends ie{constructor(){super(...arguments),z.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return D(t,{expected:y.joinValues(s),received:t.parsedType,code:j.invalid_type}),K}if(X(this,z)||ee(this,z,new Set(this._def.values)),!X(this,z).has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return D(t,{received:t.data,code:j.invalid_enum_value,options:s}),K}return W(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...s})}};z=new WeakMap,tt.create=et;var st=class extends ie{constructor(){super(...arguments),V.set(this,void 0)}_parse(e){const t=y.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==A.string&&s.parsedType!==A.number){const e=y.objectValues(t);return D(s,{expected:y.joinValues(e),received:s.parsedType,code:j.invalid_type}),K}if(X(this,V)||ee(this,V,new Set(y.getValidEnumValues(this._def.values))),!X(this,V).has(e.data)){const e=y.objectValues(t);return D(s,{received:s.data,code:j.invalid_enum_value,options:e}),K}return W(e.data)}get enum(){return this._def.values}};V=new WeakMap,st.create=(e,t)=>new st({values:e,typeName:gt.ZodNativeEnum,...ae(t)});var at=class extends ie{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.promise&&!1===t.common.async)return D(t,{code:j.invalid_type,expected:A.promise,received:t.parsedType}),K;const s=t.parsedType===A.promise?t.data:Promise.resolve(t.data);return W(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};at.create=(e,t)=>new at({type:e,typeName:gt.ZodPromise,...ae(t)});var nt=class extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===gt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:e=>{D(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===a.type){const e=a.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return K;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?K:"dirty"===a.status||"dirty"===t.value?J(a.value):a}));{if("aborted"===t.value)return K;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?K:"dirty"===a.status||"dirty"===t.value?J(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,n);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===a.status?K:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((s=>"aborted"===s.status?K:("dirty"===s.status&&t.dirty(),e(s.value).then((()=>({status:t.value,value:s.value}))))))}if("transform"===a.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!H(e))return e;const i=a.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e=>H(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):e))}y.assertNever(a)}};nt.create=(e,t,s)=>new nt({schema:e,typeName:gt.ZodEffects,effect:t,...ae(s)}),nt.createWithPreprocess=(e,t,s)=>new nt({schema:t,effect:{type:"preprocess",transform:e},typeName:gt.ZodEffects,...ae(s)});var it=class extends ie{_parse(e){return this._getType(e)===A.undefined?W(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:gt.ZodOptional,...ae(t)});var rt=class extends ie{_parse(e){return this._getType(e)===A.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:gt.ZodNullable,...ae(t)});var ot=class extends ie{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===A.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:gt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ae(t)});var dt=class extends ie{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Q(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new P(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new P(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:gt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ae(t)});var ct=class extends ie{_parse(e){if(this._getType(e)!==A.nan){const t=this._getOrReturnCtx(e);return D(t,{code:j.invalid_type,expected:A.nan,received:t.parsedType}),K}return{status:"valid",value:e.data}}};ct.create=e=>new ct({typeName:gt.ZodNaN,...ae(e)});var ut=Symbol("zod_brand"),lt=class extends ie{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},pt=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?K:"dirty"===e.status?(t.dirty(),J(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})()}{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?K:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:gt.ZodPipeline})}},ht=class extends ie{_parse(e){const t=this._def.innerType._parse(e),s=e=>(H(e)&&(e.value=Object.freeze(e.value)),e);return Q(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function mt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function ft(e,t={},s){return e?Pe.create().superRefine(((a,n)=>{var i,r;const o=e(a);if(o instanceof Promise)return o.then((e=>{var i,r;if(!e){const e=mt(t,a),o=null===(r=null!==(i=e.fatal)&&void 0!==i?i:s)||void 0===r||r;n.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=mt(t,a),o=null===(r=null!==(i=e.fatal)&&void 0!==i?i:s)||void 0===r||r;n.addIssue({code:"custom",...e,fatal:o})}})):Pe.create()}ht.create=(e,t)=>new ht({innerType:e,typeName:gt.ZodReadonly,...ae(t)});var gt,yt,vt={object:Le.lazycreate};(yt=gt||(gt={})).ZodString="ZodString",yt.ZodNumber="ZodNumber",yt.ZodNaN="ZodNaN",yt.ZodBigInt="ZodBigInt",yt.ZodBoolean="ZodBoolean",yt.ZodDate="ZodDate",yt.ZodSymbol="ZodSymbol",yt.ZodUndefined="ZodUndefined",yt.ZodNull="ZodNull",yt.ZodAny="ZodAny",yt.ZodUnknown="ZodUnknown",yt.ZodNever="ZodNever",yt.ZodVoid="ZodVoid",yt.ZodArray="ZodArray",yt.ZodObject="ZodObject",yt.ZodUnion="ZodUnion",yt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",yt.ZodIntersection="ZodIntersection",yt.ZodTuple="ZodTuple",yt.ZodRecord="ZodRecord",yt.ZodMap="ZodMap",yt.ZodSet="ZodSet",yt.ZodFunction="ZodFunction",yt.ZodLazy="ZodLazy",yt.ZodLiteral="ZodLiteral",yt.ZodEnum="ZodEnum",yt.ZodEffects="ZodEffects",yt.ZodNativeEnum="ZodNativeEnum",yt.ZodOptional="ZodOptional",yt.ZodNullable="ZodNullable",yt.ZodDefault="ZodDefault",yt.ZodCatch="ZodCatch",yt.ZodPromise="ZodPromise",yt.ZodBranded="ZodBranded",yt.ZodPipeline="ZodPipeline",yt.ZodReadonly="ZodReadonly";var _t=Te.create,bt=Se.create,wt=ct.create,xt=Me.create,kt=Oe.create,Ct=Ze.create,It=Ae.create,Tt=Ee.create,Nt=je.create,St=Pe.create,Mt=Re.create,Ot=$e.create,Zt=Fe.create,At=Ue.create,Et=Le.create,jt=Le.strictCreate,Pt=qe.create,Rt=Ve.create,$t=Ke.create,Ft=Je.create,Ut=We.create,Dt=Ye.create,Lt=Ge.create,qt=He.create,zt=Qe.create,Vt=Xe.create,Bt=tt.create,Kt=st.create,Jt=at.create,Wt=nt.create,Yt=it.create,Gt=rt.create,Ht=nt.createWithPreprocess,Qt=pt.create,Xt={string:e=>Te.create({...e,coerce:!0}),number:e=>Se.create({...e,coerce:!0}),boolean:e=>Oe.create({...e,coerce:!0}),bigint:e=>Me.create({...e,coerce:!0}),date:e=>Ze.create({...e,coerce:!0})},es=K,ts=Object.freeze({__proto__:null,defaultErrorMap:R,setErrorMap:function(e){$=e},getErrorMap:F,makeIssue:U,EMPTY_PATH:[],addIssueToContext:D,ParseStatus:B,INVALID:K,DIRTY:J,OK:W,isAborted:Y,isDirty:G,isValid:H,isAsync:Q,get util(){return y},get objectUtil(){return _},ZodParsedType:A,getParsedType:E,ZodType:ie,datetimeRegex:ke,ZodString:Te,ZodNumber:Se,ZodBigInt:Me,ZodBoolean:Oe,ZodDate:Ze,ZodSymbol:Ae,ZodUndefined:Ee,ZodNull:je,ZodAny:Pe,ZodUnknown:Re,ZodNever:$e,ZodVoid:Fe,ZodArray:Ue,ZodObject:Le,ZodUnion:qe,ZodDiscriminatedUnion:Ve,ZodIntersection:Ke,ZodTuple:Je,ZodRecord:We,ZodMap:Ye,ZodSet:Ge,ZodFunction:He,ZodLazy:Qe,ZodLiteral:Xe,ZodEnum:tt,ZodNativeEnum:st,ZodPromise:at,ZodEffects:nt,ZodTransformer:nt,ZodOptional:it,ZodNullable:rt,ZodDefault:ot,ZodCatch:dt,ZodNaN:ct,BRAND:ut,ZodBranded:lt,ZodPipeline:pt,ZodReadonly:ht,custom:ft,Schema:ie,ZodSchema:ie,late:vt,get ZodFirstPartyTypeKind(){return gt},coerce:Xt,any:St,array:At,bigint:xt,boolean:kt,date:Ct,discriminatedUnion:Rt,effect:Wt,enum:Bt,function:qt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>ft((t=>t instanceof e),t),intersection:$t,lazy:zt,literal:Vt,map:Dt,nan:wt,nativeEnum:Kt,never:Ot,null:Nt,nullable:Gt,number:bt,object:Et,oboolean:()=>kt().optional(),onumber:()=>bt().optional(),optional:Yt,ostring:()=>_t().optional(),pipeline:Qt,preprocess:Ht,promise:Jt,record:Ut,set:Lt,strictObject:jt,string:_t,symbol:It,transformer:Wt,tuple:Ft,undefined:Tt,union:Pt,unknown:Mt,void:Zt,NEVER:es,ZodIssueCode:j,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:P}),ss={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contactsArray",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"liveLocation",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"templateButtonReply",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"list",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"listResponse",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttonsResponse",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},as={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"},ns=ts.enum(["text","text","image","contact","location","document","audio","video","protocol","contactsArray","highlyStructured","sendPayment","liveLocation","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","templateButtonReply","product","deviceSent","list","viewOnce","order","listResponse","ephemeral","invoice","buttons","buttonsResponse","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","text","text","placeholder","encEventUpdate"]),is=ts.enum(["unknown","android","ios","desktop","web"]),rs=ts.object({chatId:ts.string(),channelId:ts.string(),receiverId:ts.string(),receiverName:ts.string(),roomId:ts.string(),roomName:ts.string(),senderId:ts.string(),senderName:ts.string(),senderDevice:is,chatType:ns,timestamp:ts.number(),mentions:ts.string().array(),text:ts.string().nullable(),links:ts.string().array(),isPrefix:ts.boolean(),isFromMe:ts.boolean(),isTagMe:ts.boolean(),isGroup:ts.boolean(),isStory:ts.boolean(),isViewOnce:ts.boolean(),isEdited:ts.boolean(),isDeleted:ts.boolean(),isPinned:ts.boolean(),isUnPinned:ts.boolean(),isChannel:ts.boolean(),isBroadcast:ts.boolean(),isEphemeral:ts.boolean(),isForwarded:ts.boolean(),citation:ts.record(ts.string(),ts.boolean()).nullable(),media:ts.object({buffer:ts.function().returns(ts.instanceof(Buffer)),stream:ts.function().returns(ts.instanceof(h.Readable))}).passthrough().nullable(),message:ts.function().returns(ts.record(ts.string(),ts.any()))});rs.extend({replied:rs.nullable()});var os=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(t){const{connection:s,lastDisconnect:a,qr:n}=t;if(this.client.startSpinner("connection","Connecting to WhatsApp..."),this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&n)return this.client.stopSpinner("connection",!1),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===s){this.client.failSpinner("connection","Connection closed");const t=a?.error?.output?.statusCode,s=t!==e.DisconnectReason.loggedOut;if(console.log(a?.error?.message),401===t||405===t||500===t)return void console.error("Invalid session, please delete manually");s&&this.client.options&&await this.client.initialize()}else"open"===s&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(t,s){if(t?.messageStubType||t?.messageStubParameters?.length||t?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||t?.message?.botInvokeMessage||!t?.key?.id||!t?.message)return null;if(this.client.options?.ignoreMe&&t?.key?.fromMe&&"status@broadcast"!=t?.key?.remoteJid&&!t?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([t?.key]);const a=t,n=t?.message?.pinInChatMessage?.key?.id,i=1==t?.message?.pinInChatMessage?.type,r=2==t?.message?.pinInChatMessage?.type;if(n){const e=await this.db.selectFrom("messages").select("value").where("id","=",n).executeTakeFirst(),s=S(e?.value);t=s}const o=!t?.message?.protocolMessage?.editedMessage&&t?.message?.protocolMessage?.key?.id,d=!!o;if(o){const e=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),s=S(e?.value);t=s}const c={},u=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);c.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,c.channelId="",c.receiverId=e.jidNormalizedUser(this.socket.user?.id),c.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,c.roomId=e.jidNormalizedUser(t?.key?.remoteJid);const l=await this.db.selectFrom("chats").select("value").where("id","=",c.roomId).executeTakeFirst();c.roomName=S(l?.value)?.name,c.senderId=e.jidNormalizedUser(t?.participant||t?.key?.participant||t?.key?.remoteJid);const p=await this.db.selectFrom("chats").select("value").where("id","=",c.senderId).executeTakeFirst();c.senderName=t?.pushName||t?.verifiedBizName||S(p?.value)?.name||c.receiverName,c.roomName=c.roomName||c.senderName,c.senderDevice=e.getDevice(c.chatId),c.chatType=ss[u],c.timestamp=t?.messageTimestamp?.low||t?.messageTimestamp||0,c.mentions=[],c.text=null,c.links=[],c.isPrefix=!1,c.isFromMe=t?.key?.fromMe,c.isTagMe=!1,c.isGroup=c.roomId.includes("@g.us"),c.isStory=c.roomId.includes("@broadcast"),c.isViewOnce=!1,c.isEdited=!1,c.isDeleted=d,c.isPinned=i,c.isUnPinned=r,c.isChannel=c.roomId.includes("@newsletter"),c.isBroadcast=!!t?.broadcast,c.isEphemeral=!1,c.isForwarded=!1,c.citation=null,c.media=null,c.replied=null,c.channelId=c.roomId.split("@")[0]+"-"+c.senderId.split("@")[0];const h=this.client.options?.citation;if(Object.keys(h).length){c.citation={};for(const e of Object.keys(h))c.citation[e]=h[e].includes(Number(c.senderId.split("@")[0]))||h[e].includes(Number(c.roomId.split("@")[0]))}const m=(t?.message?.protocolMessage?.editedMessage?.[u]||t?.message?.[u])?.message?.documentMessage||t?.message?.[u];"text"!=c.chatType&&(c.media={...Z(m,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await e.downloadMediaMessage(t,"buffer",{}),stream:async()=>await e.downloadMediaMessage(t,"stream",{})});const f=t?.message?.[u]?.contextInfo?.stanzaId;if(f&&this.maxReplies<1){this.maxReplies++;const s=await this.db.selectFrom("messages").select("value").where("id","=",f).executeTakeFirst(),a=S(s?.value);if(a)c.replied=await this.messages(a,!0);else{const s=t,a=e.getContentType(s.message?.extendedTextMessage?.contextInfo.quotedMessage);s.key.id=s.message?.extendedTextMessage?.contextInfo.stanzaId,s.message[a]=s.message?.extendedTextMessage?.contextInfo.quotedMessage[a],delete s.message?.extendedTextMessage,c.replied=await this.messages(s,!0)}}const g="string"==typeof m?m:m?.text||m?.caption||m?.name||m?.displayName||"";c.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(g)||null,c.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(c.text),c.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(c.text);const y=t?.message?.[u];return c.isPrefix=!!this.client.options?.prefix&&!!c.text?.startsWith(this.client.options?.prefix),c.isTagMe=c.mentions.includes(c.receiverId.split("@")[0]),c.isEdited=O(M(t),"editedMessage"),c.isEphemeral=O(M(y?.contextInfo),"ephemeralSettingTimestamp"),c.isForwarded=O(M(y?.contextInfo),"forwardingScore"),c.isViewOnce=!!y?.viewOnce,c.isPrefix&&(c.text=c.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),c.message=()=>a,s||this.client.emit("messages",c),c}async calls(e){this.client.options?.autoRejectCall&&await this.socket.rejectCall(e.id,e.from);const t={};t.callId=e.id,t.roomId=e.chatId,t.callerId=e.from,t.date=e.date,t.offline=e.offline,t.status=e.status,t.isVideo=!!e.isVideo,t.isGroup=!!e.isGroup,this.client.emit("calls",t)}},ds=f.curve,cs=()=>{const{pubKey:e,privKey:t}=ds.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(e.slice(1))}},us=(e,t)=>{const s=cs(),a=(e=>33===e.length?e:Buffer.concat([Buffer.from([5]),e]))(s.public);var n,i;return{keyPair:s,signature:(n=e.private,i=a,ds.calculateSignature(n,i)),keyId:t}},ls=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},s={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(a=e.timestamp,"string"==typeof a?parseInt(a,10):a)};var a;return"string"==typeof e.keyData&&(s.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let s=0;for(;--t%4>1&&"="===e.charAt(t);)++s;return new Uint8Array(Math.ceil(3*e.length)/4-s).fill(0)})(e.keyData)),s},ps=(e,t)=>"Buffer"===t?.type&&Array.isArray(t?.data)?{type:"Buffer",data:Buffer.from(t?.data).toString("base64")}:t,hs=(e,t)=>"Buffer"===t?.type?Buffer.from(t?.data,"base64"):t,ms=async(e,t)=>{const s="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(e);const a=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},n=async n=>{const i=await a((()=>e.selectFrom(s).select(["value"]).where("id","=",n).where("session","=",t).executeTakeFirst()));if(!i?.value)return null;const r="object"==typeof i.value?JSON.stringify(i.value):i.value;return JSON.parse(r,hs)},i=async(n,i)=>{const r=JSON.stringify(i,ps);await a((()=>e.insertInto(s).values({session:t,id:n,value:r}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:r}))).execute()))},r=async n=>{await a((()=>e.deleteFrom(s).where("id","=",n).where("session","=",t).execute()))},o=await n("creds")||(()=>{const e=cs();return{noiseKey:cs(),pairingEphemeralKeyPair:cs(),signedIdentityKey:e,signedPreKey:us(e,1),registrationId:16383&Uint16Array.from(m.randomBytes(2))[0],advSecretKey:m.randomBytes(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},deviceId:Buffer.from(m.randomUUID().replace(/-/g,""),"hex").toString("base64url"),phoneId:m.randomUUID(),identityId:m.randomBytes(20),backupToken:m.randomBytes(20),registered:!1,registration:{},pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0}})();return{state:{creds:o,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await n(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=ls(t)),s[a]=t}return s},set:async e=>{for(const t in e)for(const s in e[t]){const a=e[t][s],n=`${t}-${s}`;a?await i(n,a):await r(n)}}}},saveCreds:async()=>{await i("creds",o)},clear:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).execute()))})()}}},fs=ts.object({type:ts.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:ts.object({url:ts.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),gs=ts.record(ts.function().returns(ts.union([ts.number().array(),ts.promise(ts.number().array())]))).optional().transform((async e=>{if(!e)return{};const t={};for(const[s,a]of Object.entries(e)){t[`is${s.charAt(0).toUpperCase()}${s.slice(1)}`]=await a()}return t})),ys=ts.object({prefix:ts.string().optional(),ignoreMe:ts.boolean().optional().default(!0),showLogs:ts.boolean().optional().default(!0),autoMentions:ts.boolean().optional().default(!0),autoOnline:ts.boolean().optional().default(!0),autoRead:ts.boolean().optional().default(!0),autoPresence:ts.boolean().optional().default(!0),autoRejectCall:ts.boolean().optional().default(!0),database:fs,citation:gs}),vs=ts.object({authType:ts.literal("pairing"),phoneNumber:ts.number()}).extend(ys.shape),_s=ts.object({authType:ts.literal("qr"),phoneNumber:ts.undefined().optional()}).extend(ys.shape),bs=ts.discriminatedUnion("authType",[vs,_s]),ws=ts.union([ts.string().url(),ts.instanceof(Buffer).or(ts.instanceof(h.Readable))]),xs=ts.union([ts.string(),ts.object({image:ws,text:ts.string().optional()}),ts.object({video:ws,text:ts.string().optional()}),ts.object({videoNote:ws}),ts.object({gif:ws,text:ts.string().optional()}),ts.object({audio:ws}),ts.object({audioNote:ws}),ts.object({sticker:ws})]),ks=ts.object({roomId:ts.string(),asForwarded:ts.boolean().optional(),asViewOnce:ts.boolean().optional(),verifiedReply:ts.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:ts.function().returns(ts.record(ts.string(),ts.any())).optional()}),Cs=ks,Is=ts.object({latitude:ts.number(),longitude:ts.number(),title:ts.string().optional(),footer:ts.string().optional()}),Ts=ks,Ns=ts.object({fullname:ts.string(),nickname:ts.string().optional(),organization:ts.string().optional(),role:ts.string().optional(),email:ts.string().email().optional(),whatsAppNumber:ts.number(),callNumber:ts.number().optional(),voiceNumber:ts.number().optional(),website:ts.string().url().optional(),homeAddress:ts.string().optional(),workAddress:ts.string().optional(),avatar:ts.string().url().optional()}),Ss=ts.object({message:ts.function().returns(ts.record(ts.string(),ts.any()))}),Ms=ts.string(),Os=ts.object({message:ts.function().returns(ts.record(ts.string(),ts.any()))}),Zs=ts.object({action:ts.enum(["pin","unpin"]),expired:ts.enum(["24h","7d","30d"])}),As=ks.pick({roomId:!0}),Es=ts.object({name:ts.string(),answers:ts.string().array(),multipleAnswers:ts.boolean().optional()}),js=ts.object({message:ts.function().returns(ts.record(ts.string(),ts.any()))}),Ps=ts.string(),Rs=ts.object({message:ts.function().returns(ts.record(ts.string(),ts.any()))}),$s=ts.object({callId:ts.string(),callerId:ts.string()}),Fs=ks.pick({roomId:!0}),Us=ts.object({expired:ts.enum(["remove","8h","7d"])}),Ds=ts.string();ts.object({type:ts.enum(["group","user"]),id:ts.string(),name:ts.string(),bio:ts.string(),avatar:ts.string().url(),ephemeralDuration:ts.number().optional(),isRestrict:ts.boolean().optional(),isAnnounce:ts.boolean().optional(),isCommunity:ts.boolean().optional(),isCommunityAnnounce:ts.boolean().optional(),isJoinApprovalMode:ts.boolean().optional(),isMemberAddMode:ts.boolean().optional(),owner:ts.object({type:ts.literal("user"),id:ts.string()}).nullable(),roomCreatedAt:ts.number().optional(),nameUpdatedAt:ts.number().optional(),bioUpdatedAt:ts.number().optional(),membersLength:ts.number().optional(),members:ts.object({type:ts.enum(["user","admin","superadmin"]),id:ts.string()}).array().optional()});var Ls=ks.pick({roomId:!0}),qs=ts.enum(["typing","recording","online","offline","paused"]),zs=class{constructor(e){this.wa=e,this.parser=new os(this.wa.socket,this.wa.client,this.wa.db)}parser;async sendMessage(e,t,s){let a=[];this.wa.client.options?.autoMentions&&(a=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t].flatMap((e=>[`${e}@s.whatsapp.net`,`${e}@g.us`]))})(t?.text||t?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",e),this.wa.client.options?.autoPresence&&(t?.audio||t?.audioNote)&&this.wa.socket?.sendPresenceUpdate("recording",e);const n=t,i={contextInfo:{isForwarded:!!n?.asForwarded}};if("function"==typeof n?.quoted){let t=n?.quoted();t.key.participant=as[n?.verifiedReply]||t.key.participant;const r=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},{quoted:t,...s}));return await this.parser.messages(r)}{const t=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},s));return await this.parser.messages(t)}}async text(e,t){if(e=xs.parse(e),t=ks.parse(t),"string"==typeof e)return await this.sendMessage(t.roomId,{text:e,...t});if("object"==typeof e){const s=Object.keys(e),a=e;if(s.includes("image")){const e="string"==typeof a.image?{url:a.image}:a.image;return await this.sendMessage(t.roomId,{caption:a?.text,image:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("video")){const e="string"==typeof a.video?{url:a.video}:a.video;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!1,viewOnce:!!t.asViewOnce,...t})}if(s.includes("videoNote")){const e="string"==typeof a.videoNote?{url:a.videoNote}:a.videoNote;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!0,...t})}if(s.includes("gif")){const e="string"==typeof a.gif?{url:a.gif}:a.gif;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,gifPlayback:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audio")){const e="string"==typeof a.audio?{url:a.audio}:a.audio;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audioNote")){const e="string"==typeof a.audioNote?{url:a.audioNote}:a.audioNote;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,ptt:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("sticker")){const e="string"==typeof a.sticker?{url:a.sticker}:a.sticker;return await this.sendMessage(t.roomId,{caption:a?.text,sticker:e,...t})}}}async location(e,t){return e=Is.parse(e),t=Cs.parse(t),await this.sendMessage(t.roomId,{location:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,url:e.title,address:e.footer,name:e.title},...t})}async contact(e,t){e=Ns.parse(e),t=Ts.parse(t);const s=["BEGIN:VCARD","VERSION:3.0",`N:;${e.fullname};;;`,`FN:${e.fullname}`,e.nickname?`NICKNAME:${e.nickname}`:"",e.organization||e.role?`ORG:${e.organization??""};`:"",e.role?`TITLE:${e.role}`:"",`TEL;TYPE=CELL,VOICE;waid=${e.whatsAppNumber}:+${e.whatsAppNumber}`,e.callNumber?`TEL;TYPE=WORK,VOICE:+${e.callNumber}`:"",e.voiceNumber?`TEL;TYPE=VOICE:+${e.voiceNumber}`:"",e.email?`EMAIL;TYPE=INTERNET:${e.email}`:"",e.website?`URL;TYPE=WORK:${e.website}`:"",e.homeAddress?`ADR;TYPE=HOME:;;${e.homeAddress};;;;`:"",e.workAddress?`ADR;TYPE=WORK:;;${e.workAddress};;;;`:"",e.avatar?`PHOTO;VALUE=URI;TYPE=JPEG:${e.avatar}`:"","END:VCARD"].join("\n");return await this.sendMessage(t.roomId,{contacts:{displayName:e.fullname,contacts:[{vcard:s}]},...t})}async reaction(e,t){return e=Ms.parse(e),t=Ss.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Zs.parse(e),t=Os.parse(t);return await this.sendMessage(t.message()?.key?.remoteJid,{pin:{type:"pin"==e.action?1:0,time:{"24h":86400,"7d":604800,"30d":2592e3}[e.expired],key:t.message()?.key},...t})}async poll(e,t){return e=Es.parse(e),t=As.parse(t),await this.sendMessage(t.roomId,{poll:{name:e.name,values:e.answers,selectableCount:e.multipleAnswers?1:0,toAnnouncementGroup:!0},...t})}async edit(e,t){return e=Ps.parse(e),t=js.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=Rs.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=$s.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Us.parse(e),t=Fs.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(t){const s=(t=Ds.parse(t)).includes("@g.us"),a={};a.id=t;if(e.jidNormalizedUser(this.wa.socket?.user?.id)==t)a.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(s){const e=await(this.wa.socket?.groupMetadata(t));a.type="group",a.name=e?.subject,a.bio=e?.desc,a.avatar=await(this.wa.socket?.profilePictureUrl(t)),a.ephemeralDuration=e?.ephemeralDuration,a.isRestrict=e?.restrict,a.isAnnounce=e?.announce,a.isCommunity=e?.isCommunity,a.isCommunityAnnounce=e?.isCommunityAnnounce,a.isJoinApprovalMode=e?.joinApprovalMode,a.isMemberAddMode=e?.memberAddMode,a.owner={type:"user",id:e?.owner},a.roomCreatedAt=e?.creation,a.nameUpdatedAt=e?.subjectTime,a.membersLength=e?.size,a.members=e?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const e=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",t).executeTakeFirst()),s=S(e?.value),n=(await(this.wa?.socket?.fetchStatus(t)))[0]?.status;a.type="user",a.name=s?.name,a.bio=n?.status,a.avatar=await(this.wa?.socket?.profilePictureUrl(t)),a.bioUpdatedAt=new Date(n?.setAt).getTime()}return a}async presence(e,t){e=qs.parse(e),t=Ls.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}},Vs=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options={};cache=new x.default({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=C.default({level:"silent",enabled:!1});db;socket;events=new t.EventEmitter;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{w.default(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await bs.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",s=N.default.resolve(e);return o.mkdirSync(N.default.dirname(s),{recursive:!0}),o.writeFileSync(s,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new I.default(s)})})}const s=new p.URL(t),a=s.protocol.replace(":","");if("mysql"===e)return new d.Kysely({dialect:new d.MysqlDialect({pool:T.default.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===e)return new d.Kysely({dialect:new d.PostgresDialect({pool:new l.Pool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${a}`)})(this.options.database.type,this.options.database.connection.url),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:s}=await ms(this.db,this.chatId);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const a=await(async(e,t,s)=>({bind:a=>{const n=new os(a,e,t);a?.ev.on("connection.update",(async e=>{await n.connection(e)})),a?.ev.on("call",(async e=>{for(const t of e)await n.calls(t)})),a?.ev.on("messaging-history.set",(async e=>{const{chats:a,contacts:n,messages:i}=e;for(const e of a)await t.insertInto("chats").values({session:s,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of n)await t.insertInto("contacts").values({session:s,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of i){if(!e.message)return;if(e.message?.protocolMessage)return;await t.insertInto("messages").values({session:s,id:e.key.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute()}})),a?.ev.on("messages.upsert",(async({messages:e})=>{for(const a of e){if(!a.message)return;if(a.message?.protocolMessage)return;await n.messages(a),await t.insertInto("messages").values({session:s,id:a.key.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()}})),a?.ev.on("chats.upsert",(async e=>{for(const a of e)await t.insertInto("chats").values({session:s,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a?.ev.on("contacts.upsert",(async e=>{for(const a of e)await t.insertInto("contacts").values({session:s,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a?.ev.on("groups.update",(async([t])=>{const s=await(a?.groupMetadata(t.id));e.cache.set(t.id,s)})),a?.ev.on("group-participants.update",(async t=>{const s=await(a?.groupMetadata(t.id));e.cache.set(t.id,s)}))}}))(this,this.db,this.chatId);this.stopSpinner("store",!0,"Store adapter ready");const{version:n}=await e.fetchLatestBaileysVersion();if(this.socket=b.default({version:n,logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new x.default,mediaCache:new x.default({stdTTL:60}),userDevicesCache:new x.default,cachedGroupMetadata:async e=>this.cache.get(e),printQRInTerminal:"qr"===this.options.authType,browser:e.Browsers.ubuntu("qr"===this.options.authType?"Zaileys Library":"Chrome"),auth:{creds:t.creds,keys:e.makeCacheableSignalKeyStore(t.keys,this.logger)},getMessage:async e=>{const t=await(this.db?.selectFrom("messages").select("value").where("id","=",e.id).executeTakeFirst());return S(t?.value)}}),"pairing"===this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered){this.startSpinner("pairing","Generating pairing code...");(await this.socket.onWhatsApp(this.options.phoneNumber.toString()+"@s.whatsapp.net"))[0].exists||(this.failSpinner("pairing","Phone is not registered in WhatsApp"),process.exit(1)),setTimeout((async()=>{try{if("pairing"===this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));this.stopSpinner("pairing",!0,`Pairing code: ${e}`)}}catch{this.failSpinner("pairing","Connection failed"),process.exit(1)}}),5e3)}this.worker=new zs({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",s),a.bind(this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=k.default(t).start(),this.spinners.set(e,s)),s}stopSpinner(e,t,s){const a=this.spinners.get(e);a&&(t?a.succeed(s):a.stop(),this.spinners.delete(e))}failSpinner(e,t){const s=this.spinners.get(e);s&&(s.fail(t),this.spinners.delete(e))}on(e,t){this.events.on(e,t)}emit(e,...t){this.events.emit(e,...t)}};module.exports=Vs;