zaileys 1.1.33 → 1.1.35
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/CHANGELOG.md +92 -0
- package/README.md +565 -294
- package/dist/index.d.mts +898 -2387
- package/dist/index.d.ts +898 -2387
- package/dist/index.js +1986 -1
- package/dist/index.mjs +1960 -1
- package/package.json +42 -35
package/dist/index.mjs
CHANGED
|
@@ -1 +1,1960 @@
|
|
|
1
|
-
import{fetchLatestBaileysVersion as e,makeWASocket as t,makeCacheableSignalKeyStore as s,Browsers as a,initAuthCreds as n,generateWAMessage as i,jidNormalizedUser as r,BufferJSON as o,DisconnectReason as d,getContentType as c,getDevice as l,downloadMediaMessage as u}from"baileys";import{EventEmitter as p}from"events";import h from"figlet";import m from"node-cache";import f from"ora";import g from"pino";import y from"better-sqlite3";import{mkdirSync as v,writeFileSync as _}from"fs";import{Kysely as w,SqliteDialect as b,MysqlDialect as x,PostgresDialect as k,sql as C}from"kysely";import I from"mysql2";import M from"path";import{Pool as T}from"pg";import{URL as S}from"url";import N from"qrcode";import A from"os";import{Readable as O}from"stream";import E from"bottleneck";import{Hono as L}from"hono";import{serve as Z}from"@hono/node-server";import*as j from"fast-levenshtein";var P,R,F,$=Object.defineProperty,q=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e},(()=>t[Math.floor(62*Math.random())])).join("")},z=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},U=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},D=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,V=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>V(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?V(s,t):s]))):e,J=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},K={};((e,t)=>{for(var s in t)$(e,s,{get:t[s],enumerable:!0})})(K,{BRAND:()=>Ct,DIRTY:()=>ce,EMPTY_PATH:()=>ae,INVALID:()=>de,NEVER:()=>vs,OK:()=>le,ParseStatus:()=>oe,Schema:()=>_e,ZodAny:()=>We,ZodArray:()=>Xe,ZodBigInt:()=>De,ZodBoolean:()=>Ve,ZodBranded:()=>It,ZodCatch:()=>xt,ZodDate:()=>Je,ZodDefault:()=>bt,ZodDiscriminatedUnion:()=>nt,ZodEffects:()=>vt,ZodEnum:()=>ft,ZodError:()=>H,ZodFirstPartyTypeKind:()=>At,ZodFunction:()=>ut,ZodIntersection:()=>rt,ZodIssueCode:()=>W,ZodLazy:()=>pt,ZodLiteral:()=>ht,ZodMap:()=>ct,ZodNaN:()=>kt,ZodNativeEnum:()=>gt,ZodNever:()=>He,ZodNull:()=>Be,ZodNullable:()=>wt,ZodNumber:()=>Ue,ZodObject:()=>tt,ZodOptional:()=>_t,ZodParsedType:()=>G,ZodPipeline:()=>Mt,ZodPromise:()=>yt,ZodReadonly:()=>Tt,ZodRecord:()=>dt,ZodSchema:()=>_e,ZodSet:()=>lt,ZodString:()=>qe,ZodSymbol:()=>Ke,ZodTransformer:()=>vt,ZodTuple:()=>ot,ZodType:()=>_e,ZodUndefined:()=>Ge,ZodUnion:()=>st,ZodUnknown:()=>Ye,ZodVoid:()=>Qe,addIssueToContext:()=>ne,any:()=>Dt,array:()=>Gt,bigint:()=>Rt,boolean:()=>Ft,coerce:()=>ys,custom:()=>Nt,date:()=>$t,datetimeRegex:()=>Re,defaultErrorMap:()=>Q,discriminatedUnion:()=>Ht,effect:()=>cs,enum:()=>rs,function:()=>as,getErrorMap:()=>te,getParsedType:()=>B,instanceof:()=>Lt,intersection:()=>Qt,isAborted:()=>ue,isAsync:()=>me,isDirty:()=>pe,isValid:()=>he,late:()=>Et,lazy:()=>ns,literal:()=>is,makeIssue:()=>se,map:()=>ts,nan:()=>Pt,nativeEnum:()=>os,never:()=>Jt,null:()=>Ut,nullable:()=>us,number:()=>jt,object:()=>Bt,objectUtil:()=>F,oboolean:()=>gs,onumber:()=>fs,optional:()=>ls,ostring:()=>ms,pipeline:()=>hs,preprocess:()=>ps,promise:()=>ds,quotelessJson:()=>Y,record:()=>es,set:()=>ss,setErrorMap:()=>ee,strictObject:()=>Wt,string:()=>Zt,symbol:()=>qt,transformer:()=>cs,tuple:()=>Xt,undefined:()=>zt,union:()=>Yt,unknown:()=>Vt,util:()=>P,void:()=>Kt}),(R=P||(P={})).assertEqual=e=>{},R.assertIs=function(e){},R.assertNever=function(e){throw new Error},R.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},R.getValidEnumValues=e=>{const t=R.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return R.objectValues(s)},R.objectValues=e=>R.objectKeys(e).map((function(t){return e[t]})),R.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},R.find=(e,t)=>{for(const s of e)if(t(s))return s},R.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,R.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},R.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(F||(F={})).mergeShapes=(e,t)=>({...e,...t});var G=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),B=e=>{switch(typeof e){case"undefined":return G.undefined;case"string":return G.string;case"number":return Number.isNaN(e)?G.nan:G.number;case"boolean":return G.boolean;case"function":return G.function;case"bigint":return G.bigint;case"symbol":return G.symbol;case"object":return Array.isArray(e)?G.array:null===e?G.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?G.promise:"undefined"!=typeof Map&&e instanceof Map?G.map:"undefined"!=typeof Set&&e instanceof Set?G.set:"undefined"!=typeof Date&&e instanceof Date?G.date:G.object;default:return G.unknown}},W=P.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"]),Y=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),H=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,P.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()}};H.create=e=>new H(e);var Q=(e,t)=>{let s;switch(e.code){case W.invalid_type:s=e.received===G.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case W.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,P.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:s=`Unrecognized key(s) in object: ${P.joinValues(e.keys,", ")}`;break;case W.invalid_union:s="Invalid input";break;case W.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${P.joinValues(e.options)}`;break;case W.invalid_enum_value:s=`Invalid enum value. Expected ${P.joinValues(e.options)}, received '${e.received}'`;break;case W.invalid_arguments:s="Invalid function arguments";break;case W.invalid_return_type:s="Invalid function return type";break;case W.invalid_date:s="Invalid date";break;case W.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}"`:P.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case W.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 W.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 W.custom:s="Invalid input";break;case W.invalid_intersection_types:s="Intersection results could not be merged";break;case W.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case W.not_finite:s="Number must be finite";break;default:s=t.defaultError,P.assertNever(e)}return{message:s}},X=Q;function ee(e){X=e}function te(){return X}var se=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}},ae=[];function ne(e,t){const s=te(),a=se({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===Q?void 0:Q].filter((e=>!!e))});e.common.issues.push(a)}var ie,re,oe=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 de;"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 de;if("aborted"===n.status)return de;"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}}},de=Object.freeze({status:"aborted"}),ce=e=>({status:"dirty",value:e}),le=e=>({status:"valid",value:e}),ue=e=>"aborted"===e.status,pe=e=>"dirty"===e.status,he=e=>"valid"===e.status,me=e=>"undefined"!=typeof Promise&&e instanceof Promise;(re=ie||(ie={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},re.toString=e=>"string"==typeof e?e:e?.message;var fe=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||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ge=(e,t)=>{if(he(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 H(e.common.issues);return this._error=t,this._error}}};function ye(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)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??a??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??s??n.defaultError}},description:n}}var ve,_e=class{get description(){return this._def.description}_getType(e){return B(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:B(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new oe,ctx:{common:e.parent.common,data:e.data,parsedType:B(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(me(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){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:B(e)},a=this._parseSync({data:e,path:s.path,parent:s});return ge(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:B(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return he(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>he(e)?{value:e.value}:{issues:t.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:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:B(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(me(a)?a:Promise.resolve(a));return ge(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:W.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 vt({schema:this,typeName:At.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 _t.create(this,this._def)}nullable(){return wt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return yt.create(this,this._def)}or(e){return st.create([this,e],this._def)}and(e){return rt.create(this,e,this._def)}transform(e){return new vt({...ye(this._def),schema:this,typeName:At.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new bt({...ye(this._def),innerType:this,defaultValue:t,typeName:At.ZodDefault})}brand(){return new It({typeName:At.ZodBranded,type:this,...ye(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new xt({...ye(this._def),innerType:this,catchValue:t,typeName:At.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Mt.create(this,e)}readonly(){return Tt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},we=/^c[^\s-]{8,}$/i,be=/^[0-9a-z]+$/,xe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ke=/^[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,Ce=/^[a-z0-9_-]{21}$/i,Ie=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Me=/^[-+]?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)?)??$/,Te=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Se=/^(?:(?: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])$/,Ne=/^(?:(?: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])$/,Ae=/^(([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]))$/,Oe=/^(([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])$/,Ee=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Le=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ze="((\\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])))",je=new RegExp(`^${Ze}$`);function Pe(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 Re(e){let t=`${Ze}T${Pe(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 Fe(e,t){if(!Ie.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&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function $e(e,t){return!("v4"!==t&&t||!Ne.test(e))||!("v6"!==t&&t||!Oe.test(e))}var qe=class e extends _e{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==G.string){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.string,received:t.parsedType}),de}const t=new oe;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),ne(s,{code:W.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),ne(s,{code:W.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?ne(s,{code:W.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&ne(s,{code:W.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)Te.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"email",code:W.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)ve||(ve=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ve.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"emoji",code:W.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)ke.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"uuid",code:W.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)Ce.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"nanoid",code:W.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)we.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"cuid",code:W.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)be.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"cuid2",code:W.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)xe.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"ulid",code:W.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ne(s,{validation:"url",code:W.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),ne(s,{validation:"regex",code:W.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),ne(s,{code:W.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),ne(s,{code:W.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),ne(s,{code:W.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Re(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{code:W.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){je.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{code:W.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Pe(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{code:W.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?Me.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"duration",code:W.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!Se.test(a))&&("v6"!==n&&n||!Ae.test(a))&&(s=this._getOrReturnCtx(e,s),ne(s,{validation:"ip",code:W.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Fe(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"jwt",code:W.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?$e(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"cidr",code:W.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Ee.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"base64",code:W.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Le.test(e.data)||(s=this._getOrReturnCtx(e,s),ne(s,{validation:"base64url",code:W.invalid_string,message:i.message}),t.dirty()):P.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:W.invalid_string,...ie.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...ie.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ie.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ie.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ie.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ie.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ie.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ie.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ie.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ie.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ie.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ie.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ie.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ie.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ie.errToObj(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===e?.precision?null:e?.precision,...ie.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ie.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ie.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ie.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ie.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ie.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ie.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ie.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ie.errToObj(t)})}nonempty(e){return this.min(1,ie.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 ze(e,t){const s=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=s>a?s:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}qe.create=e=>new qe({checks:[],typeName:At.ZodString,coerce:e?.coerce??!1,...ye(e)});var Ue=class e extends _e{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)!==G.number){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.number,received:t.parsedType}),de}let t;const s=new oe;for(const a of this._def.checks)if("int"===a.kind)P.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),ne(t,{code:W.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),ne(t,{code:W.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),ne(t,{code:W.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==ze(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),ne(t,{code:W.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),ne(t,{code:W.not_finite,message:a.message}),s.dirty()):P.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ie.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ie.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ie.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ie.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:ie.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:ie.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ie.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ie.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ie.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ie.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ie.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ie.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ie.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ie.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&&P.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)}};Ue.create=e=>new Ue({checks:[],typeName:At.ZodNumber,coerce:e?.coerce||!1,...ye(e)});var De=class e extends _e{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==G.bigint)return this._getInvalidInput(e);let t;const s=new oe;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),ne(t,{code:W.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),ne(t,{code:W.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),ne(t,{code:W.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):P.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.bigint,received:t.parsedType}),de}gte(e,t){return this.setLimit("min",e,!0,ie.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ie.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ie.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ie.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:ie.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:ie.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ie.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ie.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ie.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ie.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}};De.create=e=>new De({checks:[],typeName:At.ZodBigInt,coerce:e?.coerce??!1,...ye(e)});var Ve=class extends _e{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==G.boolean){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.boolean,received:t.parsedType}),de}return le(e.data)}};Ve.create=e=>new Ve({typeName:At.ZodBoolean,coerce:e?.coerce||!1,...ye(e)});var Je=class e extends _e{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==G.date){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.date,received:t.parsedType}),de}if(Number.isNaN(e.data.getTime())){return ne(this._getOrReturnCtx(e),{code:W.invalid_date}),de}const t=new oe;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),ne(s,{code:W.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),ne(s,{code:W.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):P.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:ie.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ie.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}};Je.create=e=>new Je({checks:[],coerce:e?.coerce||!1,typeName:At.ZodDate,...ye(e)});var Ke=class extends _e{_parse(e){if(this._getType(e)!==G.symbol){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.symbol,received:t.parsedType}),de}return le(e.data)}};Ke.create=e=>new Ke({typeName:At.ZodSymbol,...ye(e)});var Ge=class extends _e{_parse(e){if(this._getType(e)!==G.undefined){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.undefined,received:t.parsedType}),de}return le(e.data)}};Ge.create=e=>new Ge({typeName:At.ZodUndefined,...ye(e)});var Be=class extends _e{_parse(e){if(this._getType(e)!==G.null){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.null,received:t.parsedType}),de}return le(e.data)}};Be.create=e=>new Be({typeName:At.ZodNull,...ye(e)});var We=class extends _e{constructor(){super(...arguments),this._any=!0}_parse(e){return le(e.data)}};We.create=e=>new We({typeName:At.ZodAny,...ye(e)});var Ye=class extends _e{constructor(){super(...arguments),this._unknown=!0}_parse(e){return le(e.data)}};Ye.create=e=>new Ye({typeName:At.ZodUnknown,...ye(e)});var He=class extends _e{_parse(e){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.never,received:t.parsedType}),de}};He.create=e=>new He({typeName:At.ZodNever,...ye(e)});var Qe=class extends _e{_parse(e){if(this._getType(e)!==G.undefined){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.void,received:t.parsedType}),de}return le(e.data)}};Qe.create=e=>new Qe({typeName:At.ZodVoid,...ye(e)});var Xe=class e extends _e{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==G.array)return ne(t,{code:W.invalid_type,expected:G.array,received:t.parsedType}),de;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(ne(t,{code:e?W.too_big:W.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&&(ne(t,{code:W.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&&(ne(t,{code:W.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 fe(t,e,t.path,s))))).then((e=>oe.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new fe(t,e,t.path,s))));return oe.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:ie.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:ie.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:ie.toString(s)}})}nonempty(e){return this.min(1,e)}};function et(e){if(e instanceof tt){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=_t.create(et(a))}return new tt({...e._def,shape:()=>t})}return e instanceof Xe?new Xe({...e._def,type:et(e.element)}):e instanceof _t?_t.create(et(e.unwrap())):e instanceof wt?wt.create(et(e.unwrap())):e instanceof ot?ot.create(e.items.map((e=>et(e)))):e}Xe.create=(e,t)=>new Xe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:At.ZodArray,...ye(t)});var tt=class e extends _e{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=P.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==G.object){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.object,received:t.parsedType}),de}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof He&&"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 fe(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof He){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&&(ne(s,{code:W.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 fe(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=>oe.mergeObjectSync(t,e))):oe.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return ie.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,s)=>{const a=this._def.errorMap?.(e,s).message??s.defaultError;return"unrecognized_keys"===e.code?{message:ie.errToObj(t).message??a}:{message:a}}}:{}})}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:At.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const s={};for(const e of P.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){const s={};for(const e of P.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return et(this)}partial(t){const s={};for(const e of P.objectKeys(this.shape)){const a=this.shape[e];t&&!t[e]?s[e]=a:s[e]=a.optional()}return new e({...this._def,shape:()=>s})}required(t){const s={};for(const e of P.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof _t;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return mt(P.objectKeys(this.shape))}};tt.create=(e,t)=>new tt({shape:()=>e,unknownKeys:"strip",catchall:He.create(),typeName:At.ZodObject,...ye(t)}),tt.strictCreate=(e,t)=>new tt({shape:()=>e,unknownKeys:"strict",catchall:He.create(),typeName:At.ZodObject,...ye(t)}),tt.lazycreate=(e,t)=>new tt({shape:e,unknownKeys:"strip",catchall:He.create(),typeName:At.ZodObject,...ye(t)});var st=class extends _e{_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 H(e.ctx.common.issues)));return ne(t,{code:W.invalid_union,unionErrors:s}),de}));{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 H(e)));return ne(t,{code:W.invalid_union,unionErrors:n}),de}}get options(){return this._def.options}};st.create=(e,t)=>new st({options:e,typeName:At.ZodUnion,...ye(t)});var at=e=>e instanceof pt?at(e.schema):e instanceof vt?at(e.innerType()):e instanceof ht?[e.value]:e instanceof ft?e.options:e instanceof gt?P.objectValues(e.enum):e instanceof bt?at(e._def.innerType):e instanceof Ge?[void 0]:e instanceof Be?[null]:e instanceof _t?[void 0,...at(e.unwrap())]:e instanceof wt?[null,...at(e.unwrap())]:e instanceof It||e instanceof Tt?at(e.unwrap()):e instanceof xt?at(e._def.innerType):[],nt=class e extends _e{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==G.object)return ne(t,{code:W.invalid_type,expected:G.object,received:t.parsedType}),de;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}):(ne(t,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),de)}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=at(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:At.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ye(a)})}};function it(e,t){const s=B(e),a=B(t);if(e===t)return{valid:!0,data:e};if(s===G.object&&a===G.object){const s=P.objectKeys(t),a=P.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=it(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===G.array&&a===G.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=it(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===G.date&&a===G.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var rt=class extends _e{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(ue(e)||ue(a))return de;const n=it(e.value,a.value);return n.valid?((pe(e)||pe(a))&&t.dirty(),{status:t.value,value:n.data}):(ne(s,{code:W.invalid_intersection_types}),de)};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}))}};rt.create=(e,t,s)=>new rt({left:e,right:t,typeName:At.ZodIntersection,...ye(s)});var ot=class e extends _e{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==G.array)return ne(s,{code:W.invalid_type,expected:G.array,received:s.parsedType}),de;if(s.data.length<this._def.items.length)return ne(s,{code:W.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),de;!this._def.rest&&s.data.length>this._def.items.length&&(ne(s,{code:W.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 fe(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>oe.mergeArray(t,e))):oe.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ot.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ot({items:e,typeName:At.ZodTuple,rest:null,...ye(t)})};var dt=class e extends _e{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!==G.object)return ne(s,{code:W.invalid_type,expected:G.object,received:s.parsedType}),de;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new fe(s,e,s.path,e)),value:i._parse(new fe(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?oe.mergeObjectAsync(t,a):oe.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof _e?{keyType:t,valueType:s,typeName:At.ZodRecord,...ye(a)}:{keyType:qe.create(),valueType:t,typeName:At.ZodRecord,...ye(s)})}},ct=class extends _e{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!==G.map)return ne(s,{code:W.invalid_type,expected:G.map,received:s.parsedType}),de;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new fe(s,e,s.path,[i,"key"])),value:n._parse(new fe(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 de;"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 de;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};ct.create=(e,t,s)=>new ct({valueType:t,keyType:e,typeName:At.ZodMap,...ye(s)});var lt=class e extends _e{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==G.set)return ne(s,{code:W.invalid_type,expected:G.set,received:s.parsedType}),de;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(ne(s,{code:W.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&&(ne(s,{code:W.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 de;"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 fe(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:ie.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:ie.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};lt.create=(e,t)=>new lt({valueType:e,minSize:null,maxSize:null,typeName:At.ZodSet,...ye(t)});var ut=class e extends _e{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==G.function)return ne(t,{code:W.invalid_type,expected:G.function,received:t.parsedType}),de;function s(e,s){return se({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,te(),Q].filter((e=>!!e)),issueData:{code:W.invalid_arguments,argumentsError:s}})}function a(e,s){return se({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,te(),Q].filter((e=>!!e)),issueData:{code:W.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof yt){const e=this;return le((async function(...t){const r=new H([]),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 le((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new H([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new H([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:ot.create(t).rest(Ye.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||ot.create([]).rest(Ye.create()),returns:s||Ye.create(),typeName:At.ZodFunction,...ye(a)})}},pt=class extends _e{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})}};pt.create=(e,t)=>new pt({getter:e,typeName:At.ZodLazy,...ye(t)});var ht=class extends _e{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return ne(t,{received:t.data,code:W.invalid_literal,expected:this._def.value}),de}return{status:"valid",value:e.data}}get value(){return this._def.value}};function mt(e,t){return new ft({values:e,typeName:At.ZodEnum,...ye(t)})}ht.create=(e,t)=>new ht({value:e,typeName:At.ZodLiteral,...ye(t)});var ft=class e extends _e{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return ne(t,{expected:P.joinValues(s),received:t.parsedType,code:W.invalid_type}),de}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return ne(t,{received:t.data,code:W.invalid_enum_value,options:s}),de}return le(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})}};ft.create=mt;var gt=class extends _e{_parse(e){const t=P.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==G.string&&s.parsedType!==G.number){const e=P.objectValues(t);return ne(s,{expected:P.joinValues(e),received:s.parsedType,code:W.invalid_type}),de}if(this._cache||(this._cache=new Set(P.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=P.objectValues(t);return ne(s,{received:s.data,code:W.invalid_enum_value,options:e}),de}return le(e.data)}get enum(){return this._def.values}};gt.create=(e,t)=>new gt({values:e,typeName:At.ZodNativeEnum,...ye(t)});var yt=class extends _e{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==G.promise&&!1===t.common.async)return ne(t,{code:W.invalid_type,expected:G.promise,received:t.parsedType}),de;const s=t.parsedType===G.promise?t.data:Promise.resolve(t.data);return le(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};yt.create=(e,t)=>new yt({type:e,typeName:At.ZodPromise,...ye(t)});var vt=class extends _e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===At.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=>{ne(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 de;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?de:"dirty"===a.status||"dirty"===t.value?ce(a.value):a}));{if("aborted"===t.value)return de;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?de:"dirty"===a.status||"dirty"===t.value?ce(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?de:("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?de:("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(!he(e))return de;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=>he(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):de))}P.assertNever(a)}};vt.create=(e,t,s)=>new vt({schema:e,typeName:At.ZodEffects,effect:t,...ye(s)}),vt.createWithPreprocess=(e,t,s)=>new vt({schema:t,effect:{type:"preprocess",transform:e},typeName:At.ZodEffects,...ye(s)});var _t=class extends _e{_parse(e){return this._getType(e)===G.undefined?le(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_t.create=(e,t)=>new _t({innerType:e,typeName:At.ZodOptional,...ye(t)});var wt=class extends _e{_parse(e){return this._getType(e)===G.null?le(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wt.create=(e,t)=>new wt({innerType:e,typeName:At.ZodNullable,...ye(t)});var bt=class extends _e{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===G.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};bt.create=(e,t)=>new bt({innerType:e,typeName:At.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ye(t)});var xt=class extends _e{_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 me(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new H(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new H(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};xt.create=(e,t)=>new xt({innerType:e,typeName:At.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ye(t)});var kt=class extends _e{_parse(e){if(this._getType(e)!==G.nan){const t=this._getOrReturnCtx(e);return ne(t,{code:W.invalid_type,expected:G.nan,received:t.parsedType}),de}return{status:"valid",value:e.data}}};kt.create=e=>new kt({typeName:At.ZodNaN,...ye(e)});var Ct=Symbol("zod_brand"),It=class extends _e{_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}},Mt=class e extends _e{_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?de:"dirty"===e.status?(t.dirty(),ce(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?de:"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:At.ZodPipeline})}},Tt=class extends _e{_parse(e){const t=this._def.innerType._parse(e),s=e=>(he(e)&&(e.value=Object.freeze(e.value)),e);return me(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function St(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function Nt(e,t={},s){return e?We.create().superRefine(((a,n)=>{const i=e(a);if(i instanceof Promise)return i.then((e=>{if(!e){const e=St(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=St(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):We.create()}Tt.create=(e,t)=>new Tt({innerType:e,typeName:At.ZodReadonly,...ye(t)});var At,Ot,Et={object:tt.lazycreate};(Ot=At||(At={})).ZodString="ZodString",Ot.ZodNumber="ZodNumber",Ot.ZodNaN="ZodNaN",Ot.ZodBigInt="ZodBigInt",Ot.ZodBoolean="ZodBoolean",Ot.ZodDate="ZodDate",Ot.ZodSymbol="ZodSymbol",Ot.ZodUndefined="ZodUndefined",Ot.ZodNull="ZodNull",Ot.ZodAny="ZodAny",Ot.ZodUnknown="ZodUnknown",Ot.ZodNever="ZodNever",Ot.ZodVoid="ZodVoid",Ot.ZodArray="ZodArray",Ot.ZodObject="ZodObject",Ot.ZodUnion="ZodUnion",Ot.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ot.ZodIntersection="ZodIntersection",Ot.ZodTuple="ZodTuple",Ot.ZodRecord="ZodRecord",Ot.ZodMap="ZodMap",Ot.ZodSet="ZodSet",Ot.ZodFunction="ZodFunction",Ot.ZodLazy="ZodLazy",Ot.ZodLiteral="ZodLiteral",Ot.ZodEnum="ZodEnum",Ot.ZodEffects="ZodEffects",Ot.ZodNativeEnum="ZodNativeEnum",Ot.ZodOptional="ZodOptional",Ot.ZodNullable="ZodNullable",Ot.ZodDefault="ZodDefault",Ot.ZodCatch="ZodCatch",Ot.ZodPromise="ZodPromise",Ot.ZodBranded="ZodBranded",Ot.ZodPipeline="ZodPipeline",Ot.ZodReadonly="ZodReadonly";var Lt=(e,t={message:`Input not instance of ${e.name}`})=>Nt((t=>t instanceof e),t),Zt=qe.create,jt=Ue.create,Pt=kt.create,Rt=De.create,Ft=Ve.create,$t=Je.create,qt=Ke.create,zt=Ge.create,Ut=Be.create,Dt=We.create,Vt=Ye.create,Jt=He.create,Kt=Qe.create,Gt=Xe.create,Bt=tt.create,Wt=tt.strictCreate,Yt=st.create,Ht=nt.create,Qt=rt.create,Xt=ot.create,es=dt.create,ts=ct.create,ss=lt.create,as=ut.create,ns=pt.create,is=ht.create,rs=ft.create,os=gt.create,ds=yt.create,cs=vt.create,ls=_t.create,us=wt.create,ps=vt.createWithPreprocess,hs=Mt.create,ms=()=>Zt().optional(),fs=()=>jt().optional(),gs=()=>Ft().optional(),ys={string:e=>qe.create({...e,coerce:!0}),number:e=>Ue.create({...e,coerce:!0}),boolean:e=>Ve.create({...e,coerce:!0}),bigint:e=>De.create({...e,coerce:!0}),date:e=>Je.create({...e,coerce:!0})},vs=de,_s={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"},ws={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"},bs=K.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"]),xs=K.enum(["unknown","android","ios","desktop","web"]),ks=K.object({chatId:K.string(),channelId:K.string(),uniqueId:K.string(),receiverId:K.string(),receiverName:K.string(),roomId:K.string(),roomName:K.string(),senderId:K.string(),senderName:K.string(),senderDevice:xs,chatType:bs,timestamp:K.number(),mentions:K.string().array(),text:K.string().nullable(),links:K.string().array(),isPrefix:K.boolean(),isSpam:K.boolean(),isFromMe:K.boolean(),isTagMe:K.boolean(),isGroup:K.boolean(),isStory:K.boolean(),isViewOnce:K.boolean(),isEdited:K.boolean(),isDeleted:K.boolean(),isPinned:K.boolean(),isUnPinned:K.boolean(),isChannel:K.boolean(),isBroadcast:K.boolean(),isEphemeral:K.boolean(),isForwarded:K.boolean(),citation:K.record(K.string(),K.boolean()).nullable(),media:K.object({buffer:K.function().returns(K.instanceof(Buffer)),stream:K.function().returns(K.instanceof(O))}).passthrough().nullable(),message:K.function().returns(K.record(K.string(),K.any()))}),Cs=ks.extend({replied:ks.nullable()}),Is=new m({stdTTL:3600,checkperiod:600}),Ms=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(e){this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:t,lastDisconnect:s,qr:a}=e;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&a)return console.log(),console.log(await N.toString(a,{type:"terminal",small:!0})),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===t){const e=s?.error?.output?.statusCode,a=e===d.restartRequired||e===d.connectionLost;if(this.client.failSpinner("connection",`[Connection Closed] [${e}]\n${s?.error?.message}\n`),401===e||405===e||500===e)return void console.error("Invalid session, please delete manually");a&&"close"==t&&await this.client.initialize()}else"open"===t&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}));this.client.stopSpinner("connection",!1)}async messages(e,t,s){if(e?.messageStubType||e?.messageStubParameters?.length||e?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||e?.message?.botInvokeMessage||!e?.key?.id||!e?.message)return null;if(this.client.options?.ignoreMe&&e?.key?.fromMe&&!this.maxReplies&&!s&&"status@broadcast"!=e?.key?.remoteJid&&!e?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([e?.key]);const a=e,n=e?.message?.pinInChatMessage?.key?.id,i=1==e?.message?.pinInChatMessage?.type,o=2==e?.message?.pinInChatMessage?.type;if(n){const t=await this.db.selectFrom("messages").select("value").where("id","=",n).executeTakeFirst(),s=z(t?.value);e=s}const d=!e?.message?.protocolMessage?.editedMessage&&e?.message?.protocolMessage?.key?.id,p=!!d;if(d){const t=await this.db.selectFrom("messages").select("value").where("id","=",d).executeTakeFirst(),s=z(t?.value);e=s}const h={},m=c(e?.message?.protocolMessage?.editedMessage||e?.message);h.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id,h.channelId="",h.uniqueId="",h.receiverId=r(this.socket.user?.id),h.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,h.roomId=r(e?.key?.remoteJid);const f=await this.db.selectFrom("chats").select("value").where("id","=",h.roomId).executeTakeFirst();h.roomName=z(f?.value)?.name,h.senderId=r(e?.participant||e?.key?.participant||e?.key?.remoteJid);const g=await this.db.selectFrom("chats").select("value").where("id","=",h.senderId).executeTakeFirst();if(h.senderName=e?.pushName||e?.verifiedBizName||z(g?.value)?.name||h.receiverName,h.roomName=h.roomName||h.senderName,h.senderDevice=l(h.chatId),h.chatType=_s[m],h.timestamp=e?.messageTimestamp?.low||e?.messageTimestamp||0,h.mentions=[],h.text=null,h.links=[],h.isPrefix=!1,h.isSpam=!1,h.isFromMe=e?.key?.fromMe,h.isTagMe=!1,h.isGroup=h.roomId.includes("@g.us"),h.isStory=h.roomId.includes("@broadcast"),h.isViewOnce=!1,h.isEdited=!1,h.isDeleted=p,h.isPinned=i,h.isUnPinned=o,h.isChannel=h.roomId.includes("@newsletter"),h.isBroadcast=!!e?.broadcast,h.isEphemeral=!1,h.isForwarded=!1,!t&&!s){const e=await(async(e,t,s)=>{const a=new E({maxConcurrent:1,minTime:0,reservoir:t,reservoirRefreshAmount:t,reservoirRefreshInterval:s}),n=Date.now(),i=Is.get(e)||{count:0,last:0};n-i.last>s&&(i.count=0),i.count+=1,i.last=n,Is.set(e,i);try{return await a.schedule((async()=>i.count>t?(Is.set(e,{...i,blacklisted:n+s}),!0):await!1))}catch(e){return console.error("Error detecting spam:",e),!1}})(h.roomId,this.client.options.limiter?.maxMessages,this.client.options.limiter?.durationMs);h.isSpam=e}h.isFromMe&&(h.senderId=h.receiverId,h.senderName=h.receiverName),h.citation=null,h.media=null,h.replied=null,h.channelId=h.roomId.split("@")[0]+"-"+h.senderId.split("@")[0],h.uniqueId=h.channelId+"-"+h.chatId;const y=this.client.options?.citation;if(Object.keys(y).length){h.citation={};for(const e of Object.keys(y))h.citation[e]=y[e].includes(Number(h.senderId.split("@")[0]))||y[e].includes(Number(h.roomId.split("@")[0]))}const v=(e?.message?.protocolMessage?.editedMessage?.[m]||e?.message?.[m])?.message?.documentMessage||e?.message?.[m];"text"!=h.chatType&&(h.media={...V(v,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await u(e,"buffer",{}),stream:async()=>await u(e,"stream",{})});const _=e?.message?.[m]?.contextInfo?.stanzaId;if(_&&this.maxReplies<1){this.maxReplies++;const t=await this.db.selectFrom("messages").select("value").where("id","=",_).executeTakeFirst(),s=z(t?.value);if(s)h.replied=await this.messages(s,!0);else{const t=e,s=c(t.message?.extendedTextMessage?.contextInfo.quotedMessage);t.key.id=t.message?.extendedTextMessage?.contextInfo.stanzaId,t.message[s]=t.message?.extendedTextMessage?.contextInfo.quotedMessage[s],delete t.message?.extendedTextMessage,h.replied=await this.messages(t,!0)}this.maxReplies=0}const w="string"==typeof v?v:v?.text||v?.caption||v?.name||v?.displayName||"";h.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(w)||null,h.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(h.text),h.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(h.text);const b=e?.message?.[m];return h.isPrefix=!!this.client.options?.prefix&&!!h.text?.startsWith(this.client.options?.prefix),h.isTagMe=h.mentions.includes(h.receiverId.split("@")[0]),h.isEdited=D(U(e),"editedMessage"),h.isEphemeral=D(U(b?.contextInfo),"ephemeralSettingTimestamp"),h.isForwarded=D(U(b?.contextInfo),"forwardingScore"),h.isViewOnce=!!b?.viewOnce,h.isPrefix&&(h.text=h.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),h.message=()=>a,t||this.client.emit("messages",h),h}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)}async webhooks(e){let t;const s=e.req.method,a=e.req.query(),n=e.req.header("content-type")||"",i={query:a,json:null,form:null,raw:null};"GET"!=s&&(n.includes("application/json")?(i.json=await e.req.json().catch((()=>null)),t=await e.req.text()):n.includes("application/x-www-form-urlencoded")||n.includes("multipart/form-data")?(i.form=await e.req.parseBody().catch((()=>null)),t=await e.req.text()):(t=await e.req.text().catch((()=>null)),i.raw=t));const r={};r.id=q(20),r.method=s,r.host=e.req.header("host"),r.referer=e.req.header("referer"),r.date=e.req.header("date")||(new Date).toISOString(),r.size=Number(e.req.header("content-length")||Buffer.byteLength(t||"","utf8")),r.data=i,this.client.emit("webhooks",r)}},Ts=!1,Ss=async(e,t)=>{const s=new L,a=(()=>{const e=A.networkInterfaces();for(const t of Object.values(e))for(const e of t)if("IPv4"===e.family&&!e.internal)return e.address;return"localhost"})();s.get("/webhooks",(async e=>(t?.ev.emit("idle-webhooks",e),e.text("OK")))),s.post("/webhooks",(async e=>(t?.ev.emit("idle-webhooks",e),e.text("OK")))),Ts||Z({fetch:s.fetch,port:4135},(()=>{e.stopSpinner("webhooks",!0,`Webhooks Access\n - URL : http://${a}:4135/webhooks\n - PORT : 4135\n - METHOD: GET, POST`),Ts=!0})),e.stopSpinner("webhooks",!0,`Webhooks Access\n - URL : http://${a}:4135/webhooks\n - PORT : 4135\n - METHOD: GET, POST`)},Ns=async(e,t)=>{(e||t)&&await fetch(e,{method:"POST",body:JSON.stringify(t)}).catch((()=>null))},As=async(e,t,s)=>{const a="auth";await(async(e,t)=>{await e.transaction().execute((async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),t.loadLLMSchemas&&(await e.schema.createTable("llm_messages").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("channelId","char(36)").addColumn("model","char(36)").addColumn("role","varchar(20)",(e=>e.notNull())).addColumn("content","text",(e=>e.notNull())).addColumn("additional","text").addUniqueConstraint("llm_messages_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_personalization").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("senderId","char(36)").addColumn("content","text",(e=>e.notNull())).addUniqueConstraint("llm_personalization_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_rag").ifNotExists().addColumn("metadata.id","char(36)",(e=>e.notNull().primaryKey())).addColumn("pageContent","text",(e=>e.notNull())).addUniqueConstraint("llm_rag_id_unique",["metadata.id"]).execute(),await Promise.all([e.schema.createIndex("llm_messages_uniqueId_idx").ifNotExists().on("llm_messages").column("uniqueId").execute(),e.schema.createIndex("llm_messages_channelId_idx").ifNotExists().on("llm_messages").column("channelId").execute(),e.schema.createIndex("llm_messages_model_idx").ifNotExists().on("llm_messages").column("model").execute(),e.schema.createIndex("llm_messages_role_idx").ifNotExists().on("llm_messages").column("role").execute(),e.schema.createIndex("llm_personalization_uniqueId_idx").ifNotExists().on("llm_personalization").column("uniqueId").execute(),e.schema.createIndex("llm_personalization_senderId_idx").ifNotExists().on("llm_personalization").column("senderId").execute(),e.schema.createIndex("llm_rag_id_idx").ifNotExists().on("llm_rag").column("metadata.id").execute(),e.schema.createIndex("llm_rag_pageContent_idx").ifNotExists().on("llm_rag").column("pageContent").execute()])),await Promise.all([e.schema.createIndex("auth_session_id_idx").ifNotExists().on("auth").columns(["session","id"]).execute(),e.schema.createIndex("chats_session_id_idx").ifNotExists().on("chats").columns(["session","id"]).execute(),e.schema.createIndex("contacts_session_id_idx").ifNotExists().on("contacts").columns(["session","id"]).execute(),e.schema.createIndex("messages_session_id_idx").ifNotExists().on("messages").columns(["session","id"]).execute()])}))})(e,s);const i=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")},r=async s=>{const n=await i((()=>e.selectFrom(a).select(["value"]).where("id","=",s).where("session","=",t).executeTakeFirst()));if(!n?.value)return null;const r="object"==typeof n.value?JSON.stringify(n.value):n.value;return JSON.parse(r,o.reviver)},d=async(s,n)=>{const r=JSON.stringify(n,o.replacer);await i((()=>e.insertInto(a).values({session:t,id:s,value:r}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:r}))).execute()))},c=async s=>{await i((()=>e.deleteFrom(a).where("id","=",s).where("session","=",t).execute()))},l=await r("creds")||n();return{state:{creds:l,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await r(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=J(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 d(n,a):await c(n)}}}},saveCreds:async()=>{await d("creds",l)},clear:async()=>{await(async()=>{await i((()=>e.deleteFrom(a).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await i((()=>e.deleteFrom(a).where("session","=",t).execute()))})()}}},Os=K.object({type:K.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:K.object({url:K.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),Es=K.record(K.function().returns(K.union([K.number().array(),K.promise(K.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})),Ls=K.object({durationMs:K.number(),maxMessages:K.number()}).optional(),Zs=K.object({url:K.string()}).optional(),js=K.object({prefix:K.string().optional(),ignoreMe:K.boolean().optional().default(!0),showLogs:K.boolean().optional().default(!0),autoMentions:K.boolean().optional().default(!0),autoOnline:K.boolean().optional().default(!0),autoRead:K.boolean().optional().default(!0),autoPresence:K.boolean().optional().default(!0),autoRejectCall:K.boolean().optional().default(!0),loadLLMSchemas:K.boolean().optional().default(!1),webhooks:Zs,limiter:Ls,database:Os,citation:Es}),Ps=K.object({authType:K.literal("pairing"),phoneNumber:K.number()}).extend(js.shape),Rs=K.object({authType:K.literal("qr"),phoneNumber:K.undefined().optional()}).extend(js.shape),Fs=K.discriminatedUnion("authType",[Ps,Rs]),$s=K.object({channelId:K.string(),uniqueId:K.string(),model:K.string().min(2).max(100).optional().nullable(),role:K.string().min(2).max(100),content:K.string().min(1).max(65e3),additional:K.string().max(2e4).optional().nullable()}),qs=K.object({uniqueId:K.string(),senderId:K.string(),content:K.string().min(1).max(5e3)}),zs=K.object({metadata:K.object({id:K.string().default((()=>q(5)))}).default({}),pageContent:K.string().min(1).max(128e3)}),Us=zs.pick({pageContent:!0}),Ds=K.union([K.string().url(),K.instanceof(Buffer).or(K.instanceof(O))]),Vs=K.union([K.string(),K.object({image:Ds,text:K.string().optional()}).strict(),K.object({video:Ds,text:K.string().optional()}).strict(),K.object({note:Ds}).strict(),K.object({gif:Ds,text:K.string().optional()}).strict(),K.object({audio:Ds}).strict(),K.object({voice:Ds}).strict(),K.object({sticker:Ds}).strict()]),Js=K.object({roomId:K.string(),asForwarded:K.boolean().optional(),asViewOnce:K.boolean().optional(),asAI:K.boolean().optional(),verifiedReply:K.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:K.function().returns(K.record(K.string(),K.any())).optional()}),Ks=Js,Gs=K.object({latitude:K.number(),longitude:K.number(),title:K.string().optional(),footer:K.string().optional()}),Bs=Js,Ws=K.object({fullname:K.string(),nickname:K.string().optional(),organization:K.string().optional(),role:K.string().optional(),email:K.string().email().optional(),whatsAppNumber:K.number(),callNumber:K.number().optional(),voiceNumber:K.number().optional(),website:K.string().url().optional(),homeAddress:K.string().optional(),workAddress:K.string().optional(),avatar:K.string().url().optional()}),Ys=K.object({message:K.function().returns(K.record(K.string(),K.any()))}),Hs=K.string(),Qs=K.object({message:K.function().returns(K.record(K.string(),K.any()))}),Xs=K.object({action:K.enum(["pin","unpin"]),expired:K.enum(["24h","7d","30d"])}),ea=Js.pick({roomId:!0}),ta=K.object({name:K.string(),answers:K.string().array(),multipleAnswers:K.boolean().optional()}),sa=K.object({message:K.function().returns(K.record(K.string(),K.any()))}),aa=K.string(),na=K.object({message:K.function().returns(K.record(K.string(),K.any()))}),ia=K.object({callId:K.string(),callerId:K.string()}),ra=Js.pick({roomId:!0}),oa=K.object({expired:K.enum(["remove","8h","7d"])}),da=K.string(),ca=K.object({type:K.enum(["group","user"]),id:K.string(),name:K.string(),bio:K.string(),avatar:K.string().url(),ephemeralDuration:K.number().optional(),isRestrict:K.boolean().optional(),isAnnounce:K.boolean().optional(),isCommunity:K.boolean().optional(),isCommunityAnnounce:K.boolean().optional(),isJoinApprovalMode:K.boolean().optional(),isMemberAddMode:K.boolean().optional(),owner:K.object({type:K.literal("user"),id:K.string()}).nullable(),roomCreatedAt:K.number().optional(),nameUpdatedAt:K.number().optional(),bioUpdatedAt:K.number().optional(),membersLength:K.number().optional(),members:K.object({type:K.enum(["user","admin","superadmin"]),id:K.string()}).array().optional()}),la=Js.pick({roomId:!0}),ua=K.enum(["typing","recording","online","offline","paused"]),pa=class{constructor(e){this.wa=e,this.parser=new Ms(e.socket,e.client,e.db)}parser;caching=new m({stdTTL:600,checkperiod:120,maxKeys:1e3});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,r=[],o={contextInfo:{isForwarded:!!n?.asForwarded,mentionedJid:a}};if(e.match("@s.whatsapp.net")&&!!n?.asAI&&r.push({attrs:{biz_bot:"1"},tag:"bot"}),"function"==typeof n?.quoted){let e=n?.quoted();e.key.remoteJid=ws[n?.verifiedReply]||e.key.remoteJid,s={...s,quoted:e}}const d=await i(e,{...n,...o},{userJid:e,upload:async(e,t)=>await(this.wa?.socket?.waUploadToServer(e,t)),...s});return await(this.wa.socket?.relayMessage(e,d.message,{additionalNodes:r})),await this.parser.messages(d,!0,!0)}async text(e,t){const s=Vs.parse(e),a=Js.parse(t);if("string"==typeof s)return await this.sendMessage(a.roomId,{text:s,...a});const n={caption:s?.text,viewOnce:!!a.asViewOnce,...a},i={image:e=>({image:"string"==typeof e?{url:e}:e}),video:e=>({video:"string"==typeof e?{url:e}:e,ptv:!1}),note:e=>({video:"string"==typeof e?{url:e}:e,ptv:!0}),gif:e=>({video:"string"==typeof e?{url:e}:e,gifPlayback:!0}),audio:e=>({audio:"string"==typeof e?{url:e}:e}),voice:e=>({audio:"string"==typeof e?{url:e}:e,ptt:!0}),sticker:e=>({sticker:"string"==typeof e?{url:e}:e})};for(const[e,t]of Object.entries(i))if(e in s)return await this.sendMessage(a.roomId,{...n,...t(s[e])});throw new Error("Invalid media type")}async location(e,t){return e=Gs.parse(e),t=Ks.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=Ws.parse(e),t=Bs.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=Hs.parse(e),t=Ys.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Xs.parse(e),t=Qs.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=ta.parse(e),t=ea.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=aa.parse(e),t=sa.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=na.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=ia.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=oa.parse(e),t=ra.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(e){const t=(e=da.parse(e)).includes("@g.us"),s={};s.id=e;if(r(this.wa.socket?.user?.id)==e)s.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(t){const t=await(this.wa.socket?.groupMetadata(e));s.type="group",s.name=t?.subject,s.bio=t?.desc,s.avatar=await(this.wa.socket?.profilePictureUrl(e)),s.ephemeralDuration=t?.ephemeralDuration,s.isRestrict=t?.restrict,s.isAnnounce=t?.announce,s.isCommunity=t?.isCommunity,s.isCommunityAnnounce=t?.isCommunityAnnounce,s.isJoinApprovalMode=t?.joinApprovalMode,s.isMemberAddMode=t?.memberAddMode,s.owner={type:"user",id:t?.owner},s.roomCreatedAt=t?.creation,s.nameUpdatedAt=t?.subjectTime,s.membersLength=t?.size,s.members=t?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const t=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",e).executeTakeFirst()),a=z(t?.value),n=(await(this.wa?.socket?.fetchStatus(e)))[0]?.status;s.type="user",s.name=a?.name,s.bio=n?.status,s.avatar=await(this.wa?.socket?.profilePictureUrl(e)),s.bioUpdatedAt=new Date(n?.setAt).getTime()}return s}async presence(e,t){e=ua.parse(e),t=la.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}async addCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=$s.parse(e);if(!await(this.wa.db?.insertInto("llm_messages").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deleteCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async updateCompletion(e,t){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const s=$s.partial().parse(t),a=await(this.wa.db?.updateTable("llm_messages").set(s).where("uniqueId","=",e).returningAll().executeTakeFirst());if(!a)throw new Error("Failed to update completion");return $s.parse(a)}async clearCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("channelId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("uniqueId","=",e).executeTakeFirst());return t?$s.parse(t):null}async getCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("channelId","=",e).execute());return t?.map((e=>$s.parse(e)))||[]}async addPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=qs.parse(e);if(!await(this.wa.db?.insertInto("llm_personalization").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deletePersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async clearPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("senderId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_personalization").selectAll().where("senderId","=",e).execute());return t?.map((e=>qs.parse(e)))||[]}async addRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=zs.parse(e);if(!await(this.wa.db?.insertInto("llm_rag").values({pageContent:e.pageContent.toLowerCase(),"metadata.id":e.metadata?.id}).executeTakeFirst()))throw new Error("Failed to add RAG");return e}async deleteRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").where(C`"metadata.id"`,"=",e).executeTakeFirst()))throw new Error("Failed to delete RAG");return!0}async updateRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.updateTable("llm_rag").set({metadata:{id:e}}).where(C`"metadata.id"`,"=",e).returningAll().executeTakeFirst());if(!t)throw new Error("Failed to update RAG");return zs.parse(t)}async clearRAGs(){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").executeTakeFirst()))throw new Error("Failed to clear RAGs");return!0}async getRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_rag").selectAll().where(C`"metadata.id"`,"=",e).executeTakeFirst());return t?zs.parse(t):null}async getRAGs(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=e.toLowerCase().trim(),s=this.caching.get(t);if(s)return s;const a=t.split(/\s+/).filter((e=>e.length>0));if(!a.length)return[];const n=await(this.wa.db?.selectFrom("llm_rag").select([C`"metadata.id"`.as("metadata.id"),"pageContent"]).where("pageContent","!=","").limit(1e4).execute().then((e=>e.map((e=>zs.parse({...e,metadata:{id:e["metadata.id"]}}))))).then((e=>e.filter((e=>{const t=e.pageContent.toLowerCase().split(/\s+/);return a.some((e=>t.some((t=>j.get(e,t)<=Math.max(1,Math.floor(e.length/4))))))})))));return this.caching.set(t,n),n||[]}async getMessage(e){const t=await(this.wa.db?.selectFrom("messages").selectAll().where("id","=",e).executeTakeFirst());return t&&t?await this.parser.messages(z(t.value),!0,!0):null}llms={addCompletion:this.addCompletion.bind(this),deleteCompletion:this.deleteCompletion.bind(this),updateCompletion:this.updateCompletion.bind(this),clearCompletions:this.clearCompletions.bind(this),getCompletion:this.getCompletion.bind(this),getCompletions:this.getCompletions.bind(this),addPersonalization:this.addPersonalization.bind(this),deletePersonalization:this.deletePersonalization.bind(this),clearPersonalization:this.clearPersonalization.bind(this),getPersonalization:this.getPersonalization.bind(this),addRAG:this.addRAG.bind(this),deleteRAG:this.deleteRAG.bind(this),updateRAG:this.updateRAG.bind(this),clearRAGs:this.clearRAGs.bind(this),getRAG:this.getRAG.bind(this),getRAGs:this.getRAGs.bind(this)};chats={getMessage:this.getMessage.bind(this)}},ha=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 m({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=g({level:"silent",enabled:!1});db;socket;events=new p;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{h(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await Fs.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await(e=>{const{type:t,connection:s}=e.database;if("sqlite"===t){const e=s.url||"./db/zaileys.db",t=M.resolve(e);return v(M.dirname(t),{recursive:!0}),_(t,"",{flag:"a"}),new w({dialect:new b({database:new y(t)})})}const a=new S(s.url),n=a.protocol.replace(":","");if("mysql"===t)return new w({dialect:new x({pool:I.createPool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"3306",10)})})});if("postgresql"===t)return new w({dialect:new k({pool:new T({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${n}`)})(this.options),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:n,saveCreds:i}=await As(this.db,this.chatId,this.options);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const r=await(async(e,t,s)=>({bind:a=>{const n=new Ms(a,e,t);a?.ev.on("connection.update",(async e=>{await n.connection(e)})),a?.ev.on("call",(async t=>{for(const s of t){const t=await n.calls(s);e.options.ignoreMe&&t&&await Ns(e.options.webhooks?.url,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:a})=>{for(const i of a){if(!i.message)return;if(i.message?.protocolMessage)return;const a=await n.messages(i);e.options.ignoreMe&&a&&await Ns(e.options.webhooks?.url,a),await t.insertInto("messages").values({session:s,id:i.key.id,value:JSON.stringify(i)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(i)}))).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)})),a?.ev.on("idle-webhooks",(async e=>{await n.webhooks(e)}))}}))(this,this.db,this.chatId);this.stopSpinner("store",!0,"Store adapter ready");const{version:o}=await e();if(this.socket=t({version:o,logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new m,mediaCache:new m({stdTTL:60}),userDevicesCache:new m,cachedGroupMetadata:async e=>this.cache.get(e),printQRInTerminal:!1,browser:a.ubuntu("qr"===this.options.authType?"Zaileys Library":"Chrome"),auth:{creds:n.creds,keys:s(n.keys,this.logger)},getMessage:async e=>{const t=await(this.db?.selectFrom("messages").select("value").where("id","=",e.id).executeTakeFirst());return z(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 on 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 pa({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",i),r.bind(this.socket),this.startSpinner("webhooks","Starting webhooks server..."),Ss(this,this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=f(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)}},ma=K.object({callId:K.string(),roomId:K.string(),callerId:K.string(),date:K.date(),offline:K.boolean(),status:K.enum(["accept","offer","reject","ringing","terminate","timeout"]),isVideo:K.boolean(),isGroup:K.boolean()});K.object({status:K.enum(["connecting","open","close"])}),K.enum(["connection","messages","calls","webhooks"]);export{Os as AdapterDatabaseType,ma as CallsParserBaseType,Es as CitationType,ha as Client,js as ClientClassesBaseType,Fs as ClientClassesType,Ws as ContactWorkerBaseType,Bs as ContactWorkerOptionsType,na as DeleteWorkerBaseType,aa as EditWorkerBaseType,sa as EditWorkerOptionsType,Gs as LocationWorkerBaseType,Ks as LocationWorkerOptionsType,Ds as MediaInputWorkerType,xs as MessagesDeviceEnumType,bs as MessagesEnumType,_s as MessagesMediaType,ks as MessagesParserBaseType,Cs as MessagesParserType,ws as MessagesVerifiedPlatformType,oa as MuteWorkerBaseType,ra as MuteWorkerOptionsType,Xs as PinWorkerBaseType,Qs as PinWorkerOptionsType,ta as PollWorkerBaseType,ea as PollWorkerOptionsType,ua as PresenceWorkerBaseType,la as PresenceWorkerOptionsType,ca as ProfileWorkerBaseOutputType,da as ProfileWorkerBaseType,Hs as ReactionWorkerBaseType,Ys as ReactionWorkerOptionsType,ia as RejectCallWorkerBaseType,Vs as TextWorkerBaseType,Js as TextWorkerOptionsType,Us as addRAGType,$s as llmMessagesTable,qs as llmPersonalizationTable,zs as llmRAGTable};
|
|
1
|
+
import makeWASocket, { BufferJSON, delay, fetchLatestBaileysVersion, makeCacheableSignalKeyStore, DisconnectReason, jidNormalizedUser, initAuthCreds, getContentType, getDevice, downloadMediaMessage } from 'baileys';
|
|
2
|
+
import EventEmitter from 'events';
|
|
3
|
+
import { createSpinner } from 'nanospinner';
|
|
4
|
+
import NodeCache2 from 'node-cache';
|
|
5
|
+
import pino from 'pino';
|
|
6
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, unlinkSync } from 'fs';
|
|
7
|
+
import lowdb from 'lowdb';
|
|
8
|
+
import FileSync from 'lowdb/adapters/FileSync';
|
|
9
|
+
import { dirname } from 'path';
|
|
10
|
+
import chalk from 'chalk';
|
|
11
|
+
import _2 from 'lodash';
|
|
12
|
+
import z2, { z } from 'zod/v4';
|
|
13
|
+
import figlet from 'figlet';
|
|
14
|
+
import QRCode from 'qrcode';
|
|
15
|
+
import { z as z$1 } from 'zod';
|
|
16
|
+
|
|
17
|
+
// src/classes/Client.ts
|
|
18
|
+
var sendError = (text) => new Error(chalk.red(text));
|
|
19
|
+
var toJson = (object) => {
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(object);
|
|
22
|
+
} catch {
|
|
23
|
+
return _2.attempt(() => JSON.parse(JSON.stringify(object) || "{}"));
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var toString = (object) => {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.stringify(object);
|
|
29
|
+
} catch {
|
|
30
|
+
const result = _2.attempt(() => JSON.stringify(toJson(object) || "{}"));
|
|
31
|
+
return _2.isError(result) ? "{}" : result;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var shuffleString = (str) => {
|
|
35
|
+
return _2.shuffle([...str]).join("");
|
|
36
|
+
};
|
|
37
|
+
var tryAgain = async (fn) => {
|
|
38
|
+
const RETRY_DELAY = 200;
|
|
39
|
+
const MAX_RETRIES = 10;
|
|
40
|
+
for (let x = 0; x < MAX_RETRIES; x++) {
|
|
41
|
+
try {
|
|
42
|
+
return await fn();
|
|
43
|
+
} catch (_e) {
|
|
44
|
+
await new Promise((r) => setTimeout(r, RETRY_DELAY));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
throw sendError("Max retries reached");
|
|
48
|
+
};
|
|
49
|
+
var findWord = (text = "", word = "") => {
|
|
50
|
+
if (!text) return null;
|
|
51
|
+
return _2.includes(text.toLowerCase(), word.toLowerCase());
|
|
52
|
+
};
|
|
53
|
+
var normalizeText = (text = "") => {
|
|
54
|
+
if (!text) return null;
|
|
55
|
+
return _2.replace(text, /\u202E([\s\S]*?)\u202C/g, (_e, segmen) => {
|
|
56
|
+
const arr = _2.toArray(segmen);
|
|
57
|
+
const reversed = _2.reverse(_2.clone(arr));
|
|
58
|
+
return _2.join(reversed, "");
|
|
59
|
+
}).replace(/[\u202A-\u202E\u202C]/g, "");
|
|
60
|
+
};
|
|
61
|
+
var extractJids = (text = "") => {
|
|
62
|
+
if (!text) return [];
|
|
63
|
+
const ids = /* @__PURE__ */ new Set();
|
|
64
|
+
for (const match of text.matchAll(/@(\d+)/g)) {
|
|
65
|
+
ids.add(match[1]);
|
|
66
|
+
}
|
|
67
|
+
return _2.flatMap([...ids], (id) => [`${id}@s.whatsapp.net`, `${id}@g.us`]);
|
|
68
|
+
};
|
|
69
|
+
var extractUrls = (text = "") => {
|
|
70
|
+
if (!text) return [];
|
|
71
|
+
const regex = /https?:\/\/(?:[-\w.])+(?:\.[a-zA-Z]{2,})+(?:\/[^\s<>"']*)?/g;
|
|
72
|
+
return _2.castArray(text.match(regex) || []);
|
|
73
|
+
};
|
|
74
|
+
var getMentions = (text = "") => {
|
|
75
|
+
if (!text) return [];
|
|
76
|
+
const ids = /* @__PURE__ */ new Set();
|
|
77
|
+
for (const match of text.matchAll(/@(\d+)/g)) {
|
|
78
|
+
ids.add(match[1]);
|
|
79
|
+
}
|
|
80
|
+
return _2.toArray(ids);
|
|
81
|
+
};
|
|
82
|
+
var CHUNK_SIZE = 1e3;
|
|
83
|
+
var JsonDB = class {
|
|
84
|
+
session = "zaileys-sessions";
|
|
85
|
+
db;
|
|
86
|
+
storeDir;
|
|
87
|
+
async initialize(session) {
|
|
88
|
+
this.session = session;
|
|
89
|
+
const authPath = `sessions/${this.session}/auth.json`;
|
|
90
|
+
this.storeDir = `sessions/${this.session}/stores`;
|
|
91
|
+
const dirAuth = dirname(authPath);
|
|
92
|
+
if (!existsSync(dirAuth)) mkdirSync(dirAuth, { recursive: true });
|
|
93
|
+
if (!existsSync(this.storeDir)) mkdirSync(this.storeDir, { recursive: true });
|
|
94
|
+
const adapter = new FileSync(authPath);
|
|
95
|
+
this.db = lowdb(adapter);
|
|
96
|
+
this.db.defaults([]).write();
|
|
97
|
+
}
|
|
98
|
+
tryRecoverRaw(raw) {
|
|
99
|
+
const s = raw.trim();
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(s);
|
|
102
|
+
} catch (_error) {
|
|
103
|
+
try {
|
|
104
|
+
const a = s.indexOf("[");
|
|
105
|
+
const b = s.lastIndexOf("]");
|
|
106
|
+
if (a !== -1 && b !== -1 && b > a) {
|
|
107
|
+
const sub = s.slice(a, b + 1);
|
|
108
|
+
return JSON.parse(sub);
|
|
109
|
+
}
|
|
110
|
+
} catch (_error2) {
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const wrapped = `[${s.replace(/}\s*{/g, "},{")}]`;
|
|
114
|
+
return JSON.parse(wrapped);
|
|
115
|
+
} catch (_error2) {
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const lines = _2.filter(_2.map(s.split(/\\r?\\n/), (l) => l.trim()), Boolean);
|
|
119
|
+
const parsedResults = _2.map(lines, (l) => {
|
|
120
|
+
try {
|
|
121
|
+
return JSON.parse(l);
|
|
122
|
+
} catch (_error2) {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
const parsed = _2.filter(parsedResults, (item) => item !== null);
|
|
127
|
+
if (parsed.length) return parsed;
|
|
128
|
+
} catch (_error2) {
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
async chunks(key) {
|
|
134
|
+
const files = _2.filter(readdirSync(this.storeDir), (f) => _2.startsWith(f, `${key}-`) && _2.endsWith(f, ".json")).sort();
|
|
135
|
+
const result = [];
|
|
136
|
+
for (const file of files) {
|
|
137
|
+
const full = `${this.storeDir}/${file}`;
|
|
138
|
+
const adapter = new FileSync(full);
|
|
139
|
+
const db = lowdb(adapter);
|
|
140
|
+
try {
|
|
141
|
+
db.defaults([]).write();
|
|
142
|
+
result.push(...toJson(db.value()));
|
|
143
|
+
} catch {
|
|
144
|
+
let raw = "";
|
|
145
|
+
try {
|
|
146
|
+
raw = readFileSync(full, "utf8");
|
|
147
|
+
} catch (_error) {
|
|
148
|
+
raw = "";
|
|
149
|
+
}
|
|
150
|
+
const recovered = raw ? this.tryRecoverRaw(raw) : null;
|
|
151
|
+
if (recovered) {
|
|
152
|
+
db.setState(Array.isArray(recovered) ? recovered : [recovered]).write();
|
|
153
|
+
result.push(...toJson(db.value()));
|
|
154
|
+
} else {
|
|
155
|
+
const corrupt = `${full}.corrupt.${Date.now()}`;
|
|
156
|
+
try {
|
|
157
|
+
renameSync(full, corrupt);
|
|
158
|
+
} catch (_renameErr) {
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
writeFileSync(full, "[]", "utf8");
|
|
162
|
+
} catch (_writeFileErr) {
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
async writeChunks(key, items) {
|
|
170
|
+
_2.forEach(
|
|
171
|
+
_2.filter(readdirSync(this.storeDir), (f) => _2.startsWith(f, `${key}-`) && _2.endsWith(f, ".json")),
|
|
172
|
+
(f) => unlinkSync(`${this.storeDir}/${f}`)
|
|
173
|
+
);
|
|
174
|
+
let index = 0;
|
|
175
|
+
for (let i = 0; i < items.length; i += CHUNK_SIZE) {
|
|
176
|
+
const chunk = items.slice(i, i + CHUNK_SIZE);
|
|
177
|
+
const file = `${this.storeDir}/${key}-${index}.json`;
|
|
178
|
+
const adapter = new FileSync(file);
|
|
179
|
+
const db = lowdb(adapter);
|
|
180
|
+
db.setState(chunk).write();
|
|
181
|
+
try {
|
|
182
|
+
db.write();
|
|
183
|
+
} catch (err) {
|
|
184
|
+
if (err?.code === "ENOENT") {
|
|
185
|
+
try {
|
|
186
|
+
renameSync(`${file}.tmp`, file);
|
|
187
|
+
} catch (_renameErr) {
|
|
188
|
+
try {
|
|
189
|
+
db.write();
|
|
190
|
+
} catch (_writeErr) {
|
|
191
|
+
try {
|
|
192
|
+
writeFileSync(file, JSON.stringify(chunk), "utf8");
|
|
193
|
+
} catch (_writeFileErr) {
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} else {
|
|
198
|
+
throw err;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
index++;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
store(key) {
|
|
205
|
+
return {
|
|
206
|
+
read: async (id) => {
|
|
207
|
+
const list = await this.chunks(key);
|
|
208
|
+
const row = _2.find(list, (i) => i.id === id);
|
|
209
|
+
return row ? JSON.parse(row.value) : null;
|
|
210
|
+
},
|
|
211
|
+
write: async (obj) => {
|
|
212
|
+
const list = await this.chunks(key);
|
|
213
|
+
const id = obj.key && typeof obj.key === "object" && "id" in obj.key ? obj.key.id : obj.id;
|
|
214
|
+
const serialized = JSON.stringify(obj);
|
|
215
|
+
const idx = list.findIndex((i) => i.id === id);
|
|
216
|
+
if (idx !== -1) list[idx].value = serialized;
|
|
217
|
+
else list.push({ id, value: serialized });
|
|
218
|
+
await this.writeChunks(key, list);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
async upsert(id, value) {
|
|
223
|
+
const replacer = JSON.stringify(value, BufferJSON.replacer);
|
|
224
|
+
const dbValue = this.db.value();
|
|
225
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
226
|
+
const idx = _2.findIndex(data, (i) => i.id === id);
|
|
227
|
+
if (idx !== -1) {
|
|
228
|
+
data[idx].value = replacer;
|
|
229
|
+
} else {
|
|
230
|
+
data.push({ id, value: replacer });
|
|
231
|
+
}
|
|
232
|
+
this.db.setState(data).write();
|
|
233
|
+
}
|
|
234
|
+
async read(id) {
|
|
235
|
+
const dbValue = this.db.value();
|
|
236
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
237
|
+
const row = _2.find(data, (i) => i.id === id);
|
|
238
|
+
if (!row || !row.value) return null;
|
|
239
|
+
const creds = typeof row.value === "object" ? toString(row.value) : row.value;
|
|
240
|
+
return JSON.parse(creds, BufferJSON.reviver);
|
|
241
|
+
}
|
|
242
|
+
async remove(id) {
|
|
243
|
+
const dbValue = this.db.value();
|
|
244
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
245
|
+
const filtered = _2.filter(data, (i) => i.id !== id);
|
|
246
|
+
this.db.setState(filtered).write();
|
|
247
|
+
}
|
|
248
|
+
async clear() {
|
|
249
|
+
const dbValue = this.db.value();
|
|
250
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
251
|
+
const filtered = _2.filter(data, (i) => i.id === "creds");
|
|
252
|
+
this.db.setState(filtered).write();
|
|
253
|
+
}
|
|
254
|
+
async delete() {
|
|
255
|
+
this.db.setState([]);
|
|
256
|
+
await this.db.write();
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
// src/utils/decrypt.ts
|
|
261
|
+
var allocate = (str) => {
|
|
262
|
+
let n = 0;
|
|
263
|
+
let p = str.length;
|
|
264
|
+
if (!p) return new Uint8Array(1);
|
|
265
|
+
while (--p % 4 > 1 && str.charAt(p) === "=") ++n;
|
|
266
|
+
return new Uint8Array(Math.ceil(str.length * 3) / 4 - n).fill(0);
|
|
267
|
+
};
|
|
268
|
+
var parseTimestamp = (timestamp) => {
|
|
269
|
+
if (typeof timestamp === "string") return parseInt(timestamp, 10);
|
|
270
|
+
if (typeof timestamp === "number") return timestamp;
|
|
271
|
+
return timestamp;
|
|
272
|
+
};
|
|
273
|
+
var fromObject = (args) => {
|
|
274
|
+
const fingerprint = args.fingerprint || {};
|
|
275
|
+
const f = {
|
|
276
|
+
...fingerprint,
|
|
277
|
+
deviceIndexes: Array.isArray(fingerprint.deviceIndexes) ? fingerprint.deviceIndexes : []
|
|
278
|
+
};
|
|
279
|
+
const message = {
|
|
280
|
+
keyData: Array.isArray(args.keyData) ? args.keyData : new Uint8Array(),
|
|
281
|
+
fingerprint: {
|
|
282
|
+
rawId: fingerprint.rawId || 0,
|
|
283
|
+
currentIndex: fingerprint.rawId || 0,
|
|
284
|
+
deviceIndexes: f.deviceIndexes
|
|
285
|
+
},
|
|
286
|
+
timestamp: parseTimestamp(args.timestamp)
|
|
287
|
+
};
|
|
288
|
+
if (typeof args.keyData === "string") {
|
|
289
|
+
message.keyData = allocate(args.keyData);
|
|
290
|
+
}
|
|
291
|
+
return message;
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
// src/modules/store.ts
|
|
295
|
+
var StoreHandler = async (db) => {
|
|
296
|
+
return {
|
|
297
|
+
bind: (client) => {
|
|
298
|
+
client?.socket?.ev.on("messaging-history.set", async (update) => {
|
|
299
|
+
const { chats, contacts, messages } = update;
|
|
300
|
+
for (const chat of chats) {
|
|
301
|
+
await db.store("chats").write(chat);
|
|
302
|
+
}
|
|
303
|
+
for (const contact of contacts) {
|
|
304
|
+
await db.store("contacts").write(contact);
|
|
305
|
+
}
|
|
306
|
+
for (const message of messages) {
|
|
307
|
+
if (!message.message) return;
|
|
308
|
+
if (message.message?.protocolMessage) return;
|
|
309
|
+
await db.store("messages").write(message);
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
client?.socket?.ev.on("messages.upsert", async ({ messages }) => {
|
|
313
|
+
for (const message of messages) {
|
|
314
|
+
await db.store("messages").write(message);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
client?.socket?.ev.on("chats.upsert", async (chats) => {
|
|
318
|
+
for (const chat of chats) {
|
|
319
|
+
await db.store("chats").write(chat);
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
client?.socket?.ev.on("contacts.upsert", async (contacts) => {
|
|
323
|
+
for (const contact of contacts) {
|
|
324
|
+
await db.store("contacts").write(contact);
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
client?.socket?.ev.on("groups.update", async ([event]) => {
|
|
328
|
+
if (event.id) {
|
|
329
|
+
const metadata = await client?.socket?.groupMetadata(event.id);
|
|
330
|
+
client.cache.set(event.id, metadata);
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
client?.socket?.ev.on("group-participants.update", async (event) => {
|
|
334
|
+
const metadata = await client?.socket?.groupMetadata(event.id);
|
|
335
|
+
client.cache.set(event.id, metadata);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// src/modules/auth.ts
|
|
342
|
+
var AuthHandler = async (db) => {
|
|
343
|
+
const creds = await tryAgain(() => db.read("creds")) || initAuthCreds();
|
|
344
|
+
const store = await StoreHandler(db);
|
|
345
|
+
return {
|
|
346
|
+
db,
|
|
347
|
+
store,
|
|
348
|
+
state: {
|
|
349
|
+
creds,
|
|
350
|
+
keys: {
|
|
351
|
+
get: async (type, ids) => {
|
|
352
|
+
const data = {};
|
|
353
|
+
for (const id of ids) {
|
|
354
|
+
let value = await tryAgain(() => db.read(`${type}-${id}`));
|
|
355
|
+
if (type === "app-state-sync-key" && value) {
|
|
356
|
+
value = fromObject(value);
|
|
357
|
+
}
|
|
358
|
+
if (value !== null && value !== void 0) {
|
|
359
|
+
data[id] = value;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return data;
|
|
363
|
+
},
|
|
364
|
+
set: async (data) => {
|
|
365
|
+
for (const category in data) {
|
|
366
|
+
for (const id in data[category]) {
|
|
367
|
+
const value = data[category][id];
|
|
368
|
+
const name = `${category}-${id}`;
|
|
369
|
+
if (value) {
|
|
370
|
+
await tryAgain(() => db.upsert(name, value));
|
|
371
|
+
} else {
|
|
372
|
+
await tryAgain(() => db.remove(name));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
},
|
|
379
|
+
clear: async () => {
|
|
380
|
+
await tryAgain(() => db.clear());
|
|
381
|
+
},
|
|
382
|
+
saveCreds: async () => {
|
|
383
|
+
await tryAgain(() => db.upsert("creds", creds));
|
|
384
|
+
},
|
|
385
|
+
removeCreds: async () => {
|
|
386
|
+
await tryAgain(() => db.delete());
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
var PluginsHandler = (necessary, props) => {
|
|
391
|
+
const plugins = _2.find(props.plugins, (x) => x?.necessary == necessary);
|
|
392
|
+
return plugins;
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
// src/modules/database.ts
|
|
396
|
+
var CredsHandler = async (props) => {
|
|
397
|
+
const db = PluginsHandler("database", props) || new JsonDB();
|
|
398
|
+
await db.initialize(props.session || "default");
|
|
399
|
+
return await AuthHandler(db);
|
|
400
|
+
};
|
|
401
|
+
var defaultBoolean = (state) => z.boolean().default(state).optional();
|
|
402
|
+
var AdsReplyType = z.custom();
|
|
403
|
+
|
|
404
|
+
// src/types/classes/Client.ts
|
|
405
|
+
var PluginsType = z2.array(
|
|
406
|
+
z2.object({
|
|
407
|
+
necessary: z2.string()
|
|
408
|
+
}).passthrough()
|
|
409
|
+
).optional();
|
|
410
|
+
var LimiterType = z2.object({
|
|
411
|
+
durationMs: z2.number(),
|
|
412
|
+
maxMessages: z2.number()
|
|
413
|
+
}).optional();
|
|
414
|
+
var CitationType = z2.partialRecord(z2.string(), z2.number().array()).optional();
|
|
415
|
+
var FakeReplyType = z2.object({
|
|
416
|
+
provider: z2.enum(["whatsapp", "meta", "chatgpt", "copilot", "instagram", "tiktok"])
|
|
417
|
+
}).optional();
|
|
418
|
+
var ClientBaseType = z2.object({
|
|
419
|
+
session: z2.string().default("zaileys-sessions").optional(),
|
|
420
|
+
prefix: z2.string().optional(),
|
|
421
|
+
ignoreMe: defaultBoolean(true),
|
|
422
|
+
showLogs: defaultBoolean(true),
|
|
423
|
+
autoMentions: defaultBoolean(true),
|
|
424
|
+
autoOnline: defaultBoolean(true),
|
|
425
|
+
autoRead: defaultBoolean(true),
|
|
426
|
+
autoPresence: defaultBoolean(true),
|
|
427
|
+
autoRejectCall: defaultBoolean(true),
|
|
428
|
+
plugins: PluginsType,
|
|
429
|
+
limiter: LimiterType,
|
|
430
|
+
citation: CitationType,
|
|
431
|
+
fakeReply: FakeReplyType
|
|
432
|
+
});
|
|
433
|
+
var ClientAuthPairingType = z2.object({
|
|
434
|
+
authType: z2.literal("pairing"),
|
|
435
|
+
phoneNumber: z2.number()
|
|
436
|
+
});
|
|
437
|
+
var ClientAuthQRType = z2.object({
|
|
438
|
+
authType: z2.literal("qr")
|
|
439
|
+
});
|
|
440
|
+
var ClientOptionsType = z2.discriminatedUnion("authType", [ClientAuthPairingType.extend(ClientBaseType.shape), ClientAuthQRType.extend(ClientBaseType.shape)]);
|
|
441
|
+
var EventEnumType = z2.enum(["connection", "messages", "calls", "webhooks"]);
|
|
442
|
+
var displayBanner = async (text = "ZAILEYS") => {
|
|
443
|
+
figlet(text, async (err, data) => {
|
|
444
|
+
if (err) return;
|
|
445
|
+
console.log(chalk.gray.italic(data));
|
|
446
|
+
});
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// src/extractor/calls.ts
|
|
450
|
+
var CallsExtractor = async (client, caller) => {
|
|
451
|
+
const payload = {};
|
|
452
|
+
payload.callId = caller.id;
|
|
453
|
+
payload.roomId = caller.chatId;
|
|
454
|
+
payload.callerId = caller.from;
|
|
455
|
+
payload.date = caller.date;
|
|
456
|
+
payload.offline = caller.offline;
|
|
457
|
+
payload.status = caller.status;
|
|
458
|
+
payload.isVideo = !!caller.isVideo;
|
|
459
|
+
payload.isGroup = !!caller.isGroup;
|
|
460
|
+
return payload;
|
|
461
|
+
};
|
|
462
|
+
var MessagesMediaType = {
|
|
463
|
+
text: "text",
|
|
464
|
+
conversation: "text",
|
|
465
|
+
imageMessage: "image",
|
|
466
|
+
contactMessage: "contact",
|
|
467
|
+
locationMessage: "location",
|
|
468
|
+
documentMessage: "document",
|
|
469
|
+
audioMessage: "audio",
|
|
470
|
+
videoMessage: "video",
|
|
471
|
+
protocolMessage: "protocol",
|
|
472
|
+
contactsArrayMessage: "contacts",
|
|
473
|
+
highlyStructuredMessage: "highlyStructured",
|
|
474
|
+
sendPaymentMessage: "sendPayment",
|
|
475
|
+
liveLocationMessage: "location",
|
|
476
|
+
requestPaymentMessage: "requestPayment",
|
|
477
|
+
declinePaymentRequestMessage: "declinePaymentRequest",
|
|
478
|
+
cancelPaymentRequestMessage: "cancelPaymentRequest",
|
|
479
|
+
templateMessage: "template",
|
|
480
|
+
stickerMessage: "sticker",
|
|
481
|
+
groupInviteMessage: "groupInvite",
|
|
482
|
+
templateButtonReplyMessage: "buttons",
|
|
483
|
+
productMessage: "product",
|
|
484
|
+
deviceSentMessage: "deviceSent",
|
|
485
|
+
listMessage: "list",
|
|
486
|
+
viewOnceMessage: "viewOnce",
|
|
487
|
+
orderMessage: "order",
|
|
488
|
+
listResponseMessage: "list",
|
|
489
|
+
ephemeralMessage: "ephemeral",
|
|
490
|
+
invoiceMessage: "invoice",
|
|
491
|
+
buttonsMessage: "buttons",
|
|
492
|
+
buttonsResponseMessage: "buttons",
|
|
493
|
+
paymentInviteMessage: "paymentInvite",
|
|
494
|
+
interactiveMessage: "interactive",
|
|
495
|
+
reactionMessage: "reaction",
|
|
496
|
+
stickerSyncRmrMessage: "sticker",
|
|
497
|
+
interactiveResponseMessage: "interactiveResponse",
|
|
498
|
+
pollCreationMessage: "pollCreation",
|
|
499
|
+
pollUpdateMessage: "pollUpdate",
|
|
500
|
+
keepInChatMessage: "keepInChat",
|
|
501
|
+
documentWithCaptionMessage: "document",
|
|
502
|
+
requestPhoneNumberMessage: "requestPhoneNumber",
|
|
503
|
+
viewOnceMessageV2: "viewOnce",
|
|
504
|
+
encReactionMessage: "reaction",
|
|
505
|
+
editedMessage: "text",
|
|
506
|
+
viewOnceMessageV2Extension: "viewOnce",
|
|
507
|
+
pollCreationMessageV2: "pollCreation",
|
|
508
|
+
scheduledCallCreationMessage: "scheduledCallCreation",
|
|
509
|
+
groupMentionedMessage: "groupMentioned",
|
|
510
|
+
pinInChatMessage: "pinInChat",
|
|
511
|
+
pollCreationMessageV3: "pollCreation",
|
|
512
|
+
scheduledCallEditMessage: "scheduledCallEdit",
|
|
513
|
+
ptvMessage: "ptv",
|
|
514
|
+
botInvokeMessage: "botInvoke",
|
|
515
|
+
callLogMesssage: "callLog",
|
|
516
|
+
encCommentMessage: "encComment",
|
|
517
|
+
bcallMessage: "bcall",
|
|
518
|
+
lottieStickerMessage: "lottieSticker",
|
|
519
|
+
eventMessage: "event",
|
|
520
|
+
commentMessage: "comment",
|
|
521
|
+
newsletterAdminInviteMessage: "text",
|
|
522
|
+
extendedTextMessageWithParentKey: "text",
|
|
523
|
+
extendedTextMessage: "text",
|
|
524
|
+
placeholderMessage: "placeholder",
|
|
525
|
+
encEventUpdateMessage: "encEventUpdate"
|
|
526
|
+
};
|
|
527
|
+
var MessagesVerifiedPlatformType = {
|
|
528
|
+
whatsapp: "0@s.whatsapp.net",
|
|
529
|
+
meta: "13135550002@s.whatsapp.net",
|
|
530
|
+
chatgpt: "18002428478@s.whatsapp.net",
|
|
531
|
+
copilot: "18772241042@s.whatsapp.net",
|
|
532
|
+
instagram: "447723442971@s.whatsapp.net",
|
|
533
|
+
tiktok: "6285574670498@s.whatsapp.net"
|
|
534
|
+
};
|
|
535
|
+
var MessagesEnumType = z$1.enum([
|
|
536
|
+
"text",
|
|
537
|
+
"image",
|
|
538
|
+
"contact",
|
|
539
|
+
"location",
|
|
540
|
+
"document",
|
|
541
|
+
"audio",
|
|
542
|
+
"video",
|
|
543
|
+
"protocol",
|
|
544
|
+
"contacts",
|
|
545
|
+
"highlyStructured",
|
|
546
|
+
"sendPayment",
|
|
547
|
+
"requestPayment",
|
|
548
|
+
"declinePaymentRequest",
|
|
549
|
+
"cancelPaymentRequest",
|
|
550
|
+
"template",
|
|
551
|
+
"sticker",
|
|
552
|
+
"groupInvite",
|
|
553
|
+
"product",
|
|
554
|
+
"deviceSent",
|
|
555
|
+
"list",
|
|
556
|
+
"viewOnce",
|
|
557
|
+
"order",
|
|
558
|
+
"ephemeral",
|
|
559
|
+
"invoice",
|
|
560
|
+
"buttons",
|
|
561
|
+
"paymentInvite",
|
|
562
|
+
"interactive",
|
|
563
|
+
"reaction",
|
|
564
|
+
"sticker",
|
|
565
|
+
"interactiveResponse",
|
|
566
|
+
"pollCreation",
|
|
567
|
+
"pollUpdate",
|
|
568
|
+
"keepInChat",
|
|
569
|
+
"document",
|
|
570
|
+
"requestPhoneNumber",
|
|
571
|
+
"viewOnce",
|
|
572
|
+
"reaction",
|
|
573
|
+
"text",
|
|
574
|
+
"viewOnce",
|
|
575
|
+
"pollCreation",
|
|
576
|
+
"scheduledCallCreation",
|
|
577
|
+
"groupMentioned",
|
|
578
|
+
"pinInChat",
|
|
579
|
+
"pollCreation",
|
|
580
|
+
"scheduledCallEdit",
|
|
581
|
+
"ptv",
|
|
582
|
+
"botInvoke",
|
|
583
|
+
"callLog",
|
|
584
|
+
"encComment",
|
|
585
|
+
"bcall",
|
|
586
|
+
"lottieSticker",
|
|
587
|
+
"event",
|
|
588
|
+
"comment",
|
|
589
|
+
"placeholder",
|
|
590
|
+
"encEventUpdate"
|
|
591
|
+
]);
|
|
592
|
+
var MessagesDeviceEnumType = z$1.enum([
|
|
593
|
+
"unknown",
|
|
594
|
+
"android",
|
|
595
|
+
"ios",
|
|
596
|
+
"desktop",
|
|
597
|
+
"web"
|
|
598
|
+
]);
|
|
599
|
+
var ExtractorMessagesType = z$1.object({
|
|
600
|
+
chatId: z$1.string(),
|
|
601
|
+
channelId: z$1.string(),
|
|
602
|
+
uniqueId: z$1.string(),
|
|
603
|
+
receiverId: z$1.string(),
|
|
604
|
+
receiverName: z$1.string(),
|
|
605
|
+
roomId: z$1.string(),
|
|
606
|
+
roomName: z$1.string(),
|
|
607
|
+
senderLid: z$1.string(),
|
|
608
|
+
senderId: z$1.string(),
|
|
609
|
+
senderName: z$1.string(),
|
|
610
|
+
senderDevice: MessagesDeviceEnumType,
|
|
611
|
+
chatType: MessagesEnumType,
|
|
612
|
+
timestamp: z$1.number(),
|
|
613
|
+
text: z$1.string().nullable(),
|
|
614
|
+
mentions: z$1.string().array(),
|
|
615
|
+
links: z$1.string().array(),
|
|
616
|
+
isPrefix: z$1.boolean(),
|
|
617
|
+
isSpam: z$1.boolean(),
|
|
618
|
+
isFromMe: z$1.boolean(),
|
|
619
|
+
isTagMe: z$1.boolean(),
|
|
620
|
+
isGroup: z$1.boolean(),
|
|
621
|
+
isStory: z$1.boolean(),
|
|
622
|
+
isViewOnce: z$1.boolean(),
|
|
623
|
+
isEdited: z$1.boolean(),
|
|
624
|
+
isDeleted: z$1.boolean(),
|
|
625
|
+
isPinned: z$1.boolean(),
|
|
626
|
+
isUnPinned: z$1.boolean(),
|
|
627
|
+
isChannel: z$1.boolean(),
|
|
628
|
+
isBroadcast: z$1.boolean(),
|
|
629
|
+
isEphemeral: z$1.boolean(),
|
|
630
|
+
isForwarded: z$1.boolean(),
|
|
631
|
+
citation: z$1.record(z$1.string(), z$1.boolean()).nullable(),
|
|
632
|
+
media: z$1.object({
|
|
633
|
+
buffer: z$1.function(),
|
|
634
|
+
stream: z$1.function()
|
|
635
|
+
}).loose().nullable(),
|
|
636
|
+
message: z$1.function({
|
|
637
|
+
input: [],
|
|
638
|
+
output: z$1.record(z$1.string(), z$1.any())
|
|
639
|
+
}),
|
|
640
|
+
get replied() {
|
|
641
|
+
return ExtractorMessagesType.nullable();
|
|
642
|
+
}
|
|
643
|
+
});
|
|
644
|
+
var limiterCache = new NodeCache2({ stdTTL: 60 * 60 });
|
|
645
|
+
var LimiterHandler = async (key, max, ms) => {
|
|
646
|
+
try {
|
|
647
|
+
if (max <= 0) {
|
|
648
|
+
return false;
|
|
649
|
+
}
|
|
650
|
+
const state = limiterCache.get(key);
|
|
651
|
+
const now = Date.now();
|
|
652
|
+
if (!state || now - state.firstRequestTime > ms) {
|
|
653
|
+
const newState2 = {
|
|
654
|
+
count: 1,
|
|
655
|
+
firstRequestTime: now
|
|
656
|
+
};
|
|
657
|
+
limiterCache.set(key, newState2, Math.ceil(ms / 1e3) + 10);
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
660
|
+
const newState = {
|
|
661
|
+
count: state.count + 1,
|
|
662
|
+
firstRequestTime: state.firstRequestTime
|
|
663
|
+
};
|
|
664
|
+
limiterCache.set(key, newState, Math.ceil((ms - (now - state.firstRequestTime)) / 1e3) + 10);
|
|
665
|
+
if (newState.count > max) {
|
|
666
|
+
return true;
|
|
667
|
+
}
|
|
668
|
+
return false;
|
|
669
|
+
} catch (err) {
|
|
670
|
+
console.error("Error detecting spam:", err);
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
// src/extractor/messages.ts
|
|
676
|
+
var MessagesExtractor = async (client, message) => {
|
|
677
|
+
let MAX_REPLIES = 0;
|
|
678
|
+
const CLONE = message;
|
|
679
|
+
const extract = async (obj, isReplied, isExtract) => {
|
|
680
|
+
let msg = toJson(obj);
|
|
681
|
+
if (!msg.message || !msg?.key?.id) {
|
|
682
|
+
return null;
|
|
683
|
+
}
|
|
684
|
+
if (msg?.messageStubType || !!msg?.messageStubParameters || msg?.message?.botInvokeMessage || msg.message?.protocolMessage?.peerDataOperationRequestResponseMessage) {
|
|
685
|
+
return null;
|
|
686
|
+
}
|
|
687
|
+
if (msg?.key?.fromMe && !msg?.participant && msg?.key?.remoteJid != "status@broadcast" && client.props?.ignoreMe && !MAX_REPLIES && true) {
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
const pinId = msg?.message?.pinInChatMessage?.key?.id;
|
|
691
|
+
const isPinned = msg?.message?.pinInChatMessage?.type == 1;
|
|
692
|
+
const isUnPinned = msg?.message?.pinInChatMessage?.type == 2;
|
|
693
|
+
if (pinId && client.db) {
|
|
694
|
+
const read = await client.db.store("messages").read(pinId);
|
|
695
|
+
msg = read;
|
|
696
|
+
}
|
|
697
|
+
const protocolId = !msg?.message?.protocolMessage?.editedMessage && msg?.message?.protocolMessage?.key?.id;
|
|
698
|
+
const isDeleted = !!protocolId;
|
|
699
|
+
if (protocolId && client.db) {
|
|
700
|
+
const read = await client.db.store("messages").read(protocolId);
|
|
701
|
+
msg = read;
|
|
702
|
+
}
|
|
703
|
+
const edited = msg?.message?.protocolMessage?.editedMessage || msg?.message?.editedMessage;
|
|
704
|
+
if (edited) {
|
|
705
|
+
const id = edited?.message?.protocolMessage?.key?.id;
|
|
706
|
+
if (id && client.db) {
|
|
707
|
+
const read3 = await client.db.store("messages").read(id);
|
|
708
|
+
const editType = getContentType(edited?.message?.protocolMessage?.editedMessage);
|
|
709
|
+
const readType = getContentType(read3?.message);
|
|
710
|
+
let editing = void 0;
|
|
711
|
+
if (editType && edited?.message?.protocolMessage?.editedMessage) {
|
|
712
|
+
editing = edited.message.protocolMessage.editedMessage[editType];
|
|
713
|
+
if (readType && read3?.message) {
|
|
714
|
+
read3.message[readType] = _2.merge(read3.message[readType], editing);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
msg = read3 || msg;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
const contentType = getContentType(msg?.message?.protocolMessage?.editedMessage || msg?.message);
|
|
721
|
+
if (!contentType) return null;
|
|
722
|
+
const payload = {};
|
|
723
|
+
payload.chatId = msg?.message?.protocolMessage?.key?.id || msg?.key?.id || "";
|
|
724
|
+
payload.channelId = "";
|
|
725
|
+
payload.uniqueId = "";
|
|
726
|
+
payload.receiverId = jidNormalizedUser(client.socket?.user?.id || "");
|
|
727
|
+
payload.receiverName = client.socket?.user?.name || client.socket?.user?.verifiedName || "";
|
|
728
|
+
payload.roomId = jidNormalizedUser(message?.key?.remoteJid || "");
|
|
729
|
+
if (client.db) {
|
|
730
|
+
const roomName = await client.db.store("chats").read(payload.roomId);
|
|
731
|
+
payload.roomName = toJson(roomName)?.name || "";
|
|
732
|
+
}
|
|
733
|
+
payload.senderLid = msg?.message?.protocolMessage?.key?.senderLid || msg?.key?.senderLid || msg?.key?.participantLid || "";
|
|
734
|
+
payload.senderId = jidNormalizedUser(msg?.participant || msg?.key?.participant || msg?.key?.remoteJid);
|
|
735
|
+
if (client.db) {
|
|
736
|
+
const senderName = await client.db.store("chats").read(payload.senderId);
|
|
737
|
+
payload.senderLid = payload.senderLid || toJson(senderName)?.lidJid || "";
|
|
738
|
+
payload.senderName = msg?.pushName || msg?.verifiedBizName || toJson(senderName)?.name || payload.receiverName;
|
|
739
|
+
}
|
|
740
|
+
payload.senderDevice = getDevice(payload.chatId);
|
|
741
|
+
if (payload.senderId == payload.receiverId) {
|
|
742
|
+
payload.senderName = payload.receiverName;
|
|
743
|
+
}
|
|
744
|
+
payload.roomName = payload.roomName || payload.senderName || _2.split(payload.roomId || "", "@")[0];
|
|
745
|
+
payload.chatType = MessagesMediaType[contentType];
|
|
746
|
+
payload.timestamp = Number(msg?.messageTimestamp || 0);
|
|
747
|
+
payload.text = null;
|
|
748
|
+
payload.mentions = [];
|
|
749
|
+
payload.links = [];
|
|
750
|
+
payload.isPrefix = false;
|
|
751
|
+
payload.isSpam = false;
|
|
752
|
+
payload.isFromMe = message?.key?.fromMe || false;
|
|
753
|
+
payload.isTagMe = false;
|
|
754
|
+
payload.isGroup = _2.includes(payload.roomId, "@g.us");
|
|
755
|
+
payload.isStory = _2.includes(payload.roomId, "@broadcast");
|
|
756
|
+
payload.isViewOnce = false;
|
|
757
|
+
payload.isEdited = false;
|
|
758
|
+
payload.isDeleted = isDeleted;
|
|
759
|
+
payload.isPinned = isPinned;
|
|
760
|
+
payload.isUnPinned = isUnPinned;
|
|
761
|
+
payload.isChannel = _2.includes(payload.roomId, "@newsletter");
|
|
762
|
+
payload.isBroadcast = !!message?.broadcast;
|
|
763
|
+
payload.isEphemeral = false;
|
|
764
|
+
payload.isForwarded = false;
|
|
765
|
+
if (!isReplied && true) {
|
|
766
|
+
const limiter = await LimiterHandler(payload.roomId, client.props.limiter?.maxMessages || 3, client.props.limiter?.durationMs || 5e3);
|
|
767
|
+
payload.isSpam = limiter;
|
|
768
|
+
}
|
|
769
|
+
if (payload.isFromMe) {
|
|
770
|
+
payload.senderId = payload.receiverId;
|
|
771
|
+
payload.senderName = payload.receiverName;
|
|
772
|
+
}
|
|
773
|
+
payload.citation = null;
|
|
774
|
+
payload.media = null;
|
|
775
|
+
payload.replied = null;
|
|
776
|
+
payload.channelId = _2.join([_2.split(payload.roomId, "@")[0], _2.split(payload.senderId, "@")[0]], "-");
|
|
777
|
+
payload.uniqueId = _2.join([payload.channelId, payload.chatId], "-");
|
|
778
|
+
const citation = client.props?.citation || {};
|
|
779
|
+
if (Object.keys(citation).length) {
|
|
780
|
+
payload.citation = {};
|
|
781
|
+
for (const key of Object.keys(citation)) {
|
|
782
|
+
const slug = "is" + _2.upperFirst(_2.camelCase(key));
|
|
783
|
+
const citationEntry = citation[key];
|
|
784
|
+
if (citationEntry && Array.isArray(citationEntry)) {
|
|
785
|
+
const senderId = payload.senderId.split("@")[0];
|
|
786
|
+
const roomId = payload.roomId.split("@")[0];
|
|
787
|
+
const citationRecord = citation;
|
|
788
|
+
payload.citation[slug] = (senderId ? (citationRecord[key] || []).includes(Number(senderId)) : false) || (roomId ? (citationRecord[key] || []).includes(Number(roomId)) : false);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
const media = msg?.message?.editedMessage?.[contentType] || msg?.message?.protocolMessage?.editedMessage?.[contentType] || msg?.message?.[contentType]?.message?.documentMessage || msg?.message?.[contentType];
|
|
793
|
+
if (payload.chatType != "text") {
|
|
794
|
+
payload.media = {
|
|
795
|
+
..._2.omit(media, [
|
|
796
|
+
"url",
|
|
797
|
+
"contextInfo",
|
|
798
|
+
"fileSha256",
|
|
799
|
+
"fileEncSha256",
|
|
800
|
+
"mediaKey",
|
|
801
|
+
"directPath",
|
|
802
|
+
"waveform",
|
|
803
|
+
"thumbnail",
|
|
804
|
+
"jpegThumbnail",
|
|
805
|
+
"thumbnailEncSha256",
|
|
806
|
+
"thumbnailSha256",
|
|
807
|
+
"thumbnailDirectPath",
|
|
808
|
+
"firstFrameSidecar",
|
|
809
|
+
"streamingSidecar",
|
|
810
|
+
"scansSidecar",
|
|
811
|
+
"callKey",
|
|
812
|
+
"message",
|
|
813
|
+
"key",
|
|
814
|
+
"midQualityFileSha256"
|
|
815
|
+
]),
|
|
816
|
+
buffer: () => downloadMediaMessage(message, "buffer", {}),
|
|
817
|
+
stream: () => downloadMediaMessage(message, "stream", {})
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
const repliedId = toJson(msg?.message?.[contentType])?.contextInfo?.stanzaId;
|
|
821
|
+
if (repliedId && MAX_REPLIES < 1 && client.db) {
|
|
822
|
+
MAX_REPLIES++;
|
|
823
|
+
const replied = await client.db.store("messages").read(repliedId);
|
|
824
|
+
if (!replied) {
|
|
825
|
+
payload.replied = await extract(msg, true);
|
|
826
|
+
} else {
|
|
827
|
+
payload.replied = await extract(replied, true);
|
|
828
|
+
}
|
|
829
|
+
MAX_REPLIES = 0;
|
|
830
|
+
}
|
|
831
|
+
const text = typeof media == "string" ? media : media?.text || media?.caption || media?.name || media?.displayName || media?.conversation || media?.contentText || media?.selectedDisplayText || "";
|
|
832
|
+
payload.text = normalizeText(text) || "";
|
|
833
|
+
payload.mentions = getMentions(payload.text || "");
|
|
834
|
+
payload.links = extractUrls(payload.text || "");
|
|
835
|
+
const messaging = toJson(msg?.message?.[contentType]);
|
|
836
|
+
payload.isPrefix = !!(client.props?.prefix && _2.startsWith(payload.text, client.props?.prefix));
|
|
837
|
+
payload.isTagMe = _2.includes(payload.mentions, _2.split(payload.receiverId, "@")[0] || "");
|
|
838
|
+
payload.isEdited = !!edited;
|
|
839
|
+
payload.isEphemeral = !!findWord(toString(messaging?.contextInfo), "ephemeralSettingTimestamp");
|
|
840
|
+
payload.isForwarded = !!findWord(toString(messaging?.contextInfo), "forwardingScore");
|
|
841
|
+
payload.isViewOnce = !!messaging?.viewOnce;
|
|
842
|
+
if (payload.isPrefix) {
|
|
843
|
+
payload.text = _2.replace(payload.text, new RegExp(`^${client.props?.prefix}`), "");
|
|
844
|
+
}
|
|
845
|
+
payload.message = () => CLONE;
|
|
846
|
+
return payload;
|
|
847
|
+
};
|
|
848
|
+
return extract(message);
|
|
849
|
+
};
|
|
850
|
+
var Listener = class {
|
|
851
|
+
client;
|
|
852
|
+
async bind(client, db) {
|
|
853
|
+
this.client = client;
|
|
854
|
+
this.client.db = db;
|
|
855
|
+
this.client.socket?.ev.on("connection.update", async (update) => {
|
|
856
|
+
await this.connection(update);
|
|
857
|
+
});
|
|
858
|
+
this.client.socket?.ev.on("messages.upsert", async ({ messages }) => {
|
|
859
|
+
for (const message of messages) {
|
|
860
|
+
await this.messages(message);
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
this.client.socket?.ev.on("call", async (callers) => {
|
|
864
|
+
for (const caller of callers) {
|
|
865
|
+
await this.calls(caller);
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
this.client.socket?.ev.on("creds.update", () => {
|
|
869
|
+
});
|
|
870
|
+
if (this.client.socket?.ws) {
|
|
871
|
+
const originalEmit = this.client.socket.ws.emit.bind(this.client.socket.ws);
|
|
872
|
+
this.client.socket.ws.emit = (event, ...args) => {
|
|
873
|
+
if (event === "error" && args[0]) {
|
|
874
|
+
const errorMessage = args[0].message || args[0]?.toString();
|
|
875
|
+
if (_2.includes(errorMessage, "Closing open session in favor of incoming prekey bundle") || _2.includes(errorMessage, "Closing stale open session for new outgoing prekey bundle") || _2.includes(errorMessage, "Closing session: SessionEntry")) {
|
|
876
|
+
this.handleSessionClosing();
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
return originalEmit(event, ...args);
|
|
880
|
+
};
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
async handleSessionClosing() {
|
|
884
|
+
this.client.spinner.start("Processing session changes...");
|
|
885
|
+
await delay(3e3);
|
|
886
|
+
this.client.spinner.success("Session processing completed");
|
|
887
|
+
}
|
|
888
|
+
async connection(update) {
|
|
889
|
+
const { connection, lastDisconnect, qr } = update;
|
|
890
|
+
this.client.emit("connection", { status: "connecting" });
|
|
891
|
+
if (this.client.props.authType === "qr" && qr) {
|
|
892
|
+
this.client.spinner.info(`Please scan the QR
|
|
893
|
+
|
|
894
|
+
${await QRCode.toString(qr, { type: "terminal", small: true })}`);
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
if (connection === "close") {
|
|
898
|
+
const code = toJson(lastDisconnect?.error)?.output?.statusCode;
|
|
899
|
+
const errorMessage = lastDisconnect?.error?.message || "";
|
|
900
|
+
const isReconnect = typeof code === "number" && code !== DisconnectReason.loggedOut;
|
|
901
|
+
if (_2.includes(errorMessage, "Closing open session in favor of incoming prekey bundle") || _2.includes(errorMessage, "Closing stale open session for new outgoing prekey bundle") || _2.includes(errorMessage, "Closing session: SessionEntry")) {
|
|
902
|
+
this.client.spinner.start("Processing session changes...");
|
|
903
|
+
await new Promise((resolve) => setTimeout(resolve, 2e3));
|
|
904
|
+
this.client.spinner.success("Session processing completed");
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
this.client.spinner.error(`[Connection Closed] [${code}] ${errorMessage}`);
|
|
908
|
+
if (code === 401 || code === 405 || code === 500) {
|
|
909
|
+
this.client.spinner.error("Invalid session, please delete manually");
|
|
910
|
+
this.client.spinner.error(`Session "${this.client.props.session}" has not valid, please delete it`);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
if (isReconnect) {
|
|
914
|
+
this.client.spinner.warn("Connection lost. Attempting auto-reload...");
|
|
915
|
+
const clientRecord = this.client;
|
|
916
|
+
if (typeof clientRecord.autoReload === "function") {
|
|
917
|
+
await clientRecord.autoReload();
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
} else if (connection === "open") {
|
|
921
|
+
if (this.client.socket?.user) {
|
|
922
|
+
const id = jidNormalizedUser(this.client.socket.user.id).split("@")[0];
|
|
923
|
+
const name = this.client.socket.user.name || this.client.socket.user.verifiedName;
|
|
924
|
+
const clientRecord = this.client;
|
|
925
|
+
if (typeof clientRecord.resetRetryCount === "function") {
|
|
926
|
+
clientRecord.resetRetryCount();
|
|
927
|
+
}
|
|
928
|
+
this.client.spinner.success(`Connected as ${chalk.green(name || id)}`);
|
|
929
|
+
this.client.emit("connection", { status: "open" });
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
async messages(message) {
|
|
934
|
+
if (this.client.props?.autoRead && this.client.socket) {
|
|
935
|
+
if (message?.key) {
|
|
936
|
+
await this.client.socket.readMessages([message.key]);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
const extract = await MessagesExtractor(this.client, message);
|
|
940
|
+
if (extract) {
|
|
941
|
+
this.client.emit("messages", extract);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
async calls(caller) {
|
|
945
|
+
if (this.client.props?.autoRejectCall && this.client.socket) {
|
|
946
|
+
await this.client.socket.rejectCall(caller.id, caller.from);
|
|
947
|
+
}
|
|
948
|
+
const extract = await CallsExtractor(this.client, caller);
|
|
949
|
+
this.client.emit("calls", extract);
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
var RelayTextType = z.string().or(z.object({
|
|
953
|
+
text: z.string(),
|
|
954
|
+
roomId: z.string().optional(),
|
|
955
|
+
options: z.custom().optional(),
|
|
956
|
+
externalAdReply: AdsReplyType.optional()
|
|
957
|
+
}));
|
|
958
|
+
var RelayReplyType = z.string().or(
|
|
959
|
+
z.object({
|
|
960
|
+
text: z.string(),
|
|
961
|
+
roomId: z.string().optional(),
|
|
962
|
+
options: z.custom().optional(),
|
|
963
|
+
externalAdReply: AdsReplyType.optional()
|
|
964
|
+
})
|
|
965
|
+
);
|
|
966
|
+
var RelayForwardType = z.string().or(
|
|
967
|
+
z.object({
|
|
968
|
+
text: z.string(),
|
|
969
|
+
isForwardMany: defaultBoolean(false),
|
|
970
|
+
roomId: z.string().optional(),
|
|
971
|
+
options: z.custom().optional(),
|
|
972
|
+
externalAdReply: AdsReplyType.optional()
|
|
973
|
+
})
|
|
974
|
+
);
|
|
975
|
+
var RelayImageEnumType = z.enum(["text", "reply", "forward"]);
|
|
976
|
+
var RelayImageType = z.object({
|
|
977
|
+
image: z.url().or(z.base64()).or(z.instanceof(Buffer)),
|
|
978
|
+
text: z.string().optional(),
|
|
979
|
+
viewOnce: defaultBoolean(false),
|
|
980
|
+
roomId: z.string().optional(),
|
|
981
|
+
externalAdReply: AdsReplyType.optional()
|
|
982
|
+
});
|
|
983
|
+
var RelayVideoEnumType = z.enum(["text", "reply", "forward"]);
|
|
984
|
+
var RelayVideoType = z.object({
|
|
985
|
+
video: z.url().or(z.base64()).or(z.instanceof(Buffer)),
|
|
986
|
+
text: z.string().optional(),
|
|
987
|
+
viewOnce: defaultBoolean(false),
|
|
988
|
+
roomId: z.string().optional()
|
|
989
|
+
});
|
|
990
|
+
var RelayAudioEnumType = z.enum(["text", "reply", "forward"]);
|
|
991
|
+
var RelayAudioType = z.object({
|
|
992
|
+
audio: z.url().or(z.base64()).or(z.instanceof(Buffer)),
|
|
993
|
+
viewOnce: defaultBoolean(false),
|
|
994
|
+
roomId: z.string().optional(),
|
|
995
|
+
externalAdReply: AdsReplyType.optional()
|
|
996
|
+
});
|
|
997
|
+
var RelayStickerEnumType = z.enum(["text", "reply", "forward"]);
|
|
998
|
+
var RelayStickerType = z.object({
|
|
999
|
+
sticker: z.url().or(z.base64()).or(z.instanceof(Buffer)),
|
|
1000
|
+
roomId: z.string().optional()
|
|
1001
|
+
});
|
|
1002
|
+
var RelayEditType = z.object({
|
|
1003
|
+
text: z.string(),
|
|
1004
|
+
message: z.function({
|
|
1005
|
+
input: [],
|
|
1006
|
+
output: z.any()
|
|
1007
|
+
}).optional()
|
|
1008
|
+
});
|
|
1009
|
+
var RelayDeleteType = z.object({
|
|
1010
|
+
message: z.function({
|
|
1011
|
+
input: [],
|
|
1012
|
+
output: z.any()
|
|
1013
|
+
}).optional()
|
|
1014
|
+
});
|
|
1015
|
+
var ExtractorCallsType = z.object({
|
|
1016
|
+
callId: z.string(),
|
|
1017
|
+
roomId: z.string(),
|
|
1018
|
+
callerId: z.string(),
|
|
1019
|
+
date: z.date(),
|
|
1020
|
+
offline: z.boolean(),
|
|
1021
|
+
status: z.enum(["accept", "offer", "reject", "ringing", "terminate", "timeout"]),
|
|
1022
|
+
isVideo: z.boolean(),
|
|
1023
|
+
isGroup: z.boolean()
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
// src/types/relay/reject.ts
|
|
1027
|
+
var RelayRejectType = ExtractorCallsType.pick({
|
|
1028
|
+
callId: true,
|
|
1029
|
+
callerId: true
|
|
1030
|
+
});
|
|
1031
|
+
var RelayPresenceType = z.enum(["typing", "recording", "online", "offline", "paused"]);
|
|
1032
|
+
var RelayReactionType = z.emoji().or(
|
|
1033
|
+
z.object({
|
|
1034
|
+
emoticon: z.emoji(),
|
|
1035
|
+
message: z.function({
|
|
1036
|
+
input: [],
|
|
1037
|
+
output: z.any()
|
|
1038
|
+
}).optional()
|
|
1039
|
+
})
|
|
1040
|
+
);
|
|
1041
|
+
var RelayLocationEnumType = z.enum(["text", "reply", "forward"]);
|
|
1042
|
+
var RelayLocationType = z.object({
|
|
1043
|
+
latitude: z.number(),
|
|
1044
|
+
longitude: z.number(),
|
|
1045
|
+
title: z.string().optional(),
|
|
1046
|
+
footer: z.string().optional(),
|
|
1047
|
+
roomId: z.string().optional(),
|
|
1048
|
+
externalAdReply: AdsReplyType.optional()
|
|
1049
|
+
});
|
|
1050
|
+
var RelayContactEnumType = z.enum(["text", "reply", "forward"]);
|
|
1051
|
+
var RelayContactType = z.object({
|
|
1052
|
+
title: z.string().optional(),
|
|
1053
|
+
contacts: z.object({
|
|
1054
|
+
fullname: z.string(),
|
|
1055
|
+
nickname: z.string().optional(),
|
|
1056
|
+
organization: z.string().optional(),
|
|
1057
|
+
phoneNumber: z.number(),
|
|
1058
|
+
website: z.url().optional()
|
|
1059
|
+
}).array(),
|
|
1060
|
+
roomId: z.string().optional()
|
|
1061
|
+
});
|
|
1062
|
+
var RelayPollEnumType = z.enum(["text", "reply", "forward"]);
|
|
1063
|
+
var RelayPollCreateType = z.object({
|
|
1064
|
+
action: z.literal("create"),
|
|
1065
|
+
name: z.string(),
|
|
1066
|
+
answers: z.string().array(),
|
|
1067
|
+
isMultiple: defaultBoolean(false),
|
|
1068
|
+
roomId: z.string().optional()
|
|
1069
|
+
});
|
|
1070
|
+
z.object({
|
|
1071
|
+
action: z.literal("result"),
|
|
1072
|
+
name: z.string(),
|
|
1073
|
+
votes: z.tuple([z.string(), z.number()]).array(),
|
|
1074
|
+
roomId: z.string().optional()
|
|
1075
|
+
});
|
|
1076
|
+
var RelayPollType = z.discriminatedUnion("action", [RelayPollCreateType]);
|
|
1077
|
+
var RelayDocumentEnumType = z.enum(["text", "reply", "forward"]);
|
|
1078
|
+
var RelayDocumentType = z.object({
|
|
1079
|
+
document: z.url().or(z.base64()).or(z.instanceof(Buffer)),
|
|
1080
|
+
mimetype: z.string(),
|
|
1081
|
+
text: z.string().optional(),
|
|
1082
|
+
fileName: z.string().optional(),
|
|
1083
|
+
roomId: z.string().optional(),
|
|
1084
|
+
externalAdReply: AdsReplyType.optional()
|
|
1085
|
+
});
|
|
1086
|
+
var RelayButtonEnumType = z.enum(["text", "reply", "forward"]);
|
|
1087
|
+
var RelayButtonSimpleType = z.object({
|
|
1088
|
+
type: z.literal("simple"),
|
|
1089
|
+
text: z.string(),
|
|
1090
|
+
footer: z.string().optional(),
|
|
1091
|
+
buttons: z.object({
|
|
1092
|
+
id: z.string(),
|
|
1093
|
+
text: z.string()
|
|
1094
|
+
}).array(),
|
|
1095
|
+
roomId: z.string().optional()
|
|
1096
|
+
});
|
|
1097
|
+
var RelayButtonInteractiveReplyType = z.object({
|
|
1098
|
+
type: z.literal("quick_reply"),
|
|
1099
|
+
id: z.string(),
|
|
1100
|
+
text: z.string()
|
|
1101
|
+
});
|
|
1102
|
+
var RelayButtonInteractiveUrlType = z.object({
|
|
1103
|
+
type: z.literal("cta_url"),
|
|
1104
|
+
id: z.string(),
|
|
1105
|
+
url: z.url(),
|
|
1106
|
+
text: z.string()
|
|
1107
|
+
});
|
|
1108
|
+
var RelayButtonInteractiveCopyType = z.object({
|
|
1109
|
+
type: z.literal("cta_copy"),
|
|
1110
|
+
id: z.string(),
|
|
1111
|
+
copy: z.string(),
|
|
1112
|
+
text: z.string()
|
|
1113
|
+
});
|
|
1114
|
+
var RelayButtonInteractiveCallType = z.object({
|
|
1115
|
+
type: z.literal("cta_call"),
|
|
1116
|
+
id: z.string(),
|
|
1117
|
+
phoneNumber: z.string(),
|
|
1118
|
+
text: z.string()
|
|
1119
|
+
});
|
|
1120
|
+
var RelayButtonInteractiveType = z.object({
|
|
1121
|
+
type: z.literal("interactive"),
|
|
1122
|
+
text: z.string(),
|
|
1123
|
+
footer: z.string().optional(),
|
|
1124
|
+
buttons: z.discriminatedUnion("type", [RelayButtonInteractiveReplyType, RelayButtonInteractiveUrlType, RelayButtonInteractiveCopyType, RelayButtonInteractiveCallType]).array(),
|
|
1125
|
+
roomId: z.string().optional()
|
|
1126
|
+
});
|
|
1127
|
+
z.object({
|
|
1128
|
+
type: z.literal("list"),
|
|
1129
|
+
text: z.string(),
|
|
1130
|
+
footer: z.string(),
|
|
1131
|
+
roomId: z.string().optional()
|
|
1132
|
+
});
|
|
1133
|
+
var RelayButtonType = z.discriminatedUnion("type", [RelayButtonSimpleType, RelayButtonInteractiveType]);
|
|
1134
|
+
var RelayGroupCreateType = z.object({
|
|
1135
|
+
title: z.string(),
|
|
1136
|
+
members: z.string().array()
|
|
1137
|
+
});
|
|
1138
|
+
var RelayGroupActionType = z.object({
|
|
1139
|
+
roomId: z.string(),
|
|
1140
|
+
action: z.enum(["add", "kick", "promote", "demote"]),
|
|
1141
|
+
members: z.string().array()
|
|
1142
|
+
});
|
|
1143
|
+
var RelayGroupUpdateType = z.object({
|
|
1144
|
+
roomId: z.string(),
|
|
1145
|
+
text: z.string(),
|
|
1146
|
+
action: z.enum(["subject", "description"])
|
|
1147
|
+
});
|
|
1148
|
+
var RelayGroupSettingsType = z.object({
|
|
1149
|
+
roomId: z.string(),
|
|
1150
|
+
action: z.enum(["open", "close", "lock", "unlock"])
|
|
1151
|
+
});
|
|
1152
|
+
var RelayGroupLeaveType = z.object({
|
|
1153
|
+
roomId: z.string()
|
|
1154
|
+
});
|
|
1155
|
+
var RelayGroupLinksType = z.object({
|
|
1156
|
+
roomId: z.string(),
|
|
1157
|
+
action: z.enum(["get", "revoke"])
|
|
1158
|
+
});
|
|
1159
|
+
var RelayGroupInviteType = z.object({
|
|
1160
|
+
url: z.url().regex(/^https:\/\/chat\.whatsapp\.com\/[A-Za-z0-9_-]{5,}$/),
|
|
1161
|
+
action: z.enum(["join", "info"])
|
|
1162
|
+
});
|
|
1163
|
+
var RelayGroupRequestsListType = z.object({
|
|
1164
|
+
roomId: z.string()
|
|
1165
|
+
});
|
|
1166
|
+
var RelayGroupRequestsApproveType = z.object({
|
|
1167
|
+
roomId: z.string(),
|
|
1168
|
+
members: z.string().array()
|
|
1169
|
+
});
|
|
1170
|
+
var RelayGroupRequestsRejectType = z.object({
|
|
1171
|
+
roomId: z.string(),
|
|
1172
|
+
members: z.string().array()
|
|
1173
|
+
});
|
|
1174
|
+
var RelayGroupMetadataType = z.object({
|
|
1175
|
+
roomId: z.string()
|
|
1176
|
+
});
|
|
1177
|
+
var RelayPrivacyUpdateControlType = z.object({
|
|
1178
|
+
action: z.literal("control"),
|
|
1179
|
+
type: z.enum(["block", "unblock"]),
|
|
1180
|
+
senderId: z.string()
|
|
1181
|
+
});
|
|
1182
|
+
var RelayPrivacyUpdateLastSeenType = z.object({
|
|
1183
|
+
action: z.literal("lastSeen"),
|
|
1184
|
+
type: z.enum(["all", "contacts", "contact_blacklist", "none"])
|
|
1185
|
+
});
|
|
1186
|
+
var RelayPrivacyUpdateOnlineType = z.object({
|
|
1187
|
+
action: z.literal("online"),
|
|
1188
|
+
type: z.enum(["all", "match_last_seen"])
|
|
1189
|
+
});
|
|
1190
|
+
var RelayPrivacyUpdateAvatarType = z.object({
|
|
1191
|
+
action: z.literal("avatar"),
|
|
1192
|
+
type: z.enum(["all", "contacts", "contact_blacklist", "none"])
|
|
1193
|
+
});
|
|
1194
|
+
var RelayPrivacyUpdateStoryType = z.object({
|
|
1195
|
+
action: z.literal("story"),
|
|
1196
|
+
type: z.enum(["all", "contacts", "contact_blacklist", "none"])
|
|
1197
|
+
});
|
|
1198
|
+
var RelayPrivacyUpdateReadType = z.object({
|
|
1199
|
+
action: z.literal("read"),
|
|
1200
|
+
type: z.enum(["all", "none"])
|
|
1201
|
+
});
|
|
1202
|
+
var RelayPrivacyGroupsAddType = z.object({
|
|
1203
|
+
action: z.literal("groupsAdd"),
|
|
1204
|
+
type: z.enum(["all", "contacts", "contact_blacklist"])
|
|
1205
|
+
});
|
|
1206
|
+
var RelayPrivacyEphemeralType = z.object({
|
|
1207
|
+
action: z.literal("ephemeral"),
|
|
1208
|
+
type: z.enum(["remove", "24h", "7d", "90d"])
|
|
1209
|
+
});
|
|
1210
|
+
var RelayPrivacyUpdateType = z.discriminatedUnion("action", [
|
|
1211
|
+
RelayPrivacyUpdateControlType,
|
|
1212
|
+
RelayPrivacyUpdateLastSeenType,
|
|
1213
|
+
RelayPrivacyUpdateOnlineType,
|
|
1214
|
+
RelayPrivacyUpdateAvatarType,
|
|
1215
|
+
RelayPrivacyUpdateStoryType,
|
|
1216
|
+
RelayPrivacyUpdateReadType,
|
|
1217
|
+
RelayPrivacyGroupsAddType,
|
|
1218
|
+
RelayPrivacyEphemeralType
|
|
1219
|
+
]);
|
|
1220
|
+
var RelayProfileBioType = z.object({
|
|
1221
|
+
senderId: z.string()
|
|
1222
|
+
});
|
|
1223
|
+
var RelayProfileUpdateType = z.object({
|
|
1224
|
+
type: z.enum(["name", "bio", "avatar"]),
|
|
1225
|
+
text: z.string().optional(),
|
|
1226
|
+
roomId: z.string().optional(),
|
|
1227
|
+
avatar: z.url().or(z.base64()).or(z.instanceof(Buffer)).or(z.literal("remove"))
|
|
1228
|
+
});
|
|
1229
|
+
var RelayProfileCheckType = z.object({
|
|
1230
|
+
senderId: z.string()
|
|
1231
|
+
});
|
|
1232
|
+
|
|
1233
|
+
// src/classes/Relay.ts
|
|
1234
|
+
var Relay = class {
|
|
1235
|
+
client;
|
|
1236
|
+
message;
|
|
1237
|
+
db;
|
|
1238
|
+
ctx;
|
|
1239
|
+
bind(client, db) {
|
|
1240
|
+
this.client = client;
|
|
1241
|
+
this.db = db;
|
|
1242
|
+
this.ctx = client;
|
|
1243
|
+
this.ctx.db = db;
|
|
1244
|
+
this.client.on("messages", (ctx) => {
|
|
1245
|
+
this.message = ctx;
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
async initial(props) {
|
|
1249
|
+
await delay(0);
|
|
1250
|
+
if (!props?.disabledPresence) {
|
|
1251
|
+
if (this.client.props?.autoPresence && props?.isAudio) {
|
|
1252
|
+
this.client.socket?.sendPresenceUpdate("recording", this.message?.roomId);
|
|
1253
|
+
} else {
|
|
1254
|
+
this.client.socket?.sendPresenceUpdate("composing", this.message?.roomId);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
// GENERAL RELAY
|
|
1259
|
+
async text(props) {
|
|
1260
|
+
await this.initial();
|
|
1261
|
+
const params = RelayTextType.parse(props);
|
|
1262
|
+
let extend = { contextInfo: {} };
|
|
1263
|
+
if (this.client.props.autoMentions) {
|
|
1264
|
+
extend.contextInfo.mentionedJid = extractJids(this.message.text);
|
|
1265
|
+
}
|
|
1266
|
+
if (typeof params == "string") {
|
|
1267
|
+
if (this.client.socket) {
|
|
1268
|
+
const res = await this.client.socket.sendMessage(this.message?.roomId, {
|
|
1269
|
+
text: params,
|
|
1270
|
+
...extend
|
|
1271
|
+
});
|
|
1272
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
if (typeof params == "object") {
|
|
1276
|
+
const obj = { ...extend, ...params.options };
|
|
1277
|
+
if (params.externalAdReply) {
|
|
1278
|
+
obj.contextInfo = { externalAdReply: params.externalAdReply };
|
|
1279
|
+
}
|
|
1280
|
+
if (this.client.socket) {
|
|
1281
|
+
if (params.text != "$$media$$") {
|
|
1282
|
+
obj.text = params?.text;
|
|
1283
|
+
}
|
|
1284
|
+
const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj);
|
|
1285
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
async reply(props) {
|
|
1290
|
+
await this.initial();
|
|
1291
|
+
const params = RelayReplyType.parse(props);
|
|
1292
|
+
const quoted = this.message?.message();
|
|
1293
|
+
let extend = { contextInfo: {} };
|
|
1294
|
+
if (this.client.props.autoMentions) {
|
|
1295
|
+
extend.contextInfo.mentionedJid = extractJids(this.message.text);
|
|
1296
|
+
}
|
|
1297
|
+
if (this.client.props?.fakeReply?.provider) {
|
|
1298
|
+
const provider = this.client.props.fakeReply.provider;
|
|
1299
|
+
if (quoted && quoted.key) {
|
|
1300
|
+
quoted.key.remoteJid = MessagesVerifiedPlatformType[provider];
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
const options = quoted ? { quoted } : void 0;
|
|
1304
|
+
if (typeof params == "string") {
|
|
1305
|
+
if (this.client.socket) {
|
|
1306
|
+
const res = await this.client.socket.sendMessage(this.message?.roomId, { text: params, ...extend }, options);
|
|
1307
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
if (typeof params == "object") {
|
|
1311
|
+
const obj = { ...extend, ...params.options };
|
|
1312
|
+
if (params.externalAdReply) {
|
|
1313
|
+
obj.contextInfo = { externalAdReply: params.externalAdReply };
|
|
1314
|
+
}
|
|
1315
|
+
if (this.client.socket) {
|
|
1316
|
+
if (params.text != "$$media$$") {
|
|
1317
|
+
obj.text = params?.text;
|
|
1318
|
+
}
|
|
1319
|
+
const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj, options);
|
|
1320
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async forward(props) {
|
|
1325
|
+
await this.initial();
|
|
1326
|
+
const params = RelayForwardType.parse(props);
|
|
1327
|
+
const quoted = this.message?.message();
|
|
1328
|
+
let extend = { contextInfo: { isForwarded: true } };
|
|
1329
|
+
if (this.client.props.autoMentions) {
|
|
1330
|
+
extend.contextInfo.mentionedJid = extractJids(this.message.text);
|
|
1331
|
+
}
|
|
1332
|
+
if (this.client.props?.fakeReply?.provider) {
|
|
1333
|
+
const provider = this.client.props.fakeReply.provider;
|
|
1334
|
+
if (quoted && quoted.key) {
|
|
1335
|
+
quoted.key.remoteJid = MessagesVerifiedPlatformType[provider];
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
if (typeof params == "string") {
|
|
1339
|
+
if (this.client.socket) {
|
|
1340
|
+
const res = await this.client.socket.sendMessage(this.message?.roomId, { text: params, ...extend });
|
|
1341
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
if (typeof params == "object") {
|
|
1345
|
+
const obj = { ...extend, ...params.options };
|
|
1346
|
+
if (params.externalAdReply) {
|
|
1347
|
+
obj.contextInfo.externalAdReply = params.externalAdReply;
|
|
1348
|
+
}
|
|
1349
|
+
if (params.isForwardMany) {
|
|
1350
|
+
extend.contextInfo.forwardingScore = 999999;
|
|
1351
|
+
}
|
|
1352
|
+
if (this.client.socket) {
|
|
1353
|
+
if (params.text != "$$media$$") {
|
|
1354
|
+
obj.text = params?.text;
|
|
1355
|
+
}
|
|
1356
|
+
const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj);
|
|
1357
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
async edit(props) {
|
|
1362
|
+
await this.initial({ disabledPresence: true });
|
|
1363
|
+
const params = RelayEditType.parse(props);
|
|
1364
|
+
const message = params.message();
|
|
1365
|
+
const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { text: params.text, edit: message?.key });
|
|
1366
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1367
|
+
}
|
|
1368
|
+
async delete(props) {
|
|
1369
|
+
await this.initial({ disabledPresence: true });
|
|
1370
|
+
const params = RelayDeleteType.parse(props);
|
|
1371
|
+
const message = params.message();
|
|
1372
|
+
const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { delete: message?.key });
|
|
1373
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1374
|
+
}
|
|
1375
|
+
async reject(props) {
|
|
1376
|
+
const params = RelayRejectType.parse(props);
|
|
1377
|
+
return await this.client.socket.rejectCall(params.callId, params.callerId);
|
|
1378
|
+
}
|
|
1379
|
+
async presence(props) {
|
|
1380
|
+
await this.initial({ disabledPresence: true });
|
|
1381
|
+
const params = RelayPresenceType.parse(props);
|
|
1382
|
+
const opts = {
|
|
1383
|
+
typing: "composing",
|
|
1384
|
+
recording: "recording",
|
|
1385
|
+
online: "available",
|
|
1386
|
+
offline: "unavailable",
|
|
1387
|
+
paused: "paused"
|
|
1388
|
+
};
|
|
1389
|
+
return await this.client.socket.sendPresenceUpdate(opts[params], this.message.roomId);
|
|
1390
|
+
}
|
|
1391
|
+
async reaction(props) {
|
|
1392
|
+
await this.initial({ disabledPresence: true });
|
|
1393
|
+
const params = RelayReactionType.parse(props);
|
|
1394
|
+
const message = typeof params == "string" ? this.message.message() : params.message();
|
|
1395
|
+
const text = typeof params == "string" ? params : params.emoticon;
|
|
1396
|
+
const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { react: { text, key: message?.key } });
|
|
1397
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1398
|
+
}
|
|
1399
|
+
// MEDIA RELAY
|
|
1400
|
+
async document(type, props) {
|
|
1401
|
+
await this.initial();
|
|
1402
|
+
const enumType = RelayDocumentEnumType.parse(type);
|
|
1403
|
+
const params = RelayDocumentType.parse(props);
|
|
1404
|
+
const options = {
|
|
1405
|
+
document: typeof params.document === "string" ? { url: params.document } : params.document,
|
|
1406
|
+
caption: params.text,
|
|
1407
|
+
mimetype: params.mimetype,
|
|
1408
|
+
fileName: params.fileName,
|
|
1409
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1410
|
+
};
|
|
1411
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1412
|
+
}
|
|
1413
|
+
async image(type, props) {
|
|
1414
|
+
await this.initial();
|
|
1415
|
+
const enumType = RelayImageEnumType.parse(type);
|
|
1416
|
+
const params = RelayImageType.parse(props);
|
|
1417
|
+
const options = {
|
|
1418
|
+
image: typeof params.image === "string" ? { url: params.image } : params.image,
|
|
1419
|
+
caption: params.text,
|
|
1420
|
+
viewOnce: params.viewOnce,
|
|
1421
|
+
contextInfo: { externalAdReply: params.externalAdReply, isQuestion: true }
|
|
1422
|
+
};
|
|
1423
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1424
|
+
}
|
|
1425
|
+
async sticker(type, props) {
|
|
1426
|
+
await this.initial();
|
|
1427
|
+
const enumType = RelayStickerEnumType.parse(type);
|
|
1428
|
+
const params = RelayStickerType.parse(props);
|
|
1429
|
+
const options = { sticker: typeof params.sticker === "string" ? { url: params.sticker } : params.sticker };
|
|
1430
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1431
|
+
}
|
|
1432
|
+
async video(type, props) {
|
|
1433
|
+
await this.initial();
|
|
1434
|
+
const enumType = RelayVideoEnumType.parse(type);
|
|
1435
|
+
const params = RelayVideoType.parse(props);
|
|
1436
|
+
const options = {
|
|
1437
|
+
video: typeof params.video === "string" ? { url: params.video } : params.video,
|
|
1438
|
+
caption: params.text,
|
|
1439
|
+
viewOnce: params.viewOnce
|
|
1440
|
+
};
|
|
1441
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1442
|
+
}
|
|
1443
|
+
async audio(type, props) {
|
|
1444
|
+
const enumType = RelayAudioEnumType.parse(type);
|
|
1445
|
+
const params = RelayAudioType.parse(props);
|
|
1446
|
+
const options = {
|
|
1447
|
+
audio: typeof params.audio === "string" ? { url: params.audio } : params.audio,
|
|
1448
|
+
viewOnce: params.viewOnce,
|
|
1449
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1450
|
+
};
|
|
1451
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1452
|
+
}
|
|
1453
|
+
async voice(type, props) {
|
|
1454
|
+
const enumType = RelayAudioEnumType.parse(type);
|
|
1455
|
+
const params = RelayAudioType.parse(props);
|
|
1456
|
+
const options = {
|
|
1457
|
+
audio: typeof params.audio === "string" ? { url: params.audio } : params.audio,
|
|
1458
|
+
ptt: true,
|
|
1459
|
+
viewOnce: params.viewOnce,
|
|
1460
|
+
mimetype: "audio/ogg; codecs=opus",
|
|
1461
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1462
|
+
};
|
|
1463
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1464
|
+
}
|
|
1465
|
+
async note(type, props) {
|
|
1466
|
+
await this.initial();
|
|
1467
|
+
const enumType = RelayVideoEnumType.parse(type);
|
|
1468
|
+
const params = RelayVideoType.parse(props);
|
|
1469
|
+
const options = { video: typeof params.video === "string" ? { url: params.video } : params.video, caption: params.text, ptv: true };
|
|
1470
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1471
|
+
}
|
|
1472
|
+
async gif(type, props) {
|
|
1473
|
+
await this.initial();
|
|
1474
|
+
const enumType = RelayVideoEnumType.parse(type);
|
|
1475
|
+
const params = RelayVideoType.parse(props);
|
|
1476
|
+
const options = { video: typeof params.video === "string" ? { url: params.video } : params.video, gifPlayback: true };
|
|
1477
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1478
|
+
}
|
|
1479
|
+
async location(type, props) {
|
|
1480
|
+
await this.initial();
|
|
1481
|
+
const enumType = RelayLocationEnumType.parse(type);
|
|
1482
|
+
const params = RelayLocationType.parse(props);
|
|
1483
|
+
const options = {
|
|
1484
|
+
location: {
|
|
1485
|
+
degreesLatitude: params.latitude,
|
|
1486
|
+
degreesLongitude: params.longitude,
|
|
1487
|
+
url: params.title,
|
|
1488
|
+
address: params.footer,
|
|
1489
|
+
name: params.title
|
|
1490
|
+
},
|
|
1491
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1492
|
+
};
|
|
1493
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1494
|
+
}
|
|
1495
|
+
async contacts(type, props) {
|
|
1496
|
+
await this.initial();
|
|
1497
|
+
const enumType = RelayContactEnumType.parse(type);
|
|
1498
|
+
const params = RelayContactType.parse(props);
|
|
1499
|
+
const contacts = params.contacts.map((x) => {
|
|
1500
|
+
const vcard = [
|
|
1501
|
+
"BEGIN:VCARD",
|
|
1502
|
+
"VERSION:3.0",
|
|
1503
|
+
`FN:${x.fullname}`,
|
|
1504
|
+
`ORG:${x.organization || ""}`,
|
|
1505
|
+
`TEL;type=CELL;type=VOICE;waid=${x.phoneNumber}:${x.phoneNumber}`,
|
|
1506
|
+
"END:VCARD"
|
|
1507
|
+
].join("\n");
|
|
1508
|
+
return { displayName: x.fullname, vcard };
|
|
1509
|
+
});
|
|
1510
|
+
const options = {
|
|
1511
|
+
contacts: {
|
|
1512
|
+
displayName: params?.title,
|
|
1513
|
+
contacts
|
|
1514
|
+
}
|
|
1515
|
+
};
|
|
1516
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1517
|
+
}
|
|
1518
|
+
async poll(type, props) {
|
|
1519
|
+
await this.initial();
|
|
1520
|
+
const enumType = RelayPollEnumType.parse(type);
|
|
1521
|
+
const params = RelayPollType.parse(props);
|
|
1522
|
+
const options = {};
|
|
1523
|
+
if (params.action == "create") {
|
|
1524
|
+
options.poll = {
|
|
1525
|
+
name: params.name,
|
|
1526
|
+
values: params.answers,
|
|
1527
|
+
selectableCount: !!params.isMultiple ? 1 : 0,
|
|
1528
|
+
toAnnouncementGroup: true
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1532
|
+
}
|
|
1533
|
+
async button(type, props) {
|
|
1534
|
+
await this.initial();
|
|
1535
|
+
const enumType = RelayButtonEnumType.parse(type);
|
|
1536
|
+
const params = RelayButtonType.parse(props);
|
|
1537
|
+
const options = {
|
|
1538
|
+
text: params.text,
|
|
1539
|
+
footer: params.footer
|
|
1540
|
+
};
|
|
1541
|
+
if (params.type == "simple") {
|
|
1542
|
+
options.buttons = params.buttons.map((x) => ({ buttonId: x.id, buttonText: { displayText: x.text } }));
|
|
1543
|
+
}
|
|
1544
|
+
if (params.type == "interactive") {
|
|
1545
|
+
options.interactiveButtons = params.buttons.map((x) => {
|
|
1546
|
+
let schema = { name: x.type };
|
|
1547
|
+
if (x.type == "quick_reply") {
|
|
1548
|
+
schema.buttonParamsJson = toString({
|
|
1549
|
+
id: x.id,
|
|
1550
|
+
display_text: x.text
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
if (x.type == "cta_url") {
|
|
1554
|
+
schema.buttonParamsJson = toString({
|
|
1555
|
+
id: x.id,
|
|
1556
|
+
display_text: x.text,
|
|
1557
|
+
url: x.url,
|
|
1558
|
+
merchant_url: x.url
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
if (x.type == "cta_copy") {
|
|
1562
|
+
schema.buttonParamsJson = toString({
|
|
1563
|
+
id: x.id,
|
|
1564
|
+
display_text: x.text,
|
|
1565
|
+
copy_code: x.copy
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
if (x.type == "cta_call") {
|
|
1569
|
+
schema.buttonParamsJson = toString({
|
|
1570
|
+
id: x.id,
|
|
1571
|
+
display_text: x.text,
|
|
1572
|
+
phone_number: x.phoneNumber
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
return schema;
|
|
1576
|
+
});
|
|
1577
|
+
}
|
|
1578
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1579
|
+
}
|
|
1580
|
+
// GROUP RELAY
|
|
1581
|
+
group() {
|
|
1582
|
+
const client = this.ctx;
|
|
1583
|
+
const create = async (props) => {
|
|
1584
|
+
const params = RelayGroupCreateType.parse(props);
|
|
1585
|
+
try {
|
|
1586
|
+
return await client.socket.groupCreate(params.title, params.members);
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
client.spinner.error("Failed create group. Make sure members has valid number.\n\n" + error);
|
|
1589
|
+
return null;
|
|
1590
|
+
}
|
|
1591
|
+
};
|
|
1592
|
+
const action = async (props) => {
|
|
1593
|
+
const params = RelayGroupActionType.parse(props);
|
|
1594
|
+
const opts = {
|
|
1595
|
+
add: "add",
|
|
1596
|
+
kick: "remove",
|
|
1597
|
+
promote: "promote",
|
|
1598
|
+
demote: "demote"
|
|
1599
|
+
};
|
|
1600
|
+
try {
|
|
1601
|
+
return await client.socket.groupParticipantsUpdate(params.roomId, params.members, opts[params.action]);
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
client.spinner.error("Failed update user. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1604
|
+
return null;
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
const update = async (props) => {
|
|
1608
|
+
const params = RelayGroupUpdateType.parse(props);
|
|
1609
|
+
const opts = {
|
|
1610
|
+
subject: "groupUpdateSubject",
|
|
1611
|
+
description: "groupUpdateDescription"
|
|
1612
|
+
};
|
|
1613
|
+
try {
|
|
1614
|
+
return await client.socket[opts[props.action]](params.roomId, props.text);
|
|
1615
|
+
} catch (error) {
|
|
1616
|
+
client.spinner.error("Failed update group. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1617
|
+
return null;
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
const settings = async (props) => {
|
|
1621
|
+
const params = RelayGroupSettingsType.parse(props);
|
|
1622
|
+
const opts = {
|
|
1623
|
+
open: "not_announcement",
|
|
1624
|
+
close: "announcement",
|
|
1625
|
+
lock: "locked",
|
|
1626
|
+
unlock: "unlocked"
|
|
1627
|
+
};
|
|
1628
|
+
try {
|
|
1629
|
+
return await client.socket.groupSettingUpdate(params.roomId, opts[params.action]);
|
|
1630
|
+
} catch (error) {
|
|
1631
|
+
client.spinner.error("Failed settings group. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1632
|
+
return null;
|
|
1633
|
+
}
|
|
1634
|
+
};
|
|
1635
|
+
const leave = async (props) => {
|
|
1636
|
+
const params = RelayGroupLeaveType.parse(props);
|
|
1637
|
+
try {
|
|
1638
|
+
return await client.socket.groupLeave(params.roomId);
|
|
1639
|
+
} catch (error) {
|
|
1640
|
+
client.spinner.error("Failed leave group. Make sure this number is in the group.\n\n" + error);
|
|
1641
|
+
return null;
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
const links = async (props) => {
|
|
1645
|
+
const params = RelayGroupLinksType.parse(props);
|
|
1646
|
+
const opts = {
|
|
1647
|
+
get: "groupInviteCode",
|
|
1648
|
+
revoke: "groupRevokeInvite"
|
|
1649
|
+
};
|
|
1650
|
+
try {
|
|
1651
|
+
const code = await client.socket[opts[params.action]](params.roomId);
|
|
1652
|
+
return `https://chat.whatsapp.com/` + code;
|
|
1653
|
+
} catch (error) {
|
|
1654
|
+
client.spinner.error("Failed get group link. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1655
|
+
return null;
|
|
1656
|
+
}
|
|
1657
|
+
};
|
|
1658
|
+
const invite = async (props) => {
|
|
1659
|
+
const params = RelayGroupInviteType.parse(props);
|
|
1660
|
+
const opts = {
|
|
1661
|
+
join: "groupAcceptInvite",
|
|
1662
|
+
info: "groupGetInviteInfo"
|
|
1663
|
+
};
|
|
1664
|
+
try {
|
|
1665
|
+
const code = params.url.split("https://chat.whatsapp.com/");
|
|
1666
|
+
return await client.socket[opts[params.action]](code[1]);
|
|
1667
|
+
} catch (error) {
|
|
1668
|
+
client.spinner.error("Failed get group link. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1669
|
+
return null;
|
|
1670
|
+
}
|
|
1671
|
+
};
|
|
1672
|
+
const metadata = async (props) => {
|
|
1673
|
+
const params = RelayGroupMetadataType.parse(props);
|
|
1674
|
+
try {
|
|
1675
|
+
const meta = await client.socket.groupMetadata(params.roomId);
|
|
1676
|
+
return meta;
|
|
1677
|
+
} catch (error) {
|
|
1678
|
+
client.spinner.error("Failed get group metadata. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1679
|
+
return null;
|
|
1680
|
+
}
|
|
1681
|
+
};
|
|
1682
|
+
const requests = {
|
|
1683
|
+
list: async (props) => {
|
|
1684
|
+
const params = RelayGroupRequestsListType.parse(props);
|
|
1685
|
+
return await client.socket.groupRequestParticipantsList(params.roomId);
|
|
1686
|
+
},
|
|
1687
|
+
approve: async (props) => {
|
|
1688
|
+
const params = RelayGroupRequestsApproveType.parse(props);
|
|
1689
|
+
return await client.socket.groupRequestParticipantsUpdate(params.roomId, params.members, "approve");
|
|
1690
|
+
},
|
|
1691
|
+
reject: async (props) => {
|
|
1692
|
+
const params = RelayGroupRequestsRejectType.parse(props);
|
|
1693
|
+
return await client.socket.groupRequestParticipantsUpdate(params.roomId, params.members, "reject");
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
return {
|
|
1697
|
+
create,
|
|
1698
|
+
action,
|
|
1699
|
+
update,
|
|
1700
|
+
settings,
|
|
1701
|
+
leave,
|
|
1702
|
+
links,
|
|
1703
|
+
invite,
|
|
1704
|
+
metadata,
|
|
1705
|
+
requests
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
// PRIVACY RELAY
|
|
1709
|
+
privacy() {
|
|
1710
|
+
const client = this.ctx;
|
|
1711
|
+
const update = async (props) => {
|
|
1712
|
+
const params = RelayPrivacyUpdateType.parse(props);
|
|
1713
|
+
try {
|
|
1714
|
+
if (params.action == "control") {
|
|
1715
|
+
return await client.socket.updateBlockStatus(params.senderId, params.type);
|
|
1716
|
+
}
|
|
1717
|
+
if (params.action == "lastSeen") {
|
|
1718
|
+
return await client.socket.updateLastSeenPrivacy(params.type);
|
|
1719
|
+
}
|
|
1720
|
+
if (params.action == "online") {
|
|
1721
|
+
return await client.socket.updateOnlinePrivacy(params.type);
|
|
1722
|
+
}
|
|
1723
|
+
if (params.action == "avatar") {
|
|
1724
|
+
return await client.socket.updateProfilePicturePrivacy(params.type);
|
|
1725
|
+
}
|
|
1726
|
+
if (params.action == "story") {
|
|
1727
|
+
return await client.socket.updateStatusPrivacy(params.type);
|
|
1728
|
+
}
|
|
1729
|
+
if (params.action == "read") {
|
|
1730
|
+
return await client.socket.updateReadReceiptsPrivacy(params.type);
|
|
1731
|
+
}
|
|
1732
|
+
if (params.action == "groupsAdd") {
|
|
1733
|
+
return await client.socket.updateGroupsAddPrivacy(params.type);
|
|
1734
|
+
}
|
|
1735
|
+
if (params.action == "ephemeral") {
|
|
1736
|
+
const opts = { remove: 0, "24h": 86400, "7d": 604800, "90d": 7776e3 };
|
|
1737
|
+
return await client.socket.updateDefaultDisappearingMode(opts[params.type]);
|
|
1738
|
+
}
|
|
1739
|
+
} catch (error) {
|
|
1740
|
+
client.spinner.error("Failed update privacy, please try again.\n\n" + error);
|
|
1741
|
+
return null;
|
|
1742
|
+
}
|
|
1743
|
+
};
|
|
1744
|
+
const fetch = {
|
|
1745
|
+
settings: async () => {
|
|
1746
|
+
return await client.socket.fetchPrivacySettings(true);
|
|
1747
|
+
},
|
|
1748
|
+
blocklists: async () => {
|
|
1749
|
+
return await client.socket.fetchBlocklist();
|
|
1750
|
+
}
|
|
1751
|
+
};
|
|
1752
|
+
return {
|
|
1753
|
+
update,
|
|
1754
|
+
fetch
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
// PROFILE RELAY
|
|
1758
|
+
profile() {
|
|
1759
|
+
const client = this.ctx;
|
|
1760
|
+
const bio = async (props) => {
|
|
1761
|
+
const params = RelayProfileBioType.parse(props);
|
|
1762
|
+
try {
|
|
1763
|
+
return await client.socket.fetchStatus(params.senderId);
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
client.spinner.error("Failed fetch profile bio. Make sure senderId is valid.\n\n" + error);
|
|
1766
|
+
return null;
|
|
1767
|
+
}
|
|
1768
|
+
};
|
|
1769
|
+
const avatar = async (props) => {
|
|
1770
|
+
const params = RelayProfileBioType.parse(props);
|
|
1771
|
+
try {
|
|
1772
|
+
return await client.socket.profilePictureUrl(params.senderId);
|
|
1773
|
+
} catch (error) {
|
|
1774
|
+
client.spinner.error("Failed fetch profile avatar. Make sure senderId is valid.\n\n" + error);
|
|
1775
|
+
return null;
|
|
1776
|
+
}
|
|
1777
|
+
};
|
|
1778
|
+
const business = async (props) => {
|
|
1779
|
+
const params = RelayProfileBioType.parse(props);
|
|
1780
|
+
try {
|
|
1781
|
+
return await client.socket.getBusinessProfile(params.senderId);
|
|
1782
|
+
} catch (error) {
|
|
1783
|
+
client.spinner.error("Failed fetch profile business. Make sure senderId is valid.\n\n" + error);
|
|
1784
|
+
return null;
|
|
1785
|
+
}
|
|
1786
|
+
};
|
|
1787
|
+
const update = async (props) => {
|
|
1788
|
+
const params = RelayProfileUpdateType.parse(props);
|
|
1789
|
+
try {
|
|
1790
|
+
if (params.type == "name") {
|
|
1791
|
+
return await client.socket.updateProfileName(params.text);
|
|
1792
|
+
}
|
|
1793
|
+
if (params.type == "bio") {
|
|
1794
|
+
return await client.socket.updateProfileStatus(params.text);
|
|
1795
|
+
}
|
|
1796
|
+
if (params.type == "avatar") {
|
|
1797
|
+
if (params.avatar == "remove") {
|
|
1798
|
+
return await client.socket.removeProfilePicture(params.roomId);
|
|
1799
|
+
}
|
|
1800
|
+
const avatar2 = typeof params.avatar == "string" ? { url: params.avatar } : params.avatar;
|
|
1801
|
+
return await client.socket.updateProfilePicture(params.roomId, avatar2);
|
|
1802
|
+
}
|
|
1803
|
+
} catch (error) {
|
|
1804
|
+
client.spinner.error("Failed update profile. Make sure senderId is valid.\n\n" + error);
|
|
1805
|
+
return null;
|
|
1806
|
+
}
|
|
1807
|
+
};
|
|
1808
|
+
const check = async (props) => {
|
|
1809
|
+
const params = RelayProfileCheckType.parse(props);
|
|
1810
|
+
try {
|
|
1811
|
+
const [wa] = await client.socket.onWhatsApp(params.senderId);
|
|
1812
|
+
if (!wa) return { isOnWhatsApp: false };
|
|
1813
|
+
const pic = await avatar({ senderId: wa.jid });
|
|
1814
|
+
const status = await bio({ senderId: wa.jid });
|
|
1815
|
+
const obj = {
|
|
1816
|
+
isOnWhatsApp: true,
|
|
1817
|
+
avatar: pic,
|
|
1818
|
+
bio: status,
|
|
1819
|
+
...wa
|
|
1820
|
+
};
|
|
1821
|
+
return obj;
|
|
1822
|
+
} catch (error) {
|
|
1823
|
+
client.spinner.error("Failed check profile. Make sure senderId is valid.\n\n" + error);
|
|
1824
|
+
return null;
|
|
1825
|
+
}
|
|
1826
|
+
};
|
|
1827
|
+
return {
|
|
1828
|
+
bio,
|
|
1829
|
+
avatar,
|
|
1830
|
+
business,
|
|
1831
|
+
update,
|
|
1832
|
+
check
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
};
|
|
1836
|
+
var Client = class {
|
|
1837
|
+
props;
|
|
1838
|
+
db;
|
|
1839
|
+
logger = pino({ level: "silent", enabled: false });
|
|
1840
|
+
events = new EventEmitter();
|
|
1841
|
+
relay;
|
|
1842
|
+
retryCount = 0;
|
|
1843
|
+
maxRetries = 10;
|
|
1844
|
+
connectionTimeout;
|
|
1845
|
+
spinner = createSpinner("", { color: "green" });
|
|
1846
|
+
socket;
|
|
1847
|
+
cache = new NodeCache2({ stdTTL: 5 * 60, useClones: false });
|
|
1848
|
+
constructor(props) {
|
|
1849
|
+
this.props = ClientOptionsType.parse(props);
|
|
1850
|
+
this.initialize();
|
|
1851
|
+
return new Proxy(this, {
|
|
1852
|
+
get(target, prop) {
|
|
1853
|
+
if (typeof prop === "string" && (prop in target || _2.includes(["on", "emit"], prop))) return target[prop];
|
|
1854
|
+
if (typeof prop === "string") return target.relay[prop];
|
|
1855
|
+
return void 0;
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1859
|
+
async initialize() {
|
|
1860
|
+
console.clear();
|
|
1861
|
+
await displayBanner();
|
|
1862
|
+
await delay(1e3);
|
|
1863
|
+
await this.spinner.start("Initializing database...");
|
|
1864
|
+
const { db, state, store, saveCreds } = await CredsHandler(this.props);
|
|
1865
|
+
await this.spinner.start("Fetching newest version...");
|
|
1866
|
+
const { version } = await fetchLatestBaileysVersion();
|
|
1867
|
+
this.socket = makeWASocket({
|
|
1868
|
+
version,
|
|
1869
|
+
logger: this.logger,
|
|
1870
|
+
markOnlineOnConnect: this.props.autoOnline,
|
|
1871
|
+
syncFullHistory: true,
|
|
1872
|
+
printQRInTerminal: false,
|
|
1873
|
+
defaultQueryTimeoutMs: void 0,
|
|
1874
|
+
msgRetryCounterCache: new NodeCache2(),
|
|
1875
|
+
mediaCache: new NodeCache2({ stdTTL: 60 }),
|
|
1876
|
+
userDevicesCache: new NodeCache2(),
|
|
1877
|
+
cachedGroupMetadata: async (jid) => this.cache.get(jid),
|
|
1878
|
+
auth: {
|
|
1879
|
+
creds: state.creds,
|
|
1880
|
+
keys: makeCacheableSignalKeyStore(state.keys, this.logger)
|
|
1881
|
+
},
|
|
1882
|
+
getMessage: async (key) => {
|
|
1883
|
+
if (!key?.id) return void 0;
|
|
1884
|
+
const message = await db.store("messages").read(key.id);
|
|
1885
|
+
return message;
|
|
1886
|
+
}
|
|
1887
|
+
});
|
|
1888
|
+
await this.socket?.ev.on("creds.update", saveCreds);
|
|
1889
|
+
if (this.props.authType === "pairing" && this.props.phoneNumber && !this.socket?.authState.creds.registered) {
|
|
1890
|
+
this.spinner.start("Generating pairing code...");
|
|
1891
|
+
setTimeout(async () => {
|
|
1892
|
+
try {
|
|
1893
|
+
if (this.props?.authType === "pairing") {
|
|
1894
|
+
const code = await this.socket?.requestPairingCode(this.props.phoneNumber.toString(), shuffleString("Z4D3V0FC"));
|
|
1895
|
+
this.spinner.info(`Pairing code: ${code}`);
|
|
1896
|
+
}
|
|
1897
|
+
} catch {
|
|
1898
|
+
this.spinner.error(`Session "${this.props.session}" has not valid, please delete it`);
|
|
1899
|
+
process.exit(0);
|
|
1900
|
+
}
|
|
1901
|
+
}, 5e3);
|
|
1902
|
+
}
|
|
1903
|
+
const listener = new Listener();
|
|
1904
|
+
this.relay = new Relay();
|
|
1905
|
+
this.spinner.success("Initialize Successfully");
|
|
1906
|
+
await store.bind(this);
|
|
1907
|
+
await listener.bind(this, db);
|
|
1908
|
+
await this.relay.bind(this, db);
|
|
1909
|
+
this.spinner.start("Connecting to WhatsApp...");
|
|
1910
|
+
this.startConnectionTimeout();
|
|
1911
|
+
}
|
|
1912
|
+
startConnectionTimeout() {
|
|
1913
|
+
if (this.connectionTimeout) {
|
|
1914
|
+
clearTimeout(this.connectionTimeout);
|
|
1915
|
+
}
|
|
1916
|
+
this.connectionTimeout = setTimeout(() => {
|
|
1917
|
+
this.handleConnectionTimeout();
|
|
1918
|
+
}, 6e4);
|
|
1919
|
+
}
|
|
1920
|
+
handleConnectionTimeout() {
|
|
1921
|
+
if (this.retryCount < this.maxRetries) {
|
|
1922
|
+
this.retryCount++;
|
|
1923
|
+
this.spinner.warn(`Connection timeout. Retrying... (${this.retryCount}/${this.maxRetries})`);
|
|
1924
|
+
this.autoReload();
|
|
1925
|
+
} else {
|
|
1926
|
+
this.spinner.error(`Max retries reached (${this.maxRetries}). Connection failed.`);
|
|
1927
|
+
process.exit(1);
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
async autoReload() {
|
|
1931
|
+
try {
|
|
1932
|
+
if (this.connectionTimeout) {
|
|
1933
|
+
clearTimeout(this.connectionTimeout);
|
|
1934
|
+
}
|
|
1935
|
+
if (this.socket) {
|
|
1936
|
+
this.socket.end?.(void 0);
|
|
1937
|
+
this.socket = void 0;
|
|
1938
|
+
}
|
|
1939
|
+
await delay(2e3);
|
|
1940
|
+
await this.initialize();
|
|
1941
|
+
} catch (error) {
|
|
1942
|
+
this.spinner.error(`Auto-reload failed: ${error.message}`);
|
|
1943
|
+
this.handleConnectionTimeout();
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
resetRetryCount() {
|
|
1947
|
+
this.retryCount = 0;
|
|
1948
|
+
if (this.connectionTimeout) {
|
|
1949
|
+
clearTimeout(this.connectionTimeout);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
on(event, handler) {
|
|
1953
|
+
this.events.on(event, handler);
|
|
1954
|
+
}
|
|
1955
|
+
emit(event, ...args) {
|
|
1956
|
+
this.events.emit(event, ...args);
|
|
1957
|
+
}
|
|
1958
|
+
};
|
|
1959
|
+
|
|
1960
|
+
export { CitationType, Client, ClientAuthPairingType, ClientAuthQRType, ClientBaseType, ClientOptionsType, EventEnumType, FakeReplyType, JsonDB, LimiterType, PluginsType };
|