orc-ai 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +163 -179
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var bV=Object.create;var{getPrototypeOf:ZV,defineProperty:wG,getOwnPropertyNames:kO,getOwnPropertyDescriptor:CV}=Object,bO=Object.prototype.hasOwnProperty;function ZO($){return this[$]}var _V,vV,DJ=($,w,E)=>{var X=$!=null&&typeof $==="object";if(X){var G=w?_V??=new WeakMap:vV??=new WeakMap,J=G.get($);if(J)return J}E=$!=null?bV(ZV($)):{};let A=w||!$||!$.__esModule?wG(E,"default",{value:$,enumerable:!0}):E;for(let D of kO($))if(!bO.call(A,D))wG(A,D,{get:ZO.bind($,D),enumerable:!0});if(X)G.set($,A);return A},CO=($)=>{var w=(SO??=new WeakMap).get($),E;if(w)return w;if(w=wG({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of kO($))if(!bO.call(w,X))wG(w,X,{get:ZO.bind($,X),enumerable:!(E=CV($,X))||E.enumerable})}return SO.set($,w),w},SO,Z=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var fV=($)=>$;function xV($,w){this[$]=fV.bind(null,w)}var Ww=($,w)=>{for(var E in w)wG($,E,{get:w[E],enumerable:!0,configurable:!0,set:xV.bind(w,E)})};var R=($,w)=>()=>($&&(w=$($=0)),w);var V$=import.meta.require;var Y0,QD,f,o1=($)=>{switch(typeof $){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN($)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray($))return f.array;if($===null)return f.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return f.promise;if(typeof Map<"u"&&$ instanceof Map)return f.map;if(typeof Set<"u"&&$ instanceof Set)return f.set;if(typeof Date<"u"&&$ instanceof Date)return f.date;return f.object;default:return f.unknown}};var EG=R(()=>{(function($){$.assertEqual=(G)=>{};function w(G){}$.assertIs=w;function E(G){throw Error()}$.assertNever=E,$.arrayToEnum=(G)=>{let J={};for(let A of G)J[A]=A;return J},$.getValidEnumValues=(G)=>{let J=$.objectKeys(G).filter((D)=>typeof G[G[D]]!=="number"),A={};for(let D of J)A[D]=G[D];return $.objectValues(A)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(J){return G[J]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let J=[];for(let A in G)if(Object.prototype.hasOwnProperty.call(G,A))J.push(A);return J},$.find=(G,J)=>{for(let A of G)if(J(A))return A;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function X(G,J=" | "){return G.map((A)=>typeof A==="string"?`'${A}'`:A).join(J)}$.joinValues=X,$.jsonStringifyReplacer=(G,J)=>{if(typeof J==="bigint")return J.toString();return J}})(Y0||(Y0={}));(function($){$.mergeShapes=(w,E)=>{return{...w,...E}}})(QD||(QD={}));f=Y0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var _,yV=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")},r$;var NJ=R(()=>{EG();_=Y0.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"]);r$=class r$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(E)=>{this.issues=[...this.issues,E]},this.addIssues=(E=[])=>{this.issues=[...this.issues,...E]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=$}format($){let w=$||function(G){return G.message},E={_errors:[]},X=(G)=>{for(let J of G.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)E._errors.push(w(J));else{let A=E,D=0;while(D<J.path.length){let N=J.path[D];if(D!==J.path.length-1)A[N]=A[N]||{_errors:[]};else A[N]=A[N]||{_errors:[]},A[N]._errors.push(w(J));A=A[N],D++}}};return X(this),E}static assert($){if(!($ instanceof r$))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(w)=>w.message){let w={},E=[];for(let X of this.issues)if(X.path.length>0){let G=X.path[0];w[G]=w[G]||[],w[G].push($(X))}else E.push($(X));return{formErrors:E,fieldErrors:w}}get formErrors(){return this.flatten()}};r$.create=($)=>{return new r$($)}});var gV=($,w)=>{let E;switch($.code){case _.invalid_type:if($.received===f.undefined)E="Required";else E=`Expected ${$.expected}, received ${$.received}`;break;case _.invalid_literal:E=`Invalid literal value, expected ${JSON.stringify($.expected,Y0.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:E=`Unrecognized key(s) in object: ${Y0.joinValues($.keys,", ")}`;break;case _.invalid_union:E="Invalid input";break;case _.invalid_union_discriminator:E=`Invalid discriminator value. Expected ${Y0.joinValues($.options)}`;break;case _.invalid_enum_value:E=`Invalid enum value. Expected ${Y0.joinValues($.options)}, received '${$.received}'`;break;case _.invalid_arguments:E="Invalid function arguments";break;case _.invalid_return_type:E="Invalid function return type";break;case _.invalid_date:E="Invalid date";break;case _.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(E=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")E=`${E} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)E=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)E=`Invalid input: must end with "${$.validation.endsWith}"`;else Y0.assertNever($.validation);else if($.validation!=="regex")E=`Invalid ${$.validation}`;else E="Invalid";break;case _.too_small:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else E="Invalid input";break;case _.too_big:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")E=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else E="Invalid input";break;case _.custom:E="Invalid input";break;case _.invalid_intersection_types:E="Intersection results could not be merged";break;case _.not_multiple_of:E=`Number must be a multiple of ${$.multipleOf}`;break;case _.not_finite:E="Number must be finite";break;default:E=w.defaultError,Y0.assertNever($)}return{message:E}},Ow;var ID=R(()=>{NJ();EG();Ow=gV});function uV($){_O=$}function fE(){return _O}var _O;var WJ=R(()=>{ID();_O=Ow});function g($,w){let E=fE(),X=XG({issueData:w,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,E,E===Ow?void 0:Ow].filter((G)=>!!G)});$.common.issues.push(X)}class j${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,w){let E=[];for(let X of w){if(X.status==="aborted")return d;if(X.status==="dirty")$.dirty();E.push(X.value)}return{status:$.value,value:E}}static async mergeObjectAsync($,w){let E=[];for(let X of w){let G=await X.key,J=await X.value;E.push({key:G,value:J})}return j$.mergeObjectSync($,E)}static mergeObjectSync($,w){let E={};for(let X of w){let{key:G,value:J}=X;if(G.status==="aborted")return d;if(J.status==="aborted")return d;if(G.status==="dirty")$.dirty();if(J.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))E[G.value]=J.value}return{status:$.value,value:E}}}var XG=($)=>{let{data:w,path:E,errorMaps:X,issueData:G}=$,J=[...E,...G.path||[]],A={...G,path:J};if(G.message!==void 0)return{...G,path:J,message:G.message};let D="",N=X.filter((W)=>!!W).slice().reverse();for(let W of N)D=W(A,{data:w,defaultError:D}).message;return{...G,path:J,message:D}},hV,d,AE=($)=>({status:"dirty",value:$}),P$=($)=>({status:"valid",value:$}),OJ=($)=>$.status==="aborted",UJ=($)=>$.status==="dirty",Zw=($)=>$.status==="valid",xE=($)=>typeof Promise<"u"&&$ instanceof Promise;var KD=R(()=>{WJ();ID();hV=[];d=Object.freeze({status:"aborted"})});var vO=()=>{};var c;var fO=R(()=>{(function($){$.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},$.toString=(w)=>typeof w==="string"?w:w?.message})(c||(c={}))});class S1{constructor($,w,E,X){this._cachedPath=[],this.parent=$,this.data=w,this._path=E,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function X0($){if(!$)return{};let{errorMap:w,invalid_type_error:E,required_error:X,description:G}=$;if(w&&(E||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:G};return{errorMap:(A,D)=>{let{message:N}=$;if(A.code==="invalid_enum_value")return{message:N??D.defaultError};if(typeof D.data>"u")return{message:N??X??D.defaultError};if(A.code!=="invalid_type")return{message:D.defaultError};return{message:N??E??D.defaultError}},description:G}}class G0{get description(){return this._def.description}_getType($){return o1($.data)}_getOrReturnCtx($,w){return w||{common:$.parent.common,data:$.data,parsedType:o1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new j$,ctx:{common:$.parent.common,data:$.data,parsedType:o1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let w=this._parse($);if(xE(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync($){let w=this._parse($);return Promise.resolve(w)}parse($,w){let E=this.safeParse($,w);if(E.success)return E.data;throw E.error}safeParse($,w){let E={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)},X=this._parseSync({data:$,path:E.path,parent:E});return xO(E,X)}"~validate"($){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)};if(!this["~standard"].async)try{let E=this._parseSync({data:$,path:[],parent:w});return Zw(E)?{value:E.value}:{issues:w.common.issues}}catch(E){if(E?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:w}).then((E)=>Zw(E)?{value:E.value}:{issues:w.common.issues})}async parseAsync($,w){let E=await this.safeParseAsync($,w);if(E.success)return E.data;throw E.error}async safeParseAsync($,w){let E={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)},X=this._parse({data:$,path:E.path,parent:E}),G=await(xE(X)?X:Promise.resolve(X));return xO(E,G)}refine($,w){let E=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,G)=>{let J=$(X),A=()=>G.addIssue({code:_.custom,...E(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((D)=>{if(!D)return A(),!1;else return!0});if(!J)return A(),!1;else return!0})}refinement($,w){return this._refinement((E,X)=>{if(!$(E))return X.addIssue(typeof w==="function"?w(E,X):w),!1;else return!0})}_refinement($){return new k1({schema:this,typeName:a.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(w)=>this["~validate"](w)}}optional(){return q1.create(this,this._def)}nullable(){return Yw.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return P1.create(this)}promise(){return OE.create(this,this._def)}or($){return nE.create([this,$],this._def)}and($){return mE.create(this,$,this._def)}transform($){return new k1({...X0(this._def),schema:this,typeName:a.ZodEffects,effect:{type:"transform",transform:$}})}default($){let w=typeof $==="function"?$:()=>$;return new tE({...X0(this._def),innerType:this,defaultValue:w,typeName:a.ZodDefault})}brand(){return new HJ({typeName:a.ZodBranded,type:this,...X0(this._def)})}catch($){let w=typeof $==="function"?$:()=>$;return new iE({...X0(this._def),innerType:this,catchValue:w,typeName:a.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return WG.create(this,$)}readonly(){return dE.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function uO($){let w="[0-5]\\d";if($.precision)w=`${w}\\.\\d{${$.precision}}`;else if($.precision==null)w=`${w}(\\.\\d+)?`;let E=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${E}`}function XP($){return new RegExp(`^${uO($)}$`)}function hO($){let w=`${gO}T${uO($)}`,E=[];if(E.push($.local?"Z?":"Z"),$.offset)E.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${E.join("|")})`,new RegExp(`^${w}$`)}function GP($,w){if((w==="v4"||!w)&&lV.test($))return!0;if((w==="v6"||!w)&&aV.test($))return!0;return!1}function JP($,w){if(!oV.test($))return!1;try{let[E]=$.split(".");if(!E)return!1;let X=E.replace(/-/g,"+").replace(/_/g,"/").padEnd(E.length+(4-E.length%4)%4,"="),G=JSON.parse(atob(X));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&G.alg!==w)return!1;return!0}catch{return!1}}function AP($,w){if((w==="v4"||!w)&&sV.test($))return!0;if((w==="v6"||!w)&&eV.test($))return!0;return!1}function DP($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,J=Number.parseInt($.toFixed(G).replace(".","")),A=Number.parseInt(w.toFixed(G).replace(".",""));return J%A/10**G}function yE($){if($ instanceof l0){let w={};for(let E in $.shape){let X=$.shape[E];w[E]=q1.create(yE(X))}return new l0({...$._def,shape:()=>w})}else if($ instanceof P1)return new P1({...$._def,type:yE($.element)});else if($ instanceof q1)return q1.create(yE($.unwrap()));else if($ instanceof Yw)return Yw.create(yE($.unwrap()));else if($ instanceof i1)return i1.create($.items.map((w)=>yE(w)));else return $}function PD($,w){let E=o1($),X=o1(w);if($===w)return{valid:!0,data:$};else if(E===f.object&&X===f.object){let G=Y0.objectKeys(w),J=Y0.objectKeys($).filter((D)=>G.indexOf(D)!==-1),A={...$,...w};for(let D of J){let N=PD($[D],w[D]);if(!N.valid)return{valid:!1};A[D]=N.data}return{valid:!0,data:A}}else if(E===f.array&&X===f.array){if($.length!==w.length)return{valid:!1};let G=[];for(let J=0;J<$.length;J++){let A=$[J],D=w[J],N=PD(A,D);if(!N.valid)return{valid:!1};G.push(N.data)}return{valid:!0,data:G}}else if(E===f.date&&X===f.date&&+$===+w)return{valid:!0,data:$};else return{valid:!1}}function cO($,w){return new fw({values:$,typeName:a.ZodEnum,...X0(w)})}function yO($,w){let E=typeof $==="function"?$(w):typeof $==="string"?{message:$}:$;return typeof E==="string"?{message:E}:E}function nO($,w={},E){if($)return NE.create().superRefine((X,G)=>{let J=$(X);if(J instanceof Promise)return J.then((A)=>{if(!A){let D=yO(w,X),N=D.fatal??E??!0;G.addIssue({code:"custom",...D,fatal:N})}});if(!J){let A=yO(w,X),D=A.fatal??E??!0;G.addIssue({code:"custom",...A,fatal:D})}return});return NE.create()}var xO=($,w)=>{if(Zw(w))return{success:!0,data:w.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let E=new r$($.common.issues);return this._error=E,this._error}}}},cV,nV,mV,rV,pV,oV,tV,iV,dV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",VD,lV,sV,aV,eV,$P,wP,gO="((\\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])))",EP,V1,_w,vw,uE,DE,GG,hE,cE,NE,Cw,t1,JG,P1,l0,nE,Uw=($)=>{if($ instanceof rE)return Uw($.schema);else if($ instanceof k1)return Uw($.innerType());else if($ instanceof pE)return[$.value];else if($ instanceof fw)return $.options;else if($ instanceof oE)return Y0.objectValues($.enum);else if($ instanceof tE)return Uw($._def.innerType);else if($ instanceof hE)return[void 0];else if($ instanceof cE)return[null];else if($ instanceof q1)return[void 0,...Uw($.unwrap())];else if($ instanceof Yw)return[null,...Uw($.unwrap())];else if($ instanceof HJ)return Uw($.unwrap());else if($ instanceof dE)return Uw($.unwrap());else if($ instanceof iE)return Uw($._def.innerType);else return[]},YJ,mE,i1,AG,DG,WE,gE,rE,pE,fw,oE,OE,k1,q1,Yw,tE,iE,NG,NP,HJ,WG,dE,WP,a,OP=($,w={message:`Input not instance of ${$.name}`})=>nO((E)=>E instanceof $,w),mO,rO,UP,YP,pO,HP,LP,FP,jP,MP,RP,zP,TP,BP,QP,IP,KP,VP,PP,qP,SP,kP,bP,ZP,CP,_P,vP,fP,xP,yP,gP,uP,hP,cP,nP=()=>mO().optional(),mP=()=>rO().optional(),rP=()=>pO().optional(),pP,oP;var oO=R(()=>{NJ();WJ();fO();KD();EG();cV=/^c[^\s-]{8,}$/i,nV=/^[0-9a-z]+$/,mV=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rV=/^[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,pV=/^[a-z0-9_-]{21}$/i,oV=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tV=/^[-+]?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)?)??$/,iV=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lV=/^(?:(?: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])$/,sV=/^(?:(?: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])$/,aV=/^(([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]))$/,eV=/^(([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])$/,$P=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wP=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,EP=new RegExp(`^${gO}$`);V1=class V1 extends G0{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==f.string){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.string,received:G.parsedType}),d}let E=new j$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="max"){if($.data.length>G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="length"){let J=$.data.length>G.value,A=$.data.length<G.value;if(J||A){if(X=this._getOrReturnCtx($,X),J)g(X,{code:_.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(A)g(X,{code:_.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});E.dirty()}}else if(G.kind==="email"){if(!iV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"email",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="emoji"){if(!VD)VD=new RegExp(dV,"u");if(!VD.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"emoji",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="uuid"){if(!rV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"uuid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="nanoid"){if(!pV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"nanoid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid"){if(!cV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid2"){if(!nV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid2",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ulid"){if(!mV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"ulid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),g(X,{validation:"url",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"regex",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),E.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{startsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{endsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="datetime"){if(!hO(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"datetime",message:G.message}),E.dirty()}else if(G.kind==="date"){if(!EP.test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"date",message:G.message}),E.dirty()}else if(G.kind==="time"){if(!XP(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"time",message:G.message}),E.dirty()}else if(G.kind==="duration"){if(!tV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"duration",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ip"){if(!GP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"ip",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="jwt"){if(!JP($.data,G.alg))X=this._getOrReturnCtx($,X),g(X,{validation:"jwt",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cidr"){if(!AP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"cidr",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64"){if(!$P.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64url"){if(!wP.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64url",code:_.invalid_string,message:G.message}),E.dirty()}else Y0.assertNever(G);return{status:E.value,value:$.data}}_regex($,w,E){return this.refinement((X)=>$.test(X),{validation:w,code:_.invalid_string,...c.errToObj(E)})}_addCheck($){return new V1({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...c.errToObj($)})}url($){return this._addCheck({kind:"url",...c.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...c.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...c.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...c.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...c.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...c.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...c.errToObj($)})}base64($){return this._addCheck({kind:"base64",...c.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...c.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...c.errToObj($)})}ip($){return this._addCheck({kind:"ip",...c.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...c.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...c.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...c.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...c.errToObj($)})}regex($,w){return this._addCheck({kind:"regex",regex:$,...c.errToObj(w)})}includes($,w){return this._addCheck({kind:"includes",value:$,position:w?.position,...c.errToObj(w?.message)})}startsWith($,w){return this._addCheck({kind:"startsWith",value:$,...c.errToObj(w)})}endsWith($,w){return this._addCheck({kind:"endsWith",value:$,...c.errToObj(w)})}min($,w){return this._addCheck({kind:"min",value:$,...c.errToObj(w)})}max($,w){return this._addCheck({kind:"max",value:$,...c.errToObj(w)})}length($,w){return this._addCheck({kind:"length",value:$,...c.errToObj(w)})}nonempty($){return this.min(1,c.errToObj($))}trim(){return new V1({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new V1({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new V1({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxLength(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};V1.create=($)=>{return new V1({checks:[],typeName:a.ZodString,coerce:$?.coerce??!1,...X0($)})};_w=class _w extends G0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==f.number){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.number,received:G.parsedType}),d}let E=void 0,X=new j$;for(let G of this._def.checks)if(G.kind==="int"){if(!Y0.isInteger($.data))E=this._getOrReturnCtx($,E),g(E,{code:_.invalid_type,expected:"integer",received:"float",message:G.message}),X.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if(DP($.data,G.value)!==0)E=this._getOrReturnCtx($,E),g(E,{code:_.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))E=this._getOrReturnCtx($,E),g(E,{code:_.not_finite,message:G.message}),X.dirty()}else Y0.assertNever(G);return{status:X.value,value:$.data}}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new _w({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new _w({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:c.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}finite($){return this._addCheck({kind:"finite",message:c.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:c.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:c.toString($)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&Y0.isInteger($.value))}get isFinite(){let $=null,w=null;for(let E of this._def.checks)if(E.kind==="finite"||E.kind==="int"||E.kind==="multipleOf")return!0;else if(E.kind==="min"){if(w===null||E.value>w)w=E.value}else if(E.kind==="max"){if($===null||E.value<$)$=E.value}return Number.isFinite(w)&&Number.isFinite($)}};_w.create=($)=>{return new _w({checks:[],typeName:a.ZodNumber,coerce:$?.coerce||!1,...X0($)})};vw=class vw extends G0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==f.bigint)return this._getInvalidInput($);let E=void 0,X=new j$;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))E=this._getOrReturnCtx($,E),g(E,{code:_.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else Y0.assertNever(G);return{status:X.value,value:$.data}}_getInvalidInput($){let w=this._getOrReturnCtx($);return g(w,{code:_.invalid_type,expected:f.bigint,received:w.parsedType}),d}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new vw({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new vw({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};vw.create=($)=>{return new vw({checks:[],typeName:a.ZodBigInt,coerce:$?.coerce??!1,...X0($)})};uE=class uE extends G0{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==f.boolean){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.boolean,received:E.parsedType}),d}return P$($.data)}};uE.create=($)=>{return new uE({typeName:a.ZodBoolean,coerce:$?.coerce||!1,...X0($)})};DE=class DE extends G0{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==f.date){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.date,received:G.parsedType}),d}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_date}),d}let E=new j$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),E.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),E.dirty()}else Y0.assertNever(G);return{status:E.value,value:new Date($.data.getTime())}}_addCheck($){return new DE({...this._def,checks:[...this._def.checks,$]})}min($,w){return this._addCheck({kind:"min",value:$.getTime(),message:c.toString(w)})}max($,w){return this._addCheck({kind:"max",value:$.getTime(),message:c.toString(w)})}get minDate(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $!=null?new Date($):null}};DE.create=($)=>{return new DE({checks:[],coerce:$?.coerce||!1,typeName:a.ZodDate,...X0($)})};GG=class GG extends G0{_parse($){if(this._getType($)!==f.symbol){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.symbol,received:E.parsedType}),d}return P$($.data)}};GG.create=($)=>{return new GG({typeName:a.ZodSymbol,...X0($)})};hE=class hE extends G0{_parse($){if(this._getType($)!==f.undefined){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.undefined,received:E.parsedType}),d}return P$($.data)}};hE.create=($)=>{return new hE({typeName:a.ZodUndefined,...X0($)})};cE=class cE extends G0{_parse($){if(this._getType($)!==f.null){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.null,received:E.parsedType}),d}return P$($.data)}};cE.create=($)=>{return new cE({typeName:a.ZodNull,...X0($)})};NE=class NE extends G0{constructor(){super(...arguments);this._any=!0}_parse($){return P$($.data)}};NE.create=($)=>{return new NE({typeName:a.ZodAny,...X0($)})};Cw=class Cw extends G0{constructor(){super(...arguments);this._unknown=!0}_parse($){return P$($.data)}};Cw.create=($)=>{return new Cw({typeName:a.ZodUnknown,...X0($)})};t1=class t1 extends G0{_parse($){let w=this._getOrReturnCtx($);return g(w,{code:_.invalid_type,expected:f.never,received:w.parsedType}),d}};t1.create=($)=>{return new t1({typeName:a.ZodNever,...X0($)})};JG=class JG extends G0{_parse($){if(this._getType($)!==f.undefined){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.void,received:E.parsedType}),d}return P$($.data)}};JG.create=($)=>{return new JG({typeName:a.ZodVoid,...X0($)})};P1=class P1 extends G0{_parse($){let{ctx:w,status:E}=this._processInputParams($),X=this._def;if(w.parsedType!==f.array)return g(w,{code:_.invalid_type,expected:f.array,received:w.parsedType}),d;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,A=w.data.length<X.exactLength.value;if(J||A)g(w,{code:J?_.too_big:_.too_small,minimum:A?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),E.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)g(w,{code:_.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),E.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)g(w,{code:_.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),E.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,A)=>{return X.type._parseAsync(new S1(w,J,w.path,A))})).then((J)=>{return j$.mergeArray(E,J)});let G=[...w.data].map((J,A)=>{return X.type._parseSync(new S1(w,J,w.path,A))});return j$.mergeArray(E,G)}get element(){return this._def.type}min($,w){return new P1({...this._def,minLength:{value:$,message:c.toString(w)}})}max($,w){return new P1({...this._def,maxLength:{value:$,message:c.toString(w)}})}length($,w){return new P1({...this._def,exactLength:{value:$,message:c.toString(w)}})}nonempty($){return this.min(1,$)}};P1.create=($,w)=>{return new P1({type:$,minLength:null,maxLength:null,exactLength:null,typeName:a.ZodArray,...X0(w)})};l0=class l0 extends G0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),w=Y0.objectKeys($);return this._cached={shape:$,keys:w},this._cached}_parse($){if(this._getType($)!==f.object){let N=this._getOrReturnCtx($);return g(N,{code:_.invalid_type,expected:f.object,received:N.parsedType}),d}let{status:E,ctx:X}=this._processInputParams($),{shape:G,keys:J}=this._getCached(),A=[];if(!(this._def.catchall instanceof t1&&this._def.unknownKeys==="strip")){for(let N in X.data)if(!J.includes(N))A.push(N)}let D=[];for(let N of J){let W=G[N],O=X.data[N];D.push({key:{status:"valid",value:N},value:W._parse(new S1(X,O,X.path,N)),alwaysSet:N in X.data})}if(this._def.catchall instanceof t1){let N=this._def.unknownKeys;if(N==="passthrough")for(let W of A)D.push({key:{status:"valid",value:W},value:{status:"valid",value:X.data[W]}});else if(N==="strict"){if(A.length>0)g(X,{code:_.unrecognized_keys,keys:A}),E.dirty()}else if(N==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let N=this._def.catchall;for(let W of A){let O=X.data[W];D.push({key:{status:"valid",value:W},value:N._parse(new S1(X,O,X.path,W)),alwaysSet:W in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let N=[];for(let W of D){let O=await W.key,Y=await W.value;N.push({key:O,value:Y,alwaysSet:W.alwaysSet})}return N}).then((N)=>{return j$.mergeObjectSync(E,N)});else return j$.mergeObjectSync(E,D)}get shape(){return this._def.shape()}strict($){return c.errToObj,new l0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(w,E)=>{let X=this._def.errorMap?.(w,E).message??E.defaultError;if(w.code==="unrecognized_keys")return{message:c.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new l0({...this._def,unknownKeys:"strip"})}passthrough(){return new l0({...this._def,unknownKeys:"passthrough"})}extend($){return new l0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new l0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:a.ZodObject})}setKey($,w){return this.augment({[$]:w})}catchall($){return new l0({...this._def,catchall:$})}pick($){let w={};for(let E of Y0.objectKeys($))if($[E]&&this.shape[E])w[E]=this.shape[E];return new l0({...this._def,shape:()=>w})}omit($){let w={};for(let E of Y0.objectKeys(this.shape))if(!$[E])w[E]=this.shape[E];return new l0({...this._def,shape:()=>w})}deepPartial(){return yE(this)}partial($){let w={};for(let E of Y0.objectKeys(this.shape)){let X=this.shape[E];if($&&!$[E])w[E]=X;else w[E]=X.optional()}return new l0({...this._def,shape:()=>w})}required($){let w={};for(let E of Y0.objectKeys(this.shape))if($&&!$[E])w[E]=this.shape[E];else{let G=this.shape[E];while(G instanceof q1)G=G._def.innerType;w[E]=G}return new l0({...this._def,shape:()=>w})}keyof(){return cO(Y0.objectKeys(this.shape))}};l0.create=($,w)=>{return new l0({shape:()=>$,unknownKeys:"strip",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};l0.strictCreate=($,w)=>{return new l0({shape:()=>$,unknownKeys:"strict",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};l0.lazycreate=($,w)=>{return new l0({shape:$,unknownKeys:"strip",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};nE=class nE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=this._def.options;function X(G){for(let A of G)if(A.result.status==="valid")return A.result;for(let A of G)if(A.result.status==="dirty")return w.common.issues.push(...A.ctx.common.issues),A.result;let J=G.map((A)=>new r$(A.ctx.common.issues));return g(w,{code:_.invalid_union,unionErrors:J}),d}if(w.common.async)return Promise.all(E.map(async(G)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await G._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let G=void 0,J=[];for(let D of E){let N={...w,common:{...w.common,issues:[]},parent:null},W=D._parseSync({data:w.data,path:w.path,parent:N});if(W.status==="valid")return W;else if(W.status==="dirty"&&!G)G={result:W,ctx:N};if(N.common.issues.length)J.push(N.common.issues)}if(G)return w.common.issues.push(...G.ctx.common.issues),G.result;let A=J.map((D)=>new r$(D));return g(w,{code:_.invalid_union,unionErrors:A}),d}}get options(){return this._def.options}};nE.create=($,w)=>{return new nE({options:$,typeName:a.ZodUnion,...X0(w)})};YJ=class YJ extends G0{_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.object)return g(w,{code:_.invalid_type,expected:f.object,received:w.parsedType}),d;let E=this.discriminator,X=w.data[E],G=this.optionsMap.get(X);if(!G)return g(w,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[E]}),d;if(w.common.async)return G._parseAsync({data:w.data,path:w.path,parent:w});else return G._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,w,E){let X=new Map;for(let G of w){let J=Uw(G.shape[$]);if(!J.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let A of J){if(X.has(A))throw Error(`Discriminator property ${String($)} has duplicate value ${String(A)}`);X.set(A,G)}}return new YJ({typeName:a.ZodDiscriminatedUnion,discriminator:$,options:w,optionsMap:X,...X0(E)})}};mE=class mE extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($),X=(G,J)=>{if(OJ(G)||OJ(J))return d;let A=PD(G.value,J.value);if(!A.valid)return g(E,{code:_.invalid_intersection_types}),d;if(UJ(G)||UJ(J))w.dirty();return{status:w.value,value:A.data}};if(E.common.async)return Promise.all([this._def.left._parseAsync({data:E.data,path:E.path,parent:E}),this._def.right._parseAsync({data:E.data,path:E.path,parent:E})]).then(([G,J])=>X(G,J));else return X(this._def.left._parseSync({data:E.data,path:E.path,parent:E}),this._def.right._parseSync({data:E.data,path:E.path,parent:E}))}};mE.create=($,w,E)=>{return new mE({left:$,right:w,typeName:a.ZodIntersection,...X0(E)})};i1=class i1 extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.array)return g(E,{code:_.invalid_type,expected:f.array,received:E.parsedType}),d;if(E.data.length<this._def.items.length)return g(E,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&E.data.length>this._def.items.length)g(E,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let G=[...E.data].map((J,A)=>{let D=this._def.items[A]||this._def.rest;if(!D)return null;return D._parse(new S1(E,J,E.path,A))}).filter((J)=>!!J);if(E.common.async)return Promise.all(G).then((J)=>{return j$.mergeArray(w,J)});else return j$.mergeArray(w,G)}get items(){return this._def.items}rest($){return new i1({...this._def,rest:$})}};i1.create=($,w)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new i1({items:$,typeName:a.ZodTuple,rest:null,...X0(w)})};AG=class AG extends G0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.object)return g(E,{code:_.invalid_type,expected:f.object,received:E.parsedType}),d;let X=[],G=this._def.keyType,J=this._def.valueType;for(let A in E.data)X.push({key:G._parse(new S1(E,A,E.path,A)),value:J._parse(new S1(E,E.data[A],E.path,A)),alwaysSet:A in E.data});if(E.common.async)return j$.mergeObjectAsync(w,X);else return j$.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create($,w,E){if(w instanceof G0)return new AG({keyType:$,valueType:w,typeName:a.ZodRecord,...X0(E)});return new AG({keyType:V1.create(),valueType:$,typeName:a.ZodRecord,...X0(w)})}};DG=class DG extends G0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.map)return g(E,{code:_.invalid_type,expected:f.map,received:E.parsedType}),d;let X=this._def.keyType,G=this._def.valueType,J=[...E.data.entries()].map(([A,D],N)=>{return{key:X._parse(new S1(E,A,E.path,[N,"key"])),value:G._parse(new S1(E,D,E.path,[N,"value"]))}});if(E.common.async){let A=new Map;return Promise.resolve().then(async()=>{for(let D of J){let N=await D.key,W=await D.value;if(N.status==="aborted"||W.status==="aborted")return d;if(N.status==="dirty"||W.status==="dirty")w.dirty();A.set(N.value,W.value)}return{status:w.value,value:A}})}else{let A=new Map;for(let D of J){let{key:N,value:W}=D;if(N.status==="aborted"||W.status==="aborted")return d;if(N.status==="dirty"||W.status==="dirty")w.dirty();A.set(N.value,W.value)}return{status:w.value,value:A}}}};DG.create=($,w,E)=>{return new DG({valueType:w,keyType:$,typeName:a.ZodMap,...X0(E)})};WE=class WE extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.set)return g(E,{code:_.invalid_type,expected:f.set,received:E.parsedType}),d;let X=this._def;if(X.minSize!==null){if(E.data.size<X.minSize.value)g(E,{code:_.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if(E.data.size>X.maxSize.value)g(E,{code:_.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let G=this._def.valueType;function J(D){let N=new Set;for(let W of D){if(W.status==="aborted")return d;if(W.status==="dirty")w.dirty();N.add(W.value)}return{status:w.value,value:N}}let A=[...E.data.values()].map((D,N)=>G._parse(new S1(E,D,E.path,N)));if(E.common.async)return Promise.all(A).then((D)=>J(D));else return J(A)}min($,w){return new WE({...this._def,minSize:{value:$,message:c.toString(w)}})}max($,w){return new WE({...this._def,maxSize:{value:$,message:c.toString(w)}})}size($,w){return this.min($,w).max($,w)}nonempty($){return this.min(1,$)}};WE.create=($,w)=>{return new WE({valueType:$,minSize:null,maxSize:null,typeName:a.ZodSet,...X0(w)})};gE=class gE extends G0{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.function)return g(w,{code:_.invalid_type,expected:f.function,received:w.parsedType}),d;function E(A,D){return XG({data:A,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,fE(),Ow].filter((N)=>!!N),issueData:{code:_.invalid_arguments,argumentsError:D}})}function X(A,D){return XG({data:A,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,fE(),Ow].filter((N)=>!!N),issueData:{code:_.invalid_return_type,returnTypeError:D}})}let G={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof OE){let A=this;return P$(async function(...D){let N=new r$([]),W=await A._def.args.parseAsync(D,G).catch((H)=>{throw N.addIssue(E(D,H)),N}),O=await Reflect.apply(J,this,W);return await A._def.returns._def.type.parseAsync(O,G).catch((H)=>{throw N.addIssue(X(O,H)),N})})}else{let A=this;return P$(function(...D){let N=A._def.args.safeParse(D,G);if(!N.success)throw new r$([E(D,N.error)]);let W=Reflect.apply(J,this,N.data),O=A._def.returns.safeParse(W,G);if(!O.success)throw new r$([X(W,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new gE({...this._def,args:i1.create($).rest(Cw.create())})}returns($){return new gE({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,w,E){return new gE({args:$?$:i1.create([]).rest(Cw.create()),returns:w||Cw.create(),typeName:a.ZodFunction,...X0(E)})}};rE=class rE extends G0{get schema(){return this._def.getter()}_parse($){let{ctx:w}=this._processInputParams($);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}};rE.create=($,w)=>{return new rE({getter:$,typeName:a.ZodLazy,...X0(w)})};pE=class pE extends G0{_parse($){if($.data!==this._def.value){let w=this._getOrReturnCtx($);return g(w,{received:w.data,code:_.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:$.data}}get value(){return this._def.value}};pE.create=($,w)=>{return new pE({value:$,typeName:a.ZodLiteral,...X0(w)})};fw=class fw extends G0{_parse($){if(typeof $.data!=="string"){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{expected:Y0.joinValues(E),received:w.parsedType,code:_.invalid_type}),d}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{received:w.data,code:_.invalid_enum_value,options:E}),d}return P$($.data)}get options(){return this._def.values}get enum(){let $={};for(let w of this._def.values)$[w]=w;return $}get Values(){let $={};for(let w of this._def.values)$[w]=w;return $}get Enum(){let $={};for(let w of this._def.values)$[w]=w;return $}extract($,w=this._def){return fw.create($,{...this._def,...w})}exclude($,w=this._def){return fw.create(this.options.filter((E)=>!$.includes(E)),{...this._def,...w})}};fw.create=cO;oE=class oE extends G0{_parse($){let w=Y0.getValidEnumValues(this._def.values),E=this._getOrReturnCtx($);if(E.parsedType!==f.string&&E.parsedType!==f.number){let X=Y0.objectValues(w);return g(E,{expected:Y0.joinValues(X),received:E.parsedType,code:_.invalid_type}),d}if(!this._cache)this._cache=new Set(Y0.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=Y0.objectValues(w);return g(E,{received:E.data,code:_.invalid_enum_value,options:X}),d}return P$($.data)}get enum(){return this._def.values}};oE.create=($,w)=>{return new oE({values:$,typeName:a.ZodNativeEnum,...X0(w)})};OE=class OE extends G0{unwrap(){return this._def.type}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.promise&&w.common.async===!1)return g(w,{code:_.invalid_type,expected:f.promise,received:w.parsedType}),d;let E=w.parsedType===f.promise?w.data:Promise.resolve(w.data);return P$(E.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}};OE.create=($,w)=>{return new OE({type:$,typeName:a.ZodPromise,...X0(w)})};k1=class k1 extends G0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===a.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:w,ctx:E}=this._processInputParams($),X=this._def.effect||null,G={addIssue:(J)=>{if(g(E,J),J.fatal)w.abort();else w.dirty()},get path(){return E.path}};if(G.addIssue=G.addIssue.bind(G),X.type==="preprocess"){let J=X.transform(E.data,G);if(E.common.async)return Promise.resolve(J).then(async(A)=>{if(w.value==="aborted")return d;let D=await this._def.schema._parseAsync({data:A,path:E.path,parent:E});if(D.status==="aborted")return d;if(D.status==="dirty")return AE(D.value);if(w.value==="dirty")return AE(D.value);return D});else{if(w.value==="aborted")return d;let A=this._def.schema._parseSync({data:J,path:E.path,parent:E});if(A.status==="aborted")return d;if(A.status==="dirty")return AE(A.value);if(w.value==="dirty")return AE(A.value);return A}}if(X.type==="refinement"){let J=(A)=>{let D=X.refinement(A,G);if(E.common.async)return Promise.resolve(D);if(D instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return A};if(E.common.async===!1){let A=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(A.status==="aborted")return d;if(A.status==="dirty")w.dirty();return J(A.value),{status:w.value,value:A.value}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((A)=>{if(A.status==="aborted")return d;if(A.status==="dirty")w.dirty();return J(A.value).then(()=>{return{status:w.value,value:A.value}})})}if(X.type==="transform")if(E.common.async===!1){let J=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(!Zw(J))return d;let A=X.transform(J.value,G);if(A instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:A}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((J)=>{if(!Zw(J))return d;return Promise.resolve(X.transform(J.value,G)).then((A)=>({status:w.value,value:A}))});Y0.assertNever(X)}};k1.create=($,w,E)=>{return new k1({schema:$,typeName:a.ZodEffects,effect:w,...X0(E)})};k1.createWithPreprocess=($,w,E)=>{return new k1({schema:w,effect:{type:"preprocess",transform:$},typeName:a.ZodEffects,...X0(E)})};q1=class q1 extends G0{_parse($){if(this._getType($)===f.undefined)return P$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};q1.create=($,w)=>{return new q1({innerType:$,typeName:a.ZodOptional,...X0(w)})};Yw=class Yw extends G0{_parse($){if(this._getType($)===f.null)return P$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};Yw.create=($,w)=>{return new Yw({innerType:$,typeName:a.ZodNullable,...X0(w)})};tE=class tE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;if(w.parsedType===f.undefined)E=this._def.defaultValue();return this._def.innerType._parse({data:E,path:w.path,parent:w})}removeDefault(){return this._def.innerType}};tE.create=($,w)=>{return new tE({innerType:$,typeName:a.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...X0(w)})};iE=class iE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:E.data,path:E.path,parent:{...E}});if(xE(X))return X.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new r$(E.common.issues)},input:E.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new r$(E.common.issues)},input:E.data})}}removeCatch(){return this._def.innerType}};iE.create=($,w)=>{return new iE({innerType:$,typeName:a.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...X0(w)})};NG=class NG extends G0{_parse($){if(this._getType($)!==f.nan){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.nan,received:E.parsedType}),d}return{status:"valid",value:$.data}}};NG.create=($)=>{return new NG({typeName:a.ZodNaN,...X0($)})};NP=Symbol("zod_brand");HJ=class HJ extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;return this._def.type._parse({data:E,path:w.path,parent:w})}unwrap(){return this._def.type}};WG=class WG extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:E.data,path:E.path,parent:E});if(G.status==="aborted")return d;if(G.status==="dirty")return w.dirty(),AE(G.value);else return this._def.out._parseAsync({data:G.value,path:E.path,parent:E})})();else{let X=this._def.in._parseSync({data:E.data,path:E.path,parent:E});if(X.status==="aborted")return d;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:E.path,parent:E})}}static create($,w){return new WG({in:$,out:w,typeName:a.ZodPipeline})}};dE=class dE extends G0{_parse($){let w=this._def.innerType._parse($),E=(X)=>{if(Zw(X))X.value=Object.freeze(X.value);return X};return xE(w)?w.then((X)=>E(X)):E(w)}unwrap(){return this._def.innerType}};dE.create=($,w)=>{return new dE({innerType:$,typeName:a.ZodReadonly,...X0(w)})};WP={object:l0.lazycreate};(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(a||(a={}));mO=V1.create,rO=_w.create,UP=NG.create,YP=vw.create,pO=uE.create,HP=DE.create,LP=GG.create,FP=hE.create,jP=cE.create,MP=NE.create,RP=Cw.create,zP=t1.create,TP=JG.create,BP=P1.create,QP=l0.create,IP=l0.strictCreate,KP=nE.create,VP=YJ.create,PP=mE.create,qP=i1.create,SP=AG.create,kP=DG.create,bP=WE.create,ZP=gE.create,CP=rE.create,_P=pE.create,vP=fw.create,fP=oE.create,xP=OE.create,yP=k1.create,gP=q1.create,uP=Yw.create,hP=k1.createWithPreprocess,cP=WG.create,pP={string:($)=>V1.create({...$,coerce:!0}),number:($)=>_w.create({...$,coerce:!0}),boolean:($)=>uE.create({...$,coerce:!0}),bigint:($)=>vw.create({...$,coerce:!0}),date:($)=>DE.create({...$,coerce:!0})},oP=d});var U={};Ww(U,{void:()=>TP,util:()=>Y0,unknown:()=>RP,union:()=>KP,undefined:()=>FP,tuple:()=>qP,transformer:()=>yP,symbol:()=>LP,string:()=>mO,strictObject:()=>IP,setErrorMap:()=>uV,set:()=>bP,record:()=>SP,quotelessJson:()=>yV,promise:()=>xP,preprocess:()=>hP,pipeline:()=>cP,ostring:()=>nP,optional:()=>gP,onumber:()=>mP,oboolean:()=>rP,objectUtil:()=>QD,object:()=>QP,number:()=>rO,nullable:()=>uP,null:()=>jP,never:()=>zP,nativeEnum:()=>fP,nan:()=>UP,map:()=>kP,makeIssue:()=>XG,literal:()=>_P,lazy:()=>CP,late:()=>WP,isValid:()=>Zw,isDirty:()=>UJ,isAsync:()=>xE,isAborted:()=>OJ,intersection:()=>PP,instanceof:()=>OP,getParsedType:()=>o1,getErrorMap:()=>fE,function:()=>ZP,enum:()=>vP,effect:()=>yP,discriminatedUnion:()=>VP,defaultErrorMap:()=>Ow,datetimeRegex:()=>hO,date:()=>HP,custom:()=>nO,coerce:()=>pP,boolean:()=>pO,bigint:()=>YP,array:()=>BP,any:()=>MP,addIssueToContext:()=>g,ZodVoid:()=>JG,ZodUnknown:()=>Cw,ZodUnion:()=>nE,ZodUndefined:()=>hE,ZodType:()=>G0,ZodTuple:()=>i1,ZodTransformer:()=>k1,ZodSymbol:()=>GG,ZodString:()=>V1,ZodSet:()=>WE,ZodSchema:()=>G0,ZodRecord:()=>AG,ZodReadonly:()=>dE,ZodPromise:()=>OE,ZodPipeline:()=>WG,ZodParsedType:()=>f,ZodOptional:()=>q1,ZodObject:()=>l0,ZodNumber:()=>_w,ZodNullable:()=>Yw,ZodNull:()=>cE,ZodNever:()=>t1,ZodNativeEnum:()=>oE,ZodNaN:()=>NG,ZodMap:()=>DG,ZodLiteral:()=>pE,ZodLazy:()=>rE,ZodIssueCode:()=>_,ZodIntersection:()=>mE,ZodFunction:()=>gE,ZodFirstPartyTypeKind:()=>a,ZodError:()=>r$,ZodEnum:()=>fw,ZodEffects:()=>k1,ZodDiscriminatedUnion:()=>YJ,ZodDefault:()=>tE,ZodDate:()=>DE,ZodCatch:()=>iE,ZodBranded:()=>HJ,ZodBoolean:()=>uE,ZodBigInt:()=>vw,ZodArray:()=>P1,ZodAny:()=>NE,Schema:()=>G0,ParseStatus:()=>j$,OK:()=>P$,NEVER:()=>oP,INVALID:()=>d,EMPTY_PATH:()=>hV,DIRTY:()=>AE,BRAND:()=>NP});var qD=R(()=>{WJ();KD();vO();EG();oO();NJ()});var OG=R(()=>{qD();qD()});import{existsSync as tO,readFileSync as tP}from"fs";import{homedir as lO}from"os";import{join as SD}from"path";function aP($){if($.startsWith("~/"))return SD(lO(),$.slice(2));return $}function dO($){try{return JSON.parse(tP($,"utf-8"))}catch{return{}}}function UG($,w){let E={...$};for(let[X,G]of Object.entries(w))if(G!==null&&typeof G==="object"&&!Array.isArray(G)&&typeof E[X]==="object"&&E[X]!==null)E[X]=UG(E[X],G);else E[X]=G;return E}function eP(){let $={};if(process.env.ORC_DB_PATH)$.db={path:process.env.ORC_DB_PATH};let w={};if(process.env.ORC_API_PORT)w.port=Number(process.env.ORC_API_PORT);if(process.env.ORC_API_HOST)w.host=process.env.ORC_API_HOST;if(process.env.ORC_API_SECRET)w.secret=process.env.ORC_API_SECRET;if(Object.keys(w).length)$.api=w;let E={};if(process.env.ORC_RUNNER_TIMEOUT)E.default_timeout_secs=Number(process.env.ORC_RUNNER_TIMEOUT);if(process.env.ORC_RUNNER_MAX_JOBS)E.max_concurrent_jobs=Number(process.env.ORC_RUNNER_MAX_JOBS);if(process.env.ORC_RUNNER_LOG_DAYS)E.log_retention_days=Number(process.env.ORC_RUNNER_LOG_DAYS);if(Object.keys(E).length)$.runner=E;let X={};if(process.env.ORC_SNAPSHOT_MAX_BYTES)X.snapshot_max_bytes=Number(process.env.ORC_SNAPSHOT_MAX_BYTES);if(process.env.ORC_LAYER1_TASKS)X.layer1_task_limit=Number(process.env.ORC_LAYER1_TASKS);if(process.env.ORC_LAYER1_MEMORIES)X.layer1_memory_limit=Number(process.env.ORC_LAYER1_MEMORIES);if(Object.keys(X).length)$.context=X;let G={};if(process.env.ORC_TELEGRAM_TOKEN)G.telegram={token:process.env.ORC_TELEGRAM_TOKEN,enabled:!0};if(process.env.ORC_SLACK_BOT_TOKEN||process.env.ORC_SLACK_APP_TOKEN)G.slack={bot_token:process.env.ORC_SLACK_BOT_TOKEN,app_token:process.env.ORC_SLACK_APP_TOKEN,enabled:!0};if(Object.keys(G).length)$.gateway=G;let J={};if(process.env.ORC_SPEECH_PROVIDER)J.provider=process.env.ORC_SPEECH_PROVIDER;if(process.env.ORC_SPEECH_LANGUAGE)J.language=process.env.ORC_SPEECH_LANGUAGE;if(process.env.ORC_OPENAI_API_KEY)J.openai={api_key:process.env.ORC_OPENAI_API_KEY};if(process.env.ORC_GROQ_API_KEY)J.groq={api_key:process.env.ORC_GROQ_API_KEY};if(process.env.ORC_QWEN_API_KEY)J.qwen={api_key:process.env.ORC_QWEN_API_KEY};if(Object.keys(J).length)J.enabled=!0,$.speech=J;let A={};if(process.env.ORC_TTS_PROVIDER)A.provider=process.env.ORC_TTS_PROVIDER;if(process.env.ORC_TTS_VOICE)A.voice=process.env.ORC_TTS_VOICE;if(process.env.ORC_TTS_MODE)A.mode=process.env.ORC_TTS_MODE;if(Object.keys(A).length)A.enabled=!0,$.tts=A;return $}function O0($){if(LJ&&!$)return LJ;let w=SD(lO(),".orc","config.json"),E=SD(process.cwd(),".orc","config.json"),X={};if(tO(w))X=UG(X,dO(w));if(tO(E))X=UG(X,dO(E));if(X=UG(X,eP()),$)X=UG(X,$);if(X.bridge&&!X.gateway)X.gateway=X.bridge;delete X.bridge;let G=sP.safeParse(X);if(!G.success)throw Error(`Invalid orc config:
4
- ${G.error.message}`);return G.data.db.path=aP(G.data.db.path),LJ=G.data,LJ}var iP,iO,YG,dP,lP,sP,LJ=null;var C$=R(()=>{OG();iP=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")).default("direct"),iO=U.object({enabled:U.boolean().default(!1),token:U.string().optional(),bot_token:U.string().optional(),app_token:U.string().optional(),authorized_users:U.array(U.union([U.string(),U.number()])).default([]),default_chat_id:U.string().optional(),mode:iP,allow_channel_mentions:U.boolean().default(!0),share_session_in_channel:U.boolean().default(!1),streaming_preview:U.boolean().default(!0)}),YG=U.object({api_key:U.string().optional(),base_url:U.string().optional(),model:U.string().optional()}),dP=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","groq","qwen"]).default("openai"),language:U.string().default(""),openai:YG.default({}),groq:YG.default({}),qwen:YG.default({})}),lP=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","qwen"]).default("openai"),voice:U.string().default("alloy"),mode:U.enum(["voice_only","always"]).default("voice_only"),max_text_len:U.number().int().min(0).default(0),openai:YG.default({}),qwen:YG.default({})}),sP=U.object({db:U.object({path:U.string().default("~/.orc/orc.db")}).default({}),api:U.object({port:U.number().int().default(7700),host:U.string().default("127.0.0.1"),secret:U.string().optional()}).default({}),mcp:U.object({transport:U.enum(["stdio","http"]).default("stdio"),port:U.number().int().default(7701)}).default({}),gateway:U.object({telegram:iO.default({}),slack:iO.default({})}).default({}),runner:U.object({default_timeout_secs:U.number().int().default(300),max_concurrent_jobs:U.number().int().default(5),log_retention_days:U.number().int().default(30)}).default({}),context:U.object({snapshot_max_bytes:U.number().int().default(2048),layer1_task_limit:U.number().int().default(10),layer1_memory_limit:U.number().int().default(5)}).default({}),speech:dP.default({}),tts:lP.default({}),activeProject:U.string().optional()})});import{readFileSync as $q}from"fs";import{dirname as wq,join as Eq}from"path";import{fileURLToPath as Xq}from"url";var kD,lE;var FJ=R(()=>{try{let $=wq(Xq(import.meta.url));kD=JSON.parse($q(Eq($,"..","package.json"),"utf-8")).version}catch{kD=process.env.ORC_VERSION??"0.0.0"}lE=kD});var HG=Z((Gq)=>{class bD extends Error{constructor($,w,E){super(E);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class sO extends bD{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Gq.CommanderError=bD;Gq.InvalidArgumentError=sO});var jJ=Z((Wq)=>{var{InvalidArgumentError:Dq}=HG();class aO{constructor($,w){switch(this.description=w||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.concat($)}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(w,E)=>{if(!this.argChoices.includes(w))throw new Dq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(w,E);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Nq($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}Wq.Argument=aO;Wq.humanReadableArgName=Nq});var ZD=Z((Hq)=>{var{humanReadableArgName:Yq}=jJ();class eO{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let w=$.commands.filter((X)=>!X._hidden),E=$._getHelpCommand();if(E&&!E._hidden)w.push(E);if(this.sortSubcommands)w.sort((X,G)=>{return X.name().localeCompare(G.name())});return w}compareOptions($,w){let E=(X)=>{return X.short?X.short.replace(/^-/,""):X.long.replace(/^--/,"")};return E($).localeCompare(E(w))}visibleOptions($){let w=$.options.filter((X)=>!X.hidden),E=$._getHelpOption();if(E&&!E.hidden){let X=E.short&&$._findOption(E.short),G=E.long&&$._findOption(E.long);if(!X&&!G)w.push(E);else if(E.long&&!G)w.push($.createOption(E.long,E.description));else if(E.short&&!X)w.push($.createOption(E.short,E.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let E=$.parent;E;E=E.parent){let X=E.options.filter((G)=>!G.hidden);w.push(...X)}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((w)=>{w.description=w.description||$._argsDescription[w.name()]||""});if($.registeredArguments.find((w)=>w.description))return $.registeredArguments;return[]}subcommandTerm($){let w=$.registeredArguments.map((E)=>Yq(E)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(X))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleOptionTerm(w.optionTerm(X))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleOptionTerm(w.optionTerm(X))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(X))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let E="";for(let X=$.parent;X;X=X.parent)E=X.name()+" "+E;return E+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((E)=>JSON.stringify(E)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)w.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)w.push(`env: ${$.envVar}`);if(w.length>0)return`${$.description} (${w.join(", ")})`;return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((E)=>JSON.stringify(E)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let E=`(${w.join(", ")})`;if($.description)return`${$.description} ${E}`;return E}return $.description}formatHelp($,w){let E=w.padWidth($,w),X=w.helpWidth??80;function G(O,Y){return w.formatItem(O,E,Y,w)}let J=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],A=w.commandDescription($);if(A.length>0)J=J.concat([w.boxWrap(w.styleCommandDescription(A),X),""]);let D=w.visibleArguments($).map((O)=>{return G(w.styleArgumentTerm(w.argumentTerm(O)),w.styleArgumentDescription(w.argumentDescription(O)))});if(D.length>0)J=J.concat([w.styleTitle("Arguments:"),...D,""]);let N=w.visibleOptions($).map((O)=>{return G(w.styleOptionTerm(w.optionTerm(O)),w.styleOptionDescription(w.optionDescription(O)))});if(N.length>0)J=J.concat([w.styleTitle("Options:"),...N,""]);if(w.showGlobalOptions){let O=w.visibleGlobalOptions($).map((Y)=>{return G(w.styleOptionTerm(w.optionTerm(Y)),w.styleOptionDescription(w.optionDescription(Y)))});if(O.length>0)J=J.concat([w.styleTitle("Global Options:"),...O,""])}let W=w.visibleCommands($).map((O)=>{return G(w.styleSubcommandTerm(w.subcommandTerm(O)),w.styleSubcommandDescription(w.subcommandDescription(O)))});if(W.length>0)J=J.concat([w.styleTitle("Commands:"),...W,""]);return J.join(`
5
- `)}displayWidth($){return $U($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w==="[command]")return this.styleSubcommandText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleCommandText(w)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleSubcommandText(w)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,w){return Math.max(w.longestOptionTermLength($,w),w.longestGlobalOptionTermLength($,w),w.longestSubcommandTermLength($,w),w.longestArgumentTermLength($,w))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,w,E,X){let J=" ".repeat(2);if(!E)return J+$;let A=$.padEnd(w+$.length-X.displayWidth($)),D=2,W=(this.helpWidth??80)-w-D-2,O;if(W<this.minWidthToWrap||X.preformatted(E))O=E;else O=X.boxWrap(E,W).replace(/\n/g,`
6
- `+" ".repeat(w+D));return J+A+" ".repeat(D)+O.replace(/\n/g,`
7
- ${J}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let E=$.split(/\r\n|\n/),X=/[\s]*[^\s]+/g,G=[];return E.forEach((J)=>{let A=J.match(X);if(A===null){G.push("");return}let D=[A.shift()],N=this.displayWidth(D[0]);A.forEach((W)=>{let O=this.displayWidth(W);if(N+O<=w){D.push(W),N+=O;return}G.push(D.join(""));let Y=W.trimStart();D=[Y],N=this.displayWidth(Y)}),G.push(D.join(""))}),G.join(`
8
- `)}}function $U($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}Hq.Help=eO;Hq.stripColor=$U});var CD=Z((Rq)=>{var{InvalidArgumentError:jq}=HG();class EU{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let E=Mq($);if(this.short=E.shortFlag,this.long=E.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let w=$;if(typeof $==="string")w={[$]:!0};return this.implied=Object.assign(this.implied||{},w),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(w,E)=>{if(!this.argChoices.includes(w))throw new jq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(w,E);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return wU(this.name().replace(/^no-/,""));return wU(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class XU{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((w)=>{if(w.negate)this.negativeOptions.set(w.attributeName(),w);else this.positiveOptions.set(w.attributeName(),w)}),this.negativeOptions.forEach((w,E)=>{if(this.positiveOptions.has(E))this.dualOptions.add(E)})}valueFromOption($,w){let E=w.attributeName();if(!this.dualOptions.has(E))return!0;let X=this.negativeOptions.get(E).presetArg,G=X!==void 0?X:!1;return w.negate===(G===$)}}function wU($){return $.split("-").reduce((w,E)=>{return w+E[0].toUpperCase()+E.slice(1)})}function Mq($){let w,E,X=/^-[^-]$/,G=/^--[^-]/,J=$.split(/[ |,]+/).concat("guard");if(X.test(J[0]))w=J.shift();if(G.test(J[0]))E=J.shift();if(!w&&X.test(J[0]))w=J.shift();if(!w&&G.test(J[0]))w=E,E=J.shift();if(J[0].startsWith("-")){let A=J[0],D=`option creation failed due to '${A}' in option flags '${$}'`;if(/^-[^-][^-]/.test(A))throw Error(`${D}
3
+ var gV=Object.create;var{getPrototypeOf:uV,defineProperty:AG,getOwnPropertyNames:x9,getOwnPropertyDescriptor:nV}=Object,y9=Object.prototype.hasOwnProperty;function g9($){return this[$]}var hV,cV,UN=($,w,E)=>{var X=$!=null&&typeof $==="object";if(X){var G=w?hV??=new WeakMap:cV??=new WeakMap,A=G.get($);if(A)return A}E=$!=null?gV(uV($)):{};let N=w||!$||!$.__esModule?AG(E,"default",{value:$,enumerable:!0}):E;for(let D of x9($))if(!y9.call(N,D))AG(N,D,{get:g9.bind($,D),enumerable:!0});if(X)G.set($,N);return N},u9=($)=>{var w=(v9??=new WeakMap).get($),E;if(w)return w;if(w=AG({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of x9($))if(!y9.call(w,X))AG(w,X,{get:g9.bind($,X),enumerable:!(E=nV($,X))||E.enumerable})}return v9.set($,w),w},v9,_=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var rV=($)=>$;function tV($,w){this[$]=rV.bind(null,w)}var OE=($,w)=>{for(var E in w)AG($,E,{get:w[E],enumerable:!0,configurable:!0,set:tV.bind(w,E)})};var T=($,w)=>()=>($&&(w=$($=0)),w);var b$=import.meta.require;var U0,VO,x,ow=($)=>{switch(typeof $){case"undefined":return x.undefined;case"string":return x.string;case"number":return Number.isNaN($)?x.nan:x.number;case"boolean":return x.boolean;case"function":return x.function;case"bigint":return x.bigint;case"symbol":return x.symbol;case"object":if(Array.isArray($))return x.array;if($===null)return x.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return x.promise;if(typeof Map<"u"&&$ instanceof Map)return x.map;if(typeof Set<"u"&&$ instanceof Set)return x.set;if(typeof Date<"u"&&$ instanceof Date)return x.date;return x.object;default:return x.unknown}};var NG=T(()=>{(function($){$.assertEqual=(G)=>{};function w(G){}$.assertIs=w;function E(G){throw Error()}$.assertNever=E,$.arrayToEnum=(G)=>{let A={};for(let N of G)A[N]=N;return A},$.getValidEnumValues=(G)=>{let A=$.objectKeys(G).filter((D)=>typeof G[G[D]]!=="number"),N={};for(let D of A)N[D]=G[D];return $.objectValues(N)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(A){return G[A]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let A=[];for(let N in G)if(Object.prototype.hasOwnProperty.call(G,N))A.push(N);return A},$.find=(G,A)=>{for(let N of G)if(A(N))return N;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function X(G,A=" | "){return G.map((N)=>typeof N==="string"?`'${N}'`:N).join(A)}$.joinValues=X,$.jsonStringifyReplacer=(G,A)=>{if(typeof A==="bigint")return A.toString();return A}})(U0||(U0={}));(function($){$.mergeShapes=(w,E)=>{return{...w,...E}}})(VO||(VO={}));x=U0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var Z,oV=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")},p$;var YN=T(()=>{NG();Z=U0.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);p$=class p$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(E)=>{this.issues=[...this.issues,E]},this.addIssues=(E=[])=>{this.issues=[...this.issues,...E]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=$}format($){let w=$||function(G){return G.message},E={_errors:[]},X=(G)=>{for(let A of G.issues)if(A.code==="invalid_union")A.unionErrors.map(X);else if(A.code==="invalid_return_type")X(A.returnTypeError);else if(A.code==="invalid_arguments")X(A.argumentsError);else if(A.path.length===0)E._errors.push(w(A));else{let N=E,D=0;while(D<A.path.length){let O=A.path[D];if(D!==A.path.length-1)N[O]=N[O]||{_errors:[]};else N[O]=N[O]||{_errors:[]},N[O]._errors.push(w(A));N=N[O],D++}}};return X(this),E}static assert($){if(!($ instanceof p$))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,U0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(w)=>w.message){let w={},E=[];for(let X of this.issues)if(X.path.length>0){let G=X.path[0];w[G]=w[G]||[],w[G].push($(X))}else E.push($(X));return{formErrors:E,fieldErrors:w}}get formErrors(){return this.flatten()}};p$.create=($)=>{return new p$($)}});var mV=($,w)=>{let E;switch($.code){case Z.invalid_type:if($.received===x.undefined)E="Required";else E=`Expected ${$.expected}, received ${$.received}`;break;case Z.invalid_literal:E=`Invalid literal value, expected ${JSON.stringify($.expected,U0.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:E=`Unrecognized key(s) in object: ${U0.joinValues($.keys,", ")}`;break;case Z.invalid_union:E="Invalid input";break;case Z.invalid_union_discriminator:E=`Invalid discriminator value. Expected ${U0.joinValues($.options)}`;break;case Z.invalid_enum_value:E=`Invalid enum value. Expected ${U0.joinValues($.options)}, received '${$.received}'`;break;case Z.invalid_arguments:E="Invalid function arguments";break;case Z.invalid_return_type:E="Invalid function return type";break;case Z.invalid_date:E="Invalid date";break;case Z.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(E=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")E=`${E} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)E=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)E=`Invalid input: must end with "${$.validation.endsWith}"`;else U0.assertNever($.validation);else if($.validation!=="regex")E=`Invalid ${$.validation}`;else E="Invalid";break;case Z.too_small:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else E="Invalid input";break;case Z.too_big:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")E=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else E="Invalid input";break;case Z.custom:E="Invalid input";break;case Z.invalid_intersection_types:E="Intersection results could not be merged";break;case Z.not_multiple_of:E=`Number must be a multiple of ${$.multipleOf}`;break;case Z.not_finite:E="Number must be finite";break;default:E=w.defaultError,U0.assertNever($)}return{message:E}},WE;var PO=T(()=>{YN();NG();WE=mV});function iV($){n9=$}function y1(){return n9}var n9;var HN=T(()=>{PO();n9=WE});function g($,w){let E=y1(),X=DG({issueData:w,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,E,E===WE?void 0:WE].filter((G)=>!!G)});$.common.issues.push(X)}class T${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,w){let E=[];for(let X of w){if(X.status==="aborted")return l;if(X.status==="dirty")$.dirty();E.push(X.value)}return{status:$.value,value:E}}static async mergeObjectAsync($,w){let E=[];for(let X of w){let G=await X.key,A=await X.value;E.push({key:G,value:A})}return T$.mergeObjectSync($,E)}static mergeObjectSync($,w){let E={};for(let X of w){let{key:G,value:A}=X;if(G.status==="aborted")return l;if(A.status==="aborted")return l;if(G.status==="dirty")$.dirty();if(A.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof A.value<"u"||X.alwaysSet))E[G.value]=A.value}return{status:$.value,value:E}}}var DG=($)=>{let{data:w,path:E,errorMaps:X,issueData:G}=$,A=[...E,...G.path||[]],N={...G,path:A};if(G.message!==void 0)return{...G,path:A,message:G.message};let D="",O=X.filter((W)=>!!W).slice().reverse();for(let W of O)D=W(N,{data:w,defaultError:D}).message;return{...G,path:A,message:D}},pV,l,D1=($)=>({status:"dirty",value:$}),_$=($)=>({status:"valid",value:$}),LN=($)=>$.status==="aborted",FN=($)=>$.status==="dirty",_E=($)=>$.status==="valid",g1=($)=>typeof Promise<"u"&&$ instanceof Promise;var qO=T(()=>{HN();PO();pV=[];l=Object.freeze({status:"aborted"})});var h9=()=>{};var c;var c9=T(()=>{(function($){$.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},$.toString=(w)=>typeof w==="string"?w:w?.message})(c||(c={}))});class qw{constructor($,w,E,X){this._cachedPath=[],this.parent=$,this.data=w,this._path=E,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function X0($){if(!$)return{};let{errorMap:w,invalid_type_error:E,required_error:X,description:G}=$;if(w&&(E||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:G};return{errorMap:(N,D)=>{let{message:O}=$;if(N.code==="invalid_enum_value")return{message:O??D.defaultError};if(typeof D.data>"u")return{message:O??X??D.defaultError};if(N.code!=="invalid_type")return{message:D.defaultError};return{message:O??E??D.defaultError}},description:G}}class A0{get description(){return this._def.description}_getType($){return ow($.data)}_getOrReturnCtx($,w){return w||{common:$.parent.common,data:$.data,parsedType:ow($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new T$,ctx:{common:$.parent.common,data:$.data,parsedType:ow($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let w=this._parse($);if(g1(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync($){let w=this._parse($);return Promise.resolve(w)}parse($,w){let E=this.safeParse($,w);if(E.success)return E.data;throw E.error}safeParse($,w){let E={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:ow($)},X=this._parseSync({data:$,path:E.path,parent:E});return r9(E,X)}"~validate"($){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:ow($)};if(!this["~standard"].async)try{let E=this._parseSync({data:$,path:[],parent:w});return _E(E)?{value:E.value}:{issues:w.common.issues}}catch(E){if(E?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:w}).then((E)=>_E(E)?{value:E.value}:{issues:w.common.issues})}async parseAsync($,w){let E=await this.safeParseAsync($,w);if(E.success)return E.data;throw E.error}async safeParseAsync($,w){let E={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:ow($)},X=this._parse({data:$,path:E.path,parent:E}),G=await(g1(X)?X:Promise.resolve(X));return r9(E,G)}refine($,w){let E=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,G)=>{let A=$(X),N=()=>G.addIssue({code:Z.custom,...E(X)});if(typeof Promise<"u"&&A instanceof Promise)return A.then((D)=>{if(!D)return N(),!1;else return!0});if(!A)return N(),!1;else return!0})}refinement($,w){return this._refinement((E,X)=>{if(!$(E))return X.addIssue(typeof w==="function"?w(E,X):w),!1;else return!0})}_refinement($){return new Sw({schema:this,typeName:a.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(w)=>this["~validate"](w)}}optional(){return Pw.create(this,this._def)}nullable(){return UE.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vw.create(this)}promise(){return U1.create(this,this._def)}or($){return t1.create([this,$],this._def)}and($){return o1.create(this,$,this._def)}transform($){return new Sw({...X0(this._def),schema:this,typeName:a.ZodEffects,effect:{type:"transform",transform:$}})}default($){let w=typeof $==="function"?$:()=>$;return new d1({...X0(this._def),innerType:this,defaultValue:w,typeName:a.ZodDefault})}brand(){return new MN({typeName:a.ZodBranded,type:this,...X0(this._def)})}catch($){let w=typeof $==="function"?$:()=>$;return new l1({...X0(this._def),innerType:this,catchValue:w,typeName:a.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return HG.create(this,$)}readonly(){return s1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function m9($){let w="[0-5]\\d";if($.precision)w=`${w}\\.\\d{${$.precision}}`;else if($.precision==null)w=`${w}(\\.\\d+)?`;let E=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${E}`}function UP($){return new RegExp(`^${m9($)}$`)}function i9($){let w=`${o9}T${m9($)}`,E=[];if(E.push($.local?"Z?":"Z"),$.offset)E.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${E.join("|")})`,new RegExp(`^${w}$`)}function YP($,w){if((w==="v4"||!w)&&GP.test($))return!0;if((w==="v6"||!w)&&NP.test($))return!0;return!1}function HP($,w){if(!$P.test($))return!1;try{let[E]=$.split(".");if(!E)return!1;let X=E.replace(/-/g,"+").replace(/_/g,"/").padEnd(E.length+(4-E.length%4)%4,"="),G=JSON.parse(atob(X));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&G.alg!==w)return!1;return!0}catch{return!1}}function LP($,w){if((w==="v4"||!w)&&AP.test($))return!0;if((w==="v6"||!w)&&DP.test($))return!0;return!1}function FP($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,A=Number.parseInt($.toFixed(G).replace(".","")),N=Number.parseInt(w.toFixed(G).replace(".",""));return A%N/10**G}function u1($){if($ instanceof s0){let w={};for(let E in $.shape){let X=$.shape[E];w[E]=Pw.create(u1(X))}return new s0({...$._def,shape:()=>w})}else if($ instanceof Vw)return new Vw({...$._def,type:u1($.element)});else if($ instanceof Pw)return Pw.create(u1($.unwrap()));else if($ instanceof UE)return UE.create(u1($.unwrap()));else if($ instanceof iw)return iw.create($.items.map((w)=>u1(w)));else return $}function kO($,w){let E=ow($),X=ow(w);if($===w)return{valid:!0,data:$};else if(E===x.object&&X===x.object){let G=U0.objectKeys(w),A=U0.objectKeys($).filter((D)=>G.indexOf(D)!==-1),N={...$,...w};for(let D of A){let O=kO($[D],w[D]);if(!O.valid)return{valid:!1};N[D]=O.data}return{valid:!0,data:N}}else if(E===x.array&&X===x.array){if($.length!==w.length)return{valid:!1};let G=[];for(let A=0;A<$.length;A++){let N=$[A],D=w[A],O=kO(N,D);if(!O.valid)return{valid:!1};G.push(O.data)}return{valid:!0,data:G}}else if(E===x.date&&X===x.date&&+$===+w)return{valid:!0,data:$};else return{valid:!1}}function p9($,w){return new vE({values:$,typeName:a.ZodEnum,...X0(w)})}function t9($,w){let E=typeof $==="function"?$(w):typeof $==="string"?{message:$}:$;return typeof E==="string"?{message:E}:E}function d9($,w={},E){if($)return W1.create().superRefine((X,G)=>{let A=$(X);if(A instanceof Promise)return A.then((N)=>{if(!N){let D=t9(w,X),O=D.fatal??E??!0;G.addIssue({code:"custom",...D,fatal:O})}});if(!A){let N=t9(w,X),D=N.fatal??E??!0;G.addIssue({code:"custom",...N,fatal:D})}return});return W1.create()}var r9=($,w)=>{if(_E(w))return{success:!0,data:w.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let E=new p$($.common.issues);return this._error=E,this._error}}}},dV,lV,sV,aV,eV,$P,wP,EP,XP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",SO,GP,AP,NP,DP,OP,WP,o9="((\\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])))",JP,Kw,CE,fE,h1,O1,OG,c1,r1,W1,ZE,mw,WG,Vw,s0,t1,JE=($)=>{if($ instanceof m1)return JE($.schema);else if($ instanceof Sw)return JE($.innerType());else if($ instanceof i1)return[$.value];else if($ instanceof vE)return $.options;else if($ instanceof p1)return U0.objectValues($.enum);else if($ instanceof d1)return JE($._def.innerType);else if($ instanceof c1)return[void 0];else if($ instanceof r1)return[null];else if($ instanceof Pw)return[void 0,...JE($.unwrap())];else if($ instanceof UE)return[null,...JE($.unwrap())];else if($ instanceof MN)return JE($.unwrap());else if($ instanceof s1)return JE($.unwrap());else if($ instanceof l1)return JE($._def.innerType);else return[]},jN,o1,iw,JG,UG,J1,n1,m1,i1,vE,p1,U1,Sw,Pw,UE,d1,l1,YG,jP,MN,HG,s1,MP,a,TP=($,w={message:`Input not instance of ${$.name}`})=>d9((E)=>E instanceof $,w),l9,s9,RP,zP,a9,BP,IP,QP,KP,VP,PP,qP,SP,kP,bP,_P,ZP,CP,fP,vP,xP,yP,gP,uP,nP,hP,cP,rP,tP,oP,mP,iP,pP,dP,lP=()=>l9().optional(),sP=()=>s9().optional(),aP=()=>a9().optional(),eP,$q;var e9=T(()=>{YN();HN();c9();qO();NG();dV=/^c[^\s-]{8,}$/i,lV=/^[0-9a-z]+$/,sV=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aV=/^[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,eV=/^[a-z0-9_-]{21}$/i,$P=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wP=/^[-+]?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)?)??$/,EP=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,GP=/^(?:(?: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])$/,AP=/^(?:(?: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])$/,NP=/^(([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]))$/,DP=/^(([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])$/,OP=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,WP=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,JP=new RegExp(`^${o9}$`);Kw=class Kw extends A0{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==x.string){let G=this._getOrReturnCtx($);return g(G,{code:Z.invalid_type,expected:x.string,received:G.parsedType}),l}let E=new T$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)X=this._getOrReturnCtx($,X),g(X,{code:Z.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="max"){if($.data.length>G.value)X=this._getOrReturnCtx($,X),g(X,{code:Z.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="length"){let A=$.data.length>G.value,N=$.data.length<G.value;if(A||N){if(X=this._getOrReturnCtx($,X),A)g(X,{code:Z.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(N)g(X,{code:Z.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});E.dirty()}}else if(G.kind==="email"){if(!EP.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"email",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="emoji"){if(!SO)SO=new RegExp(XP,"u");if(!SO.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"emoji",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="uuid"){if(!aV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"uuid",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="nanoid"){if(!eV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"nanoid",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid"){if(!dV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid2"){if(!lV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid2",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ulid"){if(!sV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"ulid",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),g(X,{validation:"url",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"regex",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))X=this._getOrReturnCtx($,X),g(X,{code:Z.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),E.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:Z.invalid_string,validation:{startsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:Z.invalid_string,validation:{endsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="datetime"){if(!i9(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:Z.invalid_string,validation:"datetime",message:G.message}),E.dirty()}else if(G.kind==="date"){if(!JP.test($.data))X=this._getOrReturnCtx($,X),g(X,{code:Z.invalid_string,validation:"date",message:G.message}),E.dirty()}else if(G.kind==="time"){if(!UP(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:Z.invalid_string,validation:"time",message:G.message}),E.dirty()}else if(G.kind==="duration"){if(!wP.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"duration",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ip"){if(!YP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"ip",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="jwt"){if(!HP($.data,G.alg))X=this._getOrReturnCtx($,X),g(X,{validation:"jwt",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cidr"){if(!LP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"cidr",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64"){if(!OP.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64",code:Z.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64url"){if(!WP.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64url",code:Z.invalid_string,message:G.message}),E.dirty()}else U0.assertNever(G);return{status:E.value,value:$.data}}_regex($,w,E){return this.refinement((X)=>$.test(X),{validation:w,code:Z.invalid_string,...c.errToObj(E)})}_addCheck($){return new Kw({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...c.errToObj($)})}url($){return this._addCheck({kind:"url",...c.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...c.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...c.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...c.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...c.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...c.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...c.errToObj($)})}base64($){return this._addCheck({kind:"base64",...c.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...c.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...c.errToObj($)})}ip($){return this._addCheck({kind:"ip",...c.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...c.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...c.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...c.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...c.errToObj($)})}regex($,w){return this._addCheck({kind:"regex",regex:$,...c.errToObj(w)})}includes($,w){return this._addCheck({kind:"includes",value:$,position:w?.position,...c.errToObj(w?.message)})}startsWith($,w){return this._addCheck({kind:"startsWith",value:$,...c.errToObj(w)})}endsWith($,w){return this._addCheck({kind:"endsWith",value:$,...c.errToObj(w)})}min($,w){return this._addCheck({kind:"min",value:$,...c.errToObj(w)})}max($,w){return this._addCheck({kind:"max",value:$,...c.errToObj(w)})}length($,w){return this._addCheck({kind:"length",value:$,...c.errToObj(w)})}nonempty($){return this.min(1,c.errToObj($))}trim(){return new Kw({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Kw({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Kw({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxLength(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};Kw.create=($)=>{return new Kw({checks:[],typeName:a.ZodString,coerce:$?.coerce??!1,...X0($)})};CE=class CE extends A0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==x.number){let G=this._getOrReturnCtx($);return g(G,{code:Z.invalid_type,expected:x.number,received:G.parsedType}),l}let E=void 0,X=new T$;for(let G of this._def.checks)if(G.kind==="int"){if(!U0.isInteger($.data))E=this._getOrReturnCtx($,E),g(E,{code:Z.invalid_type,expected:"integer",received:"float",message:G.message}),X.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:Z.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:Z.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if(FP($.data,G.value)!==0)E=this._getOrReturnCtx($,E),g(E,{code:Z.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))E=this._getOrReturnCtx($,E),g(E,{code:Z.not_finite,message:G.message}),X.dirty()}else U0.assertNever(G);return{status:X.value,value:$.data}}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new CE({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new CE({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:c.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}finite($){return this._addCheck({kind:"finite",message:c.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:c.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:c.toString($)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&U0.isInteger($.value))}get isFinite(){let $=null,w=null;for(let E of this._def.checks)if(E.kind==="finite"||E.kind==="int"||E.kind==="multipleOf")return!0;else if(E.kind==="min"){if(w===null||E.value>w)w=E.value}else if(E.kind==="max"){if($===null||E.value<$)$=E.value}return Number.isFinite(w)&&Number.isFinite($)}};CE.create=($)=>{return new CE({checks:[],typeName:a.ZodNumber,coerce:$?.coerce||!1,...X0($)})};fE=class fE extends A0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==x.bigint)return this._getInvalidInput($);let E=void 0,X=new T$;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:Z.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:Z.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))E=this._getOrReturnCtx($,E),g(E,{code:Z.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else U0.assertNever(G);return{status:X.value,value:$.data}}_getInvalidInput($){let w=this._getOrReturnCtx($);return g(w,{code:Z.invalid_type,expected:x.bigint,received:w.parsedType}),l}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new fE({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new fE({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};fE.create=($)=>{return new fE({checks:[],typeName:a.ZodBigInt,coerce:$?.coerce??!1,...X0($)})};h1=class h1 extends A0{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==x.boolean){let E=this._getOrReturnCtx($);return g(E,{code:Z.invalid_type,expected:x.boolean,received:E.parsedType}),l}return _$($.data)}};h1.create=($)=>{return new h1({typeName:a.ZodBoolean,coerce:$?.coerce||!1,...X0($)})};O1=class O1 extends A0{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==x.date){let G=this._getOrReturnCtx($);return g(G,{code:Z.invalid_type,expected:x.date,received:G.parsedType}),l}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return g(G,{code:Z.invalid_date}),l}let E=new T$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)X=this._getOrReturnCtx($,X),g(X,{code:Z.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),E.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)X=this._getOrReturnCtx($,X),g(X,{code:Z.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),E.dirty()}else U0.assertNever(G);return{status:E.value,value:new Date($.data.getTime())}}_addCheck($){return new O1({...this._def,checks:[...this._def.checks,$]})}min($,w){return this._addCheck({kind:"min",value:$.getTime(),message:c.toString(w)})}max($,w){return this._addCheck({kind:"max",value:$.getTime(),message:c.toString(w)})}get minDate(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $!=null?new Date($):null}};O1.create=($)=>{return new O1({checks:[],coerce:$?.coerce||!1,typeName:a.ZodDate,...X0($)})};OG=class OG extends A0{_parse($){if(this._getType($)!==x.symbol){let E=this._getOrReturnCtx($);return g(E,{code:Z.invalid_type,expected:x.symbol,received:E.parsedType}),l}return _$($.data)}};OG.create=($)=>{return new OG({typeName:a.ZodSymbol,...X0($)})};c1=class c1 extends A0{_parse($){if(this._getType($)!==x.undefined){let E=this._getOrReturnCtx($);return g(E,{code:Z.invalid_type,expected:x.undefined,received:E.parsedType}),l}return _$($.data)}};c1.create=($)=>{return new c1({typeName:a.ZodUndefined,...X0($)})};r1=class r1 extends A0{_parse($){if(this._getType($)!==x.null){let E=this._getOrReturnCtx($);return g(E,{code:Z.invalid_type,expected:x.null,received:E.parsedType}),l}return _$($.data)}};r1.create=($)=>{return new r1({typeName:a.ZodNull,...X0($)})};W1=class W1 extends A0{constructor(){super(...arguments);this._any=!0}_parse($){return _$($.data)}};W1.create=($)=>{return new W1({typeName:a.ZodAny,...X0($)})};ZE=class ZE extends A0{constructor(){super(...arguments);this._unknown=!0}_parse($){return _$($.data)}};ZE.create=($)=>{return new ZE({typeName:a.ZodUnknown,...X0($)})};mw=class mw extends A0{_parse($){let w=this._getOrReturnCtx($);return g(w,{code:Z.invalid_type,expected:x.never,received:w.parsedType}),l}};mw.create=($)=>{return new mw({typeName:a.ZodNever,...X0($)})};WG=class WG extends A0{_parse($){if(this._getType($)!==x.undefined){let E=this._getOrReturnCtx($);return g(E,{code:Z.invalid_type,expected:x.void,received:E.parsedType}),l}return _$($.data)}};WG.create=($)=>{return new WG({typeName:a.ZodVoid,...X0($)})};Vw=class Vw extends A0{_parse($){let{ctx:w,status:E}=this._processInputParams($),X=this._def;if(w.parsedType!==x.array)return g(w,{code:Z.invalid_type,expected:x.array,received:w.parsedType}),l;if(X.exactLength!==null){let A=w.data.length>X.exactLength.value,N=w.data.length<X.exactLength.value;if(A||N)g(w,{code:A?Z.too_big:Z.too_small,minimum:N?X.exactLength.value:void 0,maximum:A?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),E.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)g(w,{code:Z.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),E.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)g(w,{code:Z.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),E.dirty()}if(w.common.async)return Promise.all([...w.data].map((A,N)=>{return X.type._parseAsync(new qw(w,A,w.path,N))})).then((A)=>{return T$.mergeArray(E,A)});let G=[...w.data].map((A,N)=>{return X.type._parseSync(new qw(w,A,w.path,N))});return T$.mergeArray(E,G)}get element(){return this._def.type}min($,w){return new Vw({...this._def,minLength:{value:$,message:c.toString(w)}})}max($,w){return new Vw({...this._def,maxLength:{value:$,message:c.toString(w)}})}length($,w){return new Vw({...this._def,exactLength:{value:$,message:c.toString(w)}})}nonempty($){return this.min(1,$)}};Vw.create=($,w)=>{return new Vw({type:$,minLength:null,maxLength:null,exactLength:null,typeName:a.ZodArray,...X0(w)})};s0=class s0 extends A0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),w=U0.objectKeys($);return this._cached={shape:$,keys:w},this._cached}_parse($){if(this._getType($)!==x.object){let O=this._getOrReturnCtx($);return g(O,{code:Z.invalid_type,expected:x.object,received:O.parsedType}),l}let{status:E,ctx:X}=this._processInputParams($),{shape:G,keys:A}=this._getCached(),N=[];if(!(this._def.catchall instanceof mw&&this._def.unknownKeys==="strip")){for(let O in X.data)if(!A.includes(O))N.push(O)}let D=[];for(let O of A){let W=G[O],J=X.data[O];D.push({key:{status:"valid",value:O},value:W._parse(new qw(X,J,X.path,O)),alwaysSet:O in X.data})}if(this._def.catchall instanceof mw){let O=this._def.unknownKeys;if(O==="passthrough")for(let W of N)D.push({key:{status:"valid",value:W},value:{status:"valid",value:X.data[W]}});else if(O==="strict"){if(N.length>0)g(X,{code:Z.unrecognized_keys,keys:N}),E.dirty()}else if(O==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let O=this._def.catchall;for(let W of N){let J=X.data[W];D.push({key:{status:"valid",value:W},value:O._parse(new qw(X,J,X.path,W)),alwaysSet:W in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let O=[];for(let W of D){let J=await W.key,Y=await W.value;O.push({key:J,value:Y,alwaysSet:W.alwaysSet})}return O}).then((O)=>{return T$.mergeObjectSync(E,O)});else return T$.mergeObjectSync(E,D)}get shape(){return this._def.shape()}strict($){return c.errToObj,new s0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(w,E)=>{let X=this._def.errorMap?.(w,E).message??E.defaultError;if(w.code==="unrecognized_keys")return{message:c.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new s0({...this._def,unknownKeys:"strip"})}passthrough(){return new s0({...this._def,unknownKeys:"passthrough"})}extend($){return new s0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new s0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:a.ZodObject})}setKey($,w){return this.augment({[$]:w})}catchall($){return new s0({...this._def,catchall:$})}pick($){let w={};for(let E of U0.objectKeys($))if($[E]&&this.shape[E])w[E]=this.shape[E];return new s0({...this._def,shape:()=>w})}omit($){let w={};for(let E of U0.objectKeys(this.shape))if(!$[E])w[E]=this.shape[E];return new s0({...this._def,shape:()=>w})}deepPartial(){return u1(this)}partial($){let w={};for(let E of U0.objectKeys(this.shape)){let X=this.shape[E];if($&&!$[E])w[E]=X;else w[E]=X.optional()}return new s0({...this._def,shape:()=>w})}required($){let w={};for(let E of U0.objectKeys(this.shape))if($&&!$[E])w[E]=this.shape[E];else{let G=this.shape[E];while(G instanceof Pw)G=G._def.innerType;w[E]=G}return new s0({...this._def,shape:()=>w})}keyof(){return p9(U0.objectKeys(this.shape))}};s0.create=($,w)=>{return new s0({shape:()=>$,unknownKeys:"strip",catchall:mw.create(),typeName:a.ZodObject,...X0(w)})};s0.strictCreate=($,w)=>{return new s0({shape:()=>$,unknownKeys:"strict",catchall:mw.create(),typeName:a.ZodObject,...X0(w)})};s0.lazycreate=($,w)=>{return new s0({shape:$,unknownKeys:"strip",catchall:mw.create(),typeName:a.ZodObject,...X0(w)})};t1=class t1 extends A0{_parse($){let{ctx:w}=this._processInputParams($),E=this._def.options;function X(G){for(let N of G)if(N.result.status==="valid")return N.result;for(let N of G)if(N.result.status==="dirty")return w.common.issues.push(...N.ctx.common.issues),N.result;let A=G.map((N)=>new p$(N.ctx.common.issues));return g(w,{code:Z.invalid_union,unionErrors:A}),l}if(w.common.async)return Promise.all(E.map(async(G)=>{let A={...w,common:{...w.common,issues:[]},parent:null};return{result:await G._parseAsync({data:w.data,path:w.path,parent:A}),ctx:A}})).then(X);else{let G=void 0,A=[];for(let D of E){let O={...w,common:{...w.common,issues:[]},parent:null},W=D._parseSync({data:w.data,path:w.path,parent:O});if(W.status==="valid")return W;else if(W.status==="dirty"&&!G)G={result:W,ctx:O};if(O.common.issues.length)A.push(O.common.issues)}if(G)return w.common.issues.push(...G.ctx.common.issues),G.result;let N=A.map((D)=>new p$(D));return g(w,{code:Z.invalid_union,unionErrors:N}),l}}get options(){return this._def.options}};t1.create=($,w)=>{return new t1({options:$,typeName:a.ZodUnion,...X0(w)})};jN=class jN extends A0{_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==x.object)return g(w,{code:Z.invalid_type,expected:x.object,received:w.parsedType}),l;let E=this.discriminator,X=w.data[E],G=this.optionsMap.get(X);if(!G)return g(w,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[E]}),l;if(w.common.async)return G._parseAsync({data:w.data,path:w.path,parent:w});else return G._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,w,E){let X=new Map;for(let G of w){let A=JE(G.shape[$]);if(!A.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let N of A){if(X.has(N))throw Error(`Discriminator property ${String($)} has duplicate value ${String(N)}`);X.set(N,G)}}return new jN({typeName:a.ZodDiscriminatedUnion,discriminator:$,options:w,optionsMap:X,...X0(E)})}};o1=class o1 extends A0{_parse($){let{status:w,ctx:E}=this._processInputParams($),X=(G,A)=>{if(LN(G)||LN(A))return l;let N=kO(G.value,A.value);if(!N.valid)return g(E,{code:Z.invalid_intersection_types}),l;if(FN(G)||FN(A))w.dirty();return{status:w.value,value:N.data}};if(E.common.async)return Promise.all([this._def.left._parseAsync({data:E.data,path:E.path,parent:E}),this._def.right._parseAsync({data:E.data,path:E.path,parent:E})]).then(([G,A])=>X(G,A));else return X(this._def.left._parseSync({data:E.data,path:E.path,parent:E}),this._def.right._parseSync({data:E.data,path:E.path,parent:E}))}};o1.create=($,w,E)=>{return new o1({left:$,right:w,typeName:a.ZodIntersection,...X0(E)})};iw=class iw extends A0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==x.array)return g(E,{code:Z.invalid_type,expected:x.array,received:E.parsedType}),l;if(E.data.length<this._def.items.length)return g(E,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),l;if(!this._def.rest&&E.data.length>this._def.items.length)g(E,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let G=[...E.data].map((A,N)=>{let D=this._def.items[N]||this._def.rest;if(!D)return null;return D._parse(new qw(E,A,E.path,N))}).filter((A)=>!!A);if(E.common.async)return Promise.all(G).then((A)=>{return T$.mergeArray(w,A)});else return T$.mergeArray(w,G)}get items(){return this._def.items}rest($){return new iw({...this._def,rest:$})}};iw.create=($,w)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new iw({items:$,typeName:a.ZodTuple,rest:null,...X0(w)})};JG=class JG extends A0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==x.object)return g(E,{code:Z.invalid_type,expected:x.object,received:E.parsedType}),l;let X=[],G=this._def.keyType,A=this._def.valueType;for(let N in E.data)X.push({key:G._parse(new qw(E,N,E.path,N)),value:A._parse(new qw(E,E.data[N],E.path,N)),alwaysSet:N in E.data});if(E.common.async)return T$.mergeObjectAsync(w,X);else return T$.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create($,w,E){if(w instanceof A0)return new JG({keyType:$,valueType:w,typeName:a.ZodRecord,...X0(E)});return new JG({keyType:Kw.create(),valueType:$,typeName:a.ZodRecord,...X0(w)})}};UG=class UG extends A0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==x.map)return g(E,{code:Z.invalid_type,expected:x.map,received:E.parsedType}),l;let X=this._def.keyType,G=this._def.valueType,A=[...E.data.entries()].map(([N,D],O)=>{return{key:X._parse(new qw(E,N,E.path,[O,"key"])),value:G._parse(new qw(E,D,E.path,[O,"value"]))}});if(E.common.async){let N=new Map;return Promise.resolve().then(async()=>{for(let D of A){let O=await D.key,W=await D.value;if(O.status==="aborted"||W.status==="aborted")return l;if(O.status==="dirty"||W.status==="dirty")w.dirty();N.set(O.value,W.value)}return{status:w.value,value:N}})}else{let N=new Map;for(let D of A){let{key:O,value:W}=D;if(O.status==="aborted"||W.status==="aborted")return l;if(O.status==="dirty"||W.status==="dirty")w.dirty();N.set(O.value,W.value)}return{status:w.value,value:N}}}};UG.create=($,w,E)=>{return new UG({valueType:w,keyType:$,typeName:a.ZodMap,...X0(E)})};J1=class J1 extends A0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==x.set)return g(E,{code:Z.invalid_type,expected:x.set,received:E.parsedType}),l;let X=this._def;if(X.minSize!==null){if(E.data.size<X.minSize.value)g(E,{code:Z.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if(E.data.size>X.maxSize.value)g(E,{code:Z.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let G=this._def.valueType;function A(D){let O=new Set;for(let W of D){if(W.status==="aborted")return l;if(W.status==="dirty")w.dirty();O.add(W.value)}return{status:w.value,value:O}}let N=[...E.data.values()].map((D,O)=>G._parse(new qw(E,D,E.path,O)));if(E.common.async)return Promise.all(N).then((D)=>A(D));else return A(N)}min($,w){return new J1({...this._def,minSize:{value:$,message:c.toString(w)}})}max($,w){return new J1({...this._def,maxSize:{value:$,message:c.toString(w)}})}size($,w){return this.min($,w).max($,w)}nonempty($){return this.min(1,$)}};J1.create=($,w)=>{return new J1({valueType:$,minSize:null,maxSize:null,typeName:a.ZodSet,...X0(w)})};n1=class n1 extends A0{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==x.function)return g(w,{code:Z.invalid_type,expected:x.function,received:w.parsedType}),l;function E(N,D){return DG({data:N,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,y1(),WE].filter((O)=>!!O),issueData:{code:Z.invalid_arguments,argumentsError:D}})}function X(N,D){return DG({data:N,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,y1(),WE].filter((O)=>!!O),issueData:{code:Z.invalid_return_type,returnTypeError:D}})}let G={errorMap:w.common.contextualErrorMap},A=w.data;if(this._def.returns instanceof U1){let N=this;return _$(async function(...D){let O=new p$([]),W=await N._def.args.parseAsync(D,G).catch((H)=>{throw O.addIssue(E(D,H)),O}),J=await Reflect.apply(A,this,W);return await N._def.returns._def.type.parseAsync(J,G).catch((H)=>{throw O.addIssue(X(J,H)),O})})}else{let N=this;return _$(function(...D){let O=N._def.args.safeParse(D,G);if(!O.success)throw new p$([E(D,O.error)]);let W=Reflect.apply(A,this,O.data),J=N._def.returns.safeParse(W,G);if(!J.success)throw new p$([X(W,J.error)]);return J.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new n1({...this._def,args:iw.create($).rest(ZE.create())})}returns($){return new n1({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,w,E){return new n1({args:$?$:iw.create([]).rest(ZE.create()),returns:w||ZE.create(),typeName:a.ZodFunction,...X0(E)})}};m1=class m1 extends A0{get schema(){return this._def.getter()}_parse($){let{ctx:w}=this._processInputParams($);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}};m1.create=($,w)=>{return new m1({getter:$,typeName:a.ZodLazy,...X0(w)})};i1=class i1 extends A0{_parse($){if($.data!==this._def.value){let w=this._getOrReturnCtx($);return g(w,{received:w.data,code:Z.invalid_literal,expected:this._def.value}),l}return{status:"valid",value:$.data}}get value(){return this._def.value}};i1.create=($,w)=>{return new i1({value:$,typeName:a.ZodLiteral,...X0(w)})};vE=class vE extends A0{_parse($){if(typeof $.data!=="string"){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{expected:U0.joinValues(E),received:w.parsedType,code:Z.invalid_type}),l}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{received:w.data,code:Z.invalid_enum_value,options:E}),l}return _$($.data)}get options(){return this._def.values}get enum(){let $={};for(let w of this._def.values)$[w]=w;return $}get Values(){let $={};for(let w of this._def.values)$[w]=w;return $}get Enum(){let $={};for(let w of this._def.values)$[w]=w;return $}extract($,w=this._def){return vE.create($,{...this._def,...w})}exclude($,w=this._def){return vE.create(this.options.filter((E)=>!$.includes(E)),{...this._def,...w})}};vE.create=p9;p1=class p1 extends A0{_parse($){let w=U0.getValidEnumValues(this._def.values),E=this._getOrReturnCtx($);if(E.parsedType!==x.string&&E.parsedType!==x.number){let X=U0.objectValues(w);return g(E,{expected:U0.joinValues(X),received:E.parsedType,code:Z.invalid_type}),l}if(!this._cache)this._cache=new Set(U0.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=U0.objectValues(w);return g(E,{received:E.data,code:Z.invalid_enum_value,options:X}),l}return _$($.data)}get enum(){return this._def.values}};p1.create=($,w)=>{return new p1({values:$,typeName:a.ZodNativeEnum,...X0(w)})};U1=class U1 extends A0{unwrap(){return this._def.type}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==x.promise&&w.common.async===!1)return g(w,{code:Z.invalid_type,expected:x.promise,received:w.parsedType}),l;let E=w.parsedType===x.promise?w.data:Promise.resolve(w.data);return _$(E.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}};U1.create=($,w)=>{return new U1({type:$,typeName:a.ZodPromise,...X0(w)})};Sw=class Sw extends A0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===a.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:w,ctx:E}=this._processInputParams($),X=this._def.effect||null,G={addIssue:(A)=>{if(g(E,A),A.fatal)w.abort();else w.dirty()},get path(){return E.path}};if(G.addIssue=G.addIssue.bind(G),X.type==="preprocess"){let A=X.transform(E.data,G);if(E.common.async)return Promise.resolve(A).then(async(N)=>{if(w.value==="aborted")return l;let D=await this._def.schema._parseAsync({data:N,path:E.path,parent:E});if(D.status==="aborted")return l;if(D.status==="dirty")return D1(D.value);if(w.value==="dirty")return D1(D.value);return D});else{if(w.value==="aborted")return l;let N=this._def.schema._parseSync({data:A,path:E.path,parent:E});if(N.status==="aborted")return l;if(N.status==="dirty")return D1(N.value);if(w.value==="dirty")return D1(N.value);return N}}if(X.type==="refinement"){let A=(N)=>{let D=X.refinement(N,G);if(E.common.async)return Promise.resolve(D);if(D instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return N};if(E.common.async===!1){let N=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(N.status==="aborted")return l;if(N.status==="dirty")w.dirty();return A(N.value),{status:w.value,value:N.value}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((N)=>{if(N.status==="aborted")return l;if(N.status==="dirty")w.dirty();return A(N.value).then(()=>{return{status:w.value,value:N.value}})})}if(X.type==="transform")if(E.common.async===!1){let A=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(!_E(A))return l;let N=X.transform(A.value,G);if(N instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:N}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((A)=>{if(!_E(A))return l;return Promise.resolve(X.transform(A.value,G)).then((N)=>({status:w.value,value:N}))});U0.assertNever(X)}};Sw.create=($,w,E)=>{return new Sw({schema:$,typeName:a.ZodEffects,effect:w,...X0(E)})};Sw.createWithPreprocess=($,w,E)=>{return new Sw({schema:w,effect:{type:"preprocess",transform:$},typeName:a.ZodEffects,...X0(E)})};Pw=class Pw extends A0{_parse($){if(this._getType($)===x.undefined)return _$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};Pw.create=($,w)=>{return new Pw({innerType:$,typeName:a.ZodOptional,...X0(w)})};UE=class UE extends A0{_parse($){if(this._getType($)===x.null)return _$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};UE.create=($,w)=>{return new UE({innerType:$,typeName:a.ZodNullable,...X0(w)})};d1=class d1 extends A0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;if(w.parsedType===x.undefined)E=this._def.defaultValue();return this._def.innerType._parse({data:E,path:w.path,parent:w})}removeDefault(){return this._def.innerType}};d1.create=($,w)=>{return new d1({innerType:$,typeName:a.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...X0(w)})};l1=class l1 extends A0{_parse($){let{ctx:w}=this._processInputParams($),E={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:E.data,path:E.path,parent:{...E}});if(g1(X))return X.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new p$(E.common.issues)},input:E.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new p$(E.common.issues)},input:E.data})}}removeCatch(){return this._def.innerType}};l1.create=($,w)=>{return new l1({innerType:$,typeName:a.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...X0(w)})};YG=class YG extends A0{_parse($){if(this._getType($)!==x.nan){let E=this._getOrReturnCtx($);return g(E,{code:Z.invalid_type,expected:x.nan,received:E.parsedType}),l}return{status:"valid",value:$.data}}};YG.create=($)=>{return new YG({typeName:a.ZodNaN,...X0($)})};jP=Symbol("zod_brand");MN=class MN extends A0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;return this._def.type._parse({data:E,path:w.path,parent:w})}unwrap(){return this._def.type}};HG=class HG extends A0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:E.data,path:E.path,parent:E});if(G.status==="aborted")return l;if(G.status==="dirty")return w.dirty(),D1(G.value);else return this._def.out._parseAsync({data:G.value,path:E.path,parent:E})})();else{let X=this._def.in._parseSync({data:E.data,path:E.path,parent:E});if(X.status==="aborted")return l;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:E.path,parent:E})}}static create($,w){return new HG({in:$,out:w,typeName:a.ZodPipeline})}};s1=class s1 extends A0{_parse($){let w=this._def.innerType._parse($),E=(X)=>{if(_E(X))X.value=Object.freeze(X.value);return X};return g1(w)?w.then((X)=>E(X)):E(w)}unwrap(){return this._def.innerType}};s1.create=($,w)=>{return new s1({innerType:$,typeName:a.ZodReadonly,...X0(w)})};MP={object:s0.lazycreate};(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(a||(a={}));l9=Kw.create,s9=CE.create,RP=YG.create,zP=fE.create,a9=h1.create,BP=O1.create,IP=OG.create,QP=c1.create,KP=r1.create,VP=W1.create,PP=ZE.create,qP=mw.create,SP=WG.create,kP=Vw.create,bP=s0.create,_P=s0.strictCreate,ZP=t1.create,CP=jN.create,fP=o1.create,vP=iw.create,xP=JG.create,yP=UG.create,gP=J1.create,uP=n1.create,nP=m1.create,hP=i1.create,cP=vE.create,rP=p1.create,tP=U1.create,oP=Sw.create,mP=Pw.create,iP=UE.create,pP=Sw.createWithPreprocess,dP=HG.create,eP={string:($)=>Kw.create({...$,coerce:!0}),number:($)=>CE.create({...$,coerce:!0}),boolean:($)=>h1.create({...$,coerce:!0}),bigint:($)=>fE.create({...$,coerce:!0}),date:($)=>O1.create({...$,coerce:!0})},$q=l});var U={};OE(U,{void:()=>SP,util:()=>U0,unknown:()=>PP,union:()=>ZP,undefined:()=>QP,tuple:()=>vP,transformer:()=>oP,symbol:()=>IP,string:()=>l9,strictObject:()=>_P,setErrorMap:()=>iV,set:()=>gP,record:()=>xP,quotelessJson:()=>oV,promise:()=>tP,preprocess:()=>pP,pipeline:()=>dP,ostring:()=>lP,optional:()=>mP,onumber:()=>sP,oboolean:()=>aP,objectUtil:()=>VO,object:()=>bP,number:()=>s9,nullable:()=>iP,null:()=>KP,never:()=>qP,nativeEnum:()=>rP,nan:()=>RP,map:()=>yP,makeIssue:()=>DG,literal:()=>hP,lazy:()=>nP,late:()=>MP,isValid:()=>_E,isDirty:()=>FN,isAsync:()=>g1,isAborted:()=>LN,intersection:()=>fP,instanceof:()=>TP,getParsedType:()=>ow,getErrorMap:()=>y1,function:()=>uP,enum:()=>cP,effect:()=>oP,discriminatedUnion:()=>CP,defaultErrorMap:()=>WE,datetimeRegex:()=>i9,date:()=>BP,custom:()=>d9,coerce:()=>eP,boolean:()=>a9,bigint:()=>zP,array:()=>kP,any:()=>VP,addIssueToContext:()=>g,ZodVoid:()=>WG,ZodUnknown:()=>ZE,ZodUnion:()=>t1,ZodUndefined:()=>c1,ZodType:()=>A0,ZodTuple:()=>iw,ZodTransformer:()=>Sw,ZodSymbol:()=>OG,ZodString:()=>Kw,ZodSet:()=>J1,ZodSchema:()=>A0,ZodRecord:()=>JG,ZodReadonly:()=>s1,ZodPromise:()=>U1,ZodPipeline:()=>HG,ZodParsedType:()=>x,ZodOptional:()=>Pw,ZodObject:()=>s0,ZodNumber:()=>CE,ZodNullable:()=>UE,ZodNull:()=>r1,ZodNever:()=>mw,ZodNativeEnum:()=>p1,ZodNaN:()=>YG,ZodMap:()=>UG,ZodLiteral:()=>i1,ZodLazy:()=>m1,ZodIssueCode:()=>Z,ZodIntersection:()=>o1,ZodFunction:()=>n1,ZodFirstPartyTypeKind:()=>a,ZodError:()=>p$,ZodEnum:()=>vE,ZodEffects:()=>Sw,ZodDiscriminatedUnion:()=>jN,ZodDefault:()=>d1,ZodDate:()=>O1,ZodCatch:()=>l1,ZodBranded:()=>MN,ZodBoolean:()=>h1,ZodBigInt:()=>fE,ZodArray:()=>Vw,ZodAny:()=>W1,Schema:()=>A0,ParseStatus:()=>T$,OK:()=>_$,NEVER:()=>$q,INVALID:()=>l,EMPTY_PATH:()=>pV,DIRTY:()=>D1,BRAND:()=>jP});var bO=T(()=>{HN();qO();h9();NG();e9();YN()});var LG=T(()=>{bO();bO()});import{existsSync as $5,readFileSync as wq}from"fs";import{homedir as X5}from"os";import{join as _O}from"path";function Nq($){if($.startsWith("~/"))return _O(X5(),$.slice(2));return $}function E5($){try{return JSON.parse(wq($,"utf-8"))}catch{return{}}}function FG($,w){let E={...$};for(let[X,G]of Object.entries(w))if(G!==null&&typeof G==="object"&&!Array.isArray(G)&&typeof E[X]==="object"&&E[X]!==null)E[X]=FG(E[X],G);else E[X]=G;return E}function Dq(){let $={};if(process.env.ORC_DB_PATH)$.db={path:process.env.ORC_DB_PATH};let w={};if(process.env.ORC_API_PORT)w.port=Number(process.env.ORC_API_PORT);if(process.env.ORC_API_HOST)w.host=process.env.ORC_API_HOST;if(process.env.ORC_API_SECRET)w.secret=process.env.ORC_API_SECRET;if(Object.keys(w).length)$.api=w;let E={};if(process.env.ORC_RUNNER_TIMEOUT)E.default_timeout_secs=Number(process.env.ORC_RUNNER_TIMEOUT);if(process.env.ORC_RUNNER_MAX_JOBS)E.max_concurrent_jobs=Number(process.env.ORC_RUNNER_MAX_JOBS);if(process.env.ORC_RUNNER_LOG_DAYS)E.log_retention_days=Number(process.env.ORC_RUNNER_LOG_DAYS);if(Object.keys(E).length)$.runner=E;let X={};if(process.env.ORC_SNAPSHOT_MAX_BYTES)X.snapshot_max_bytes=Number(process.env.ORC_SNAPSHOT_MAX_BYTES);if(process.env.ORC_LAYER1_TASKS)X.layer1_task_limit=Number(process.env.ORC_LAYER1_TASKS);if(process.env.ORC_LAYER1_MEMORIES)X.layer1_memory_limit=Number(process.env.ORC_LAYER1_MEMORIES);if(Object.keys(X).length)$.context=X;let G={};if(process.env.ORC_AGENT_LOOP_ENABLED)G.enabled=process.env.ORC_AGENT_LOOP_ENABLED==="true";if(process.env.ORC_AGENT_LOOP_POLL_INTERVAL)G.poll_interval_minutes=Number(process.env.ORC_AGENT_LOOP_POLL_INTERVAL);if(process.env.ORC_AGENT_LOOP_MAX_WORKERS)G.max_workers=Number(process.env.ORC_AGENT_LOOP_MAX_WORKERS);if(process.env.ORC_AGENT_LOOP_DEFAULT_BACKEND)G.default_backend=process.env.ORC_AGENT_LOOP_DEFAULT_BACKEND;if(process.env.ORC_AGENT_LOOP_IDLE_TIMEOUT)G.session_idle_timeout_minutes=Number(process.env.ORC_AGENT_LOOP_IDLE_TIMEOUT);if(process.env.ORC_AGENT_LOOP_AUTO_APPROVE)G.worker_auto_approve=process.env.ORC_AGENT_LOOP_AUTO_APPROVE==="true";if(Object.keys(G).length)$.agent_loop=G;let A={};if(process.env.ORC_TELEGRAM_TOKEN)A.telegram={token:process.env.ORC_TELEGRAM_TOKEN,enabled:!0};if(process.env.ORC_SLACK_BOT_TOKEN||process.env.ORC_SLACK_APP_TOKEN)A.slack={bot_token:process.env.ORC_SLACK_BOT_TOKEN,app_token:process.env.ORC_SLACK_APP_TOKEN,enabled:!0};if(Object.keys(A).length)$.gateway=A;let N={};if(process.env.ORC_SPEECH_PROVIDER)N.provider=process.env.ORC_SPEECH_PROVIDER;if(process.env.ORC_SPEECH_LANGUAGE)N.language=process.env.ORC_SPEECH_LANGUAGE;if(process.env.ORC_OPENAI_API_KEY)N.openai={api_key:process.env.ORC_OPENAI_API_KEY};if(process.env.ORC_GROQ_API_KEY)N.groq={api_key:process.env.ORC_GROQ_API_KEY};if(process.env.ORC_QWEN_API_KEY)N.qwen={api_key:process.env.ORC_QWEN_API_KEY};if(Object.keys(N).length)N.enabled=!0,$.speech=N;let D={};if(process.env.ORC_TTS_PROVIDER)D.provider=process.env.ORC_TTS_PROVIDER;if(process.env.ORC_TTS_VOICE)D.voice=process.env.ORC_TTS_VOICE;if(process.env.ORC_TTS_MODE)D.mode=process.env.ORC_TTS_MODE;if(Object.keys(D).length)D.enabled=!0,$.tts=D;return $}function G0($){if(TN&&!$)return TN;let w=_O(X5(),".orc","config.json"),E=_O(process.cwd(),".orc","config.json"),X={};if($5(w))X=FG(X,E5(w));if($5(E))X=FG(X,E5(E));if(X=FG(X,Dq()),$)X=FG(X,$);if(X.bridge&&!X.gateway)X.gateway=X.bridge;delete X.bridge;let G=Aq.safeParse(X);if(!G.success)throw Error(`Invalid orc config:
4
+ ${G.error.message}`);return G.data.db.path=Nq(G.data.db.path),TN=G.data,TN}var Eq,w5,jG,Xq,Gq,Aq,TN=null;var R$=T(()=>{LG();Eq=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")).default("direct"),w5=U.object({enabled:U.boolean().default(!1),token:U.string().optional(),bot_token:U.string().optional(),app_token:U.string().optional(),authorized_users:U.array(U.union([U.string(),U.number()])).default([]),default_chat_id:U.string().optional(),mode:Eq,allow_channel_mentions:U.boolean().default(!0),share_session_in_channel:U.boolean().default(!1),streaming_preview:U.boolean().default(!0)}),jG=U.object({api_key:U.string().optional(),base_url:U.string().optional(),model:U.string().optional()}),Xq=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","groq","qwen"]).default("openai"),language:U.string().default(""),openai:jG.default({}),groq:jG.default({}),qwen:jG.default({})}),Gq=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","qwen"]).default("openai"),voice:U.string().default("alloy"),mode:U.enum(["voice_only","always"]).default("voice_only"),max_text_len:U.number().int().min(0).default(0),openai:jG.default({}),qwen:jG.default({})}),Aq=U.object({db:U.object({path:U.string().default("~/.orc/orc.db")}).default({}),api:U.object({port:U.number().int().default(7700),host:U.string().default("127.0.0.1"),secret:U.string().optional()}).default({}),mcp:U.object({transport:U.enum(["stdio","http"]).default("stdio"),port:U.number().int().default(7701)}).default({}),gateway:U.object({telegram:w5.default({}),slack:w5.default({})}).default({}),runner:U.object({default_timeout_secs:U.number().int().default(300),max_concurrent_jobs:U.number().int().default(5),log_retention_days:U.number().int().default(30)}).default({}),context:U.object({snapshot_max_bytes:U.number().int().default(2048),layer1_task_limit:U.number().int().default(10),layer1_memory_limit:U.number().int().default(5)}).default({}),agent_loop:U.object({enabled:U.boolean().default(!1),poll_interval_minutes:U.number().int().min(1).default(5),max_workers:U.number().int().min(1).default(1),default_backend:U.enum(["claude","codex","cursor"]).default("claude"),session_idle_timeout_minutes:U.number().int().min(1).default(20),worker_auto_approve:U.boolean().default(!0)}).default({}),speech:Xq.default({}),tts:Gq.default({}),activeProject:U.string().optional()})});import{readFileSync as Oq}from"fs";import{dirname as Wq,join as Jq}from"path";import{fileURLToPath as Uq}from"url";var ZO,a1;var RN=T(()=>{try{let $=Wq(Uq(import.meta.url));ZO=JSON.parse(Oq(Jq($,"..","package.json"),"utf-8")).version}catch{ZO=process.env.ORC_VERSION??"0.0.0"}a1=ZO});var MG=_((Yq)=>{class CO extends Error{constructor($,w,E){super(E);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class G5 extends CO{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Yq.CommanderError=CO;Yq.InvalidArgumentError=G5});var zN=_((Mq)=>{var{InvalidArgumentError:Fq}=MG();class A5{constructor($,w){switch(this.description=w||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.concat($)}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(w,E)=>{if(!this.argChoices.includes(w))throw new Fq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(w,E);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function jq($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}Mq.Argument=A5;Mq.humanReadableArgName=jq});var fO=_((Bq)=>{var{humanReadableArgName:zq}=zN();class N5{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let w=$.commands.filter((X)=>!X._hidden),E=$._getHelpCommand();if(E&&!E._hidden)w.push(E);if(this.sortSubcommands)w.sort((X,G)=>{return X.name().localeCompare(G.name())});return w}compareOptions($,w){let E=(X)=>{return X.short?X.short.replace(/^-/,""):X.long.replace(/^--/,"")};return E($).localeCompare(E(w))}visibleOptions($){let w=$.options.filter((X)=>!X.hidden),E=$._getHelpOption();if(E&&!E.hidden){let X=E.short&&$._findOption(E.short),G=E.long&&$._findOption(E.long);if(!X&&!G)w.push(E);else if(E.long&&!G)w.push($.createOption(E.long,E.description));else if(E.short&&!X)w.push($.createOption(E.short,E.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let E=$.parent;E;E=E.parent){let X=E.options.filter((G)=>!G.hidden);w.push(...X)}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((w)=>{w.description=w.description||$._argsDescription[w.name()]||""});if($.registeredArguments.find((w)=>w.description))return $.registeredArguments;return[]}subcommandTerm($){let w=$.registeredArguments.map((E)=>zq(E)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(X))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleOptionTerm(w.optionTerm(X))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleOptionTerm(w.optionTerm(X))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(X))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let E="";for(let X=$.parent;X;X=X.parent)E=X.name()+" "+E;return E+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((E)=>JSON.stringify(E)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)w.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)w.push(`env: ${$.envVar}`);if(w.length>0)return`${$.description} (${w.join(", ")})`;return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((E)=>JSON.stringify(E)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let E=`(${w.join(", ")})`;if($.description)return`${$.description} ${E}`;return E}return $.description}formatHelp($,w){let E=w.padWidth($,w),X=w.helpWidth??80;function G(J,Y){return w.formatItem(J,E,Y,w)}let A=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],N=w.commandDescription($);if(N.length>0)A=A.concat([w.boxWrap(w.styleCommandDescription(N),X),""]);let D=w.visibleArguments($).map((J)=>{return G(w.styleArgumentTerm(w.argumentTerm(J)),w.styleArgumentDescription(w.argumentDescription(J)))});if(D.length>0)A=A.concat([w.styleTitle("Arguments:"),...D,""]);let O=w.visibleOptions($).map((J)=>{return G(w.styleOptionTerm(w.optionTerm(J)),w.styleOptionDescription(w.optionDescription(J)))});if(O.length>0)A=A.concat([w.styleTitle("Options:"),...O,""]);if(w.showGlobalOptions){let J=w.visibleGlobalOptions($).map((Y)=>{return G(w.styleOptionTerm(w.optionTerm(Y)),w.styleOptionDescription(w.optionDescription(Y)))});if(J.length>0)A=A.concat([w.styleTitle("Global Options:"),...J,""])}let W=w.visibleCommands($).map((J)=>{return G(w.styleSubcommandTerm(w.subcommandTerm(J)),w.styleSubcommandDescription(w.subcommandDescription(J)))});if(W.length>0)A=A.concat([w.styleTitle("Commands:"),...W,""]);return A.join(`
5
+ `)}displayWidth($){return D5($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w==="[command]")return this.styleSubcommandText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleCommandText(w)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleSubcommandText(w)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,w){return Math.max(w.longestOptionTermLength($,w),w.longestGlobalOptionTermLength($,w),w.longestSubcommandTermLength($,w),w.longestArgumentTermLength($,w))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,w,E,X){let A=" ".repeat(2);if(!E)return A+$;let N=$.padEnd(w+$.length-X.displayWidth($)),D=2,W=(this.helpWidth??80)-w-D-2,J;if(W<this.minWidthToWrap||X.preformatted(E))J=E;else J=X.boxWrap(E,W).replace(/\n/g,`
6
+ `+" ".repeat(w+D));return A+N+" ".repeat(D)+J.replace(/\n/g,`
7
+ ${A}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let E=$.split(/\r\n|\n/),X=/[\s]*[^\s]+/g,G=[];return E.forEach((A)=>{let N=A.match(X);if(N===null){G.push("");return}let D=[N.shift()],O=this.displayWidth(D[0]);N.forEach((W)=>{let J=this.displayWidth(W);if(O+J<=w){D.push(W),O+=J;return}G.push(D.join(""));let Y=W.trimStart();D=[Y],O=this.displayWidth(Y)}),G.push(D.join(""))}),G.join(`
8
+ `)}}function D5($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}Bq.Help=N5;Bq.stripColor=D5});var vO=_((Pq)=>{var{InvalidArgumentError:Kq}=MG();class W5{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let E=Vq($);if(this.short=E.shortFlag,this.long=E.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let w=$;if(typeof $==="string")w={[$]:!0};return this.implied=Object.assign(this.implied||{},w),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(w,E)=>{if(!this.argChoices.includes(w))throw new Kq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(w,E);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return O5(this.name().replace(/^no-/,""));return O5(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class J5{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((w)=>{if(w.negate)this.negativeOptions.set(w.attributeName(),w);else this.positiveOptions.set(w.attributeName(),w)}),this.negativeOptions.forEach((w,E)=>{if(this.positiveOptions.has(E))this.dualOptions.add(E)})}valueFromOption($,w){let E=w.attributeName();if(!this.dualOptions.has(E))return!0;let X=this.negativeOptions.get(E).presetArg,G=X!==void 0?X:!1;return w.negate===(G===$)}}function O5($){return $.split("-").reduce((w,E)=>{return w+E[0].toUpperCase()+E.slice(1)})}function Vq($){let w,E,X=/^-[^-]$/,G=/^--[^-]/,A=$.split(/[ |,]+/).concat("guard");if(X.test(A[0]))w=A.shift();if(G.test(A[0]))E=A.shift();if(!w&&X.test(A[0]))w=A.shift();if(!w&&G.test(A[0]))w=E,E=A.shift();if(A[0].startsWith("-")){let N=A[0],D=`option creation failed due to '${N}' in option flags '${$}'`;if(/^-[^-][^-]/.test(N))throw Error(`${D}
9
9
  - a short flag is a single dash and a single character
10
10
  - either use a single dash and a single character (for a short flag)
11
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(X.test(A))throw Error(`${D}
12
- - too many short flags`);if(G.test(A))throw Error(`${D}
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(X.test(N))throw Error(`${D}
12
+ - too many short flags`);if(G.test(N))throw Error(`${D}
13
13
  - too many long flags`);throw Error(`${D}
14
- - unrecognised flag format`)}if(w===void 0&&E===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:E}}Rq.Option=EU;Rq.DualOptions=XU});var GU=Z((Iq)=>{function Bq($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let E=[];for(let X=0;X<=$.length;X++)E[X]=[X];for(let X=0;X<=w.length;X++)E[0][X]=X;for(let X=1;X<=w.length;X++)for(let G=1;G<=$.length;G++){let J=1;if($[G-1]===w[X-1])J=0;else J=1;if(E[G][X]=Math.min(E[G-1][X]+1,E[G][X-1]+1,E[G-1][X-1]+J),G>1&&X>1&&$[G-1]===w[X-2]&&$[G-2]===w[X-1])E[G][X]=Math.min(E[G][X],E[G-2][X-2]+1)}return E[$.length][w.length]}function Qq($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let E=$.startsWith("--");if(E)$=$.slice(2),w=w.map((A)=>A.slice(2));let X=[],G=3,J=0.4;if(w.forEach((A)=>{if(A.length<=1)return;let D=Bq($,A),N=Math.max($.length,A.length);if((N-D)/N>J){if(D<G)G=D,X=[A];else if(D===G)X.push(A)}}),X.sort((A,D)=>A.localeCompare(D)),E)X=X.map((A)=>`--${A}`);if(X.length>1)return`
14
+ - unrecognised flag format`)}if(w===void 0&&E===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:E}}Pq.Option=W5;Pq.DualOptions=J5});var U5=_((_q)=>{function kq($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let E=[];for(let X=0;X<=$.length;X++)E[X]=[X];for(let X=0;X<=w.length;X++)E[0][X]=X;for(let X=1;X<=w.length;X++)for(let G=1;G<=$.length;G++){let A=1;if($[G-1]===w[X-1])A=0;else A=1;if(E[G][X]=Math.min(E[G-1][X]+1,E[G][X-1]+1,E[G-1][X-1]+A),G>1&&X>1&&$[G-1]===w[X-2]&&$[G-2]===w[X-1])E[G][X]=Math.min(E[G][X],E[G-2][X-2]+1)}return E[$.length][w.length]}function bq($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let E=$.startsWith("--");if(E)$=$.slice(2),w=w.map((N)=>N.slice(2));let X=[],G=3,A=0.4;if(w.forEach((N)=>{if(N.length<=1)return;let D=kq($,N),O=Math.max($.length,N.length);if((O-D)/O>A){if(D<G)G=D,X=[N];else if(D===G)X.push(N)}}),X.sort((N,D)=>N.localeCompare(D)),E)X=X.map((N)=>`--${N}`);if(X.length>1)return`
15
15
  (Did you mean one of ${X.join(", ")}?)`;if(X.length===1)return`
16
- (Did you mean ${X[0]}?)`;return""}Iq.suggestSimilar=Qq});var NU=Z((Zq)=>{var Vq=V$("events").EventEmitter,_D=V$("child_process"),Hw=V$("path"),MJ=V$("fs"),Q0=V$("process"),{Argument:Pq,humanReadableArgName:qq}=jJ(),{CommanderError:vD}=HG(),{Help:Sq,stripColor:kq}=ZD(),{Option:JU,DualOptions:bq}=CD(),{suggestSimilar:AU}=GU();class xD extends Vq{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(w)=>Q0.stdout.write(w),writeErr:(w)=>Q0.stderr.write(w),outputError:(w,E)=>E(w),getOutHelpWidth:()=>Q0.stdout.isTTY?Q0.stdout.columns:void 0,getErrHelpWidth:()=>Q0.stderr.isTTY?Q0.stderr.columns:void 0,getOutHasColors:()=>fD()??(Q0.stdout.isTTY&&Q0.stdout.hasColors?.()),getErrHasColors:()=>fD()??(Q0.stderr.isTTY&&Q0.stderr.hasColors?.()),stripColor:(w)=>kq(w)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let w=this;w;w=w.parent)$.push(w);return $}command($,w,E){let X=w,G=E;if(typeof X==="object"&&X!==null)G=X,X=null;G=G||{};let[,J,A]=$.match(/([^ ]+) *(.*)/),D=this.createCommand(J);if(X)D.description(X),D._executableHandler=!0;if(G.isDefault)this._defaultCommandName=D._name;if(D._hidden=!!(G.noHelp||G.hidden),D._executableFile=G.executableFile||null,A)D.arguments(A);if(this._registerCommand(D),D.parent=this,D.copyInheritedSettings(this),X)return this;return D}createCommand($){return new xD($)}createHelp(){return Object.assign(new Sq,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,w){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
17
- - specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new Pq($,w)}argument($,w,E,X){let G=this.createArgument($,w);if(typeof E==="function")G.default(X).argParser(E);else G.default(E);return this.addArgument(G),this}arguments($){return $.trim().split(/ +/).forEach((w)=>{this.argument(w)}),this}addArgument($){let w=this.registeredArguments.slice(-1)[0];if(w&&w.variadic)throw Error(`only the last argument can be variadic '${w.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,w){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,E,X]=$.match(/([^ ]+) *(.*)/),G=w??"display help for command",J=this.createCommand(E);if(J.helpOption(!1),X)J.arguments(X);if(G)J.description(G);return this._addImplicitHelpCommand=!0,this._helpCommand=J,this}addHelpCommand($,w){if(typeof $!=="object")return this.helpCommand($,w),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,w){let E=["preSubcommand","preAction","postAction"];if(!E.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
18
- Expecting one of '${E.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,E){if(this._exitCallback)this._exitCallback(new vD($,w,E));Q0.exit($)}action($){let w=(E)=>{let X=this.registeredArguments.length,G=E.slice(0,X);if(this._storeOptionsAsProperties)G[X]=this;else G[X]=this.opts();return G.push(this),$.apply(this,G)};return this._actionHandler=w,this}createOption($,w){return new JU($,w)}_callParseArg($,w,E,X){try{return $.parseArg(w,E)}catch(G){if(G.code==="commander.invalidArgument"){let J=`${X} ${G.message}`;this.error(J,{exitCode:G.exitCode,code:G.code})}throw G}}_registerOption($){let w=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(w){let E=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${E}'
19
- - already used by option '${w.flags}'`)}this.options.push($)}_registerCommand($){let w=(X)=>{return[X.name()].concat(X.aliases())},E=w($).find((X)=>this._findCommand(X));if(E){let X=w(this._findCommand(E)).join("|"),G=w($).join("|");throw Error(`cannot add command '${G}' as already have command '${X}'`)}this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),E=$.attributeName();if($.negate){let G=$.long.replace(/^--no-/,"--");if(!this._findOption(G))this.setOptionValueWithSource(E,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(E,$.defaultValue,"default");let X=(G,J,A)=>{if(G==null&&$.presetArg!==void 0)G=$.presetArg;let D=this.getOptionValue(E);if(G!==null&&$.parseArg)G=this._callParseArg($,G,D,J);else if(G!==null&&$.variadic)G=$._concatValue(G,D);if(G==null)if($.negate)G=!1;else if($.isBoolean()||$.optional)G=!0;else G="";this.setOptionValueWithSource(E,G,A)};if(this.on("option:"+w,(G)=>{let J=`error: option '${$.flags}' argument '${G}' is invalid.`;X(G,J,"cli")}),$.envVar)this.on("optionEnv:"+w,(G)=>{let J=`error: option '${$.flags}' value '${G}' from env '${$.envVar}' is invalid.`;X(G,J,"env")});return this}_optionEx($,w,E,X,G){if(typeof w==="object"&&w instanceof JU)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let J=this.createOption(w,E);if(J.makeOptionMandatory(!!$.mandatory),typeof X==="function")J.default(G).argParser(X);else if(X instanceof RegExp){let A=X;X=(D,N)=>{let W=A.exec(D);return W?W[0]:N},J.default(G).argParser(X)}else J.default(X);return this.addOption(J)}option($,w,E,X){return this._optionEx({},$,w,E,X)}requiredOption($,w,E,X){return this._optionEx({mandatory:!0},$,w,E,X)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,w){return this.setOptionValueWithSource($,w,void 0)}setOptionValueWithSource($,w,E){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=E,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((E)=>{if(E.getOptionValueSource($)!==void 0)w=E.getOptionValueSource($)}),w}_prepareUserArgs($,w){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(w=w||{},$===void 0&&w.from===void 0){if(Q0.versions?.electron)w.from="electron";let X=Q0.execArgv??[];if(X.includes("-e")||X.includes("--eval")||X.includes("-p")||X.includes("--print"))w.from="eval"}if($===void 0)$=Q0.argv;this.rawArgs=$.slice();let E;switch(w.from){case void 0:case"node":this._scriptPath=$[1],E=$.slice(2);break;case"electron":if(Q0.defaultApp)this._scriptPath=$[1],E=$.slice(2);else E=$.slice(1);break;case"user":E=$.slice(0);break;case"eval":E=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${w.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",E}parse($,w){this._prepareForParse();let E=this._prepareUserArgs($,w);return this._parseCommand([],E),this}async parseAsync($,w){this._prepareForParse();let E=this._prepareUserArgs($,w);return await this._parseCommand([],E),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
20
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,E){if(MJ.existsSync($))return;let X=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",G=`'${$}' does not exist
16
+ (Did you mean ${X[0]}?)`;return""}_q.suggestSimilar=bq});var F5=_((uq)=>{var Cq=b$("events").EventEmitter,xO=b$("child_process"),YE=b$("path"),BN=b$("fs"),K0=b$("process"),{Argument:fq,humanReadableArgName:vq}=zN(),{CommanderError:yO}=MG(),{Help:xq,stripColor:yq}=fO(),{Option:Y5,DualOptions:gq}=vO(),{suggestSimilar:H5}=U5();class uO extends Cq{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(w)=>K0.stdout.write(w),writeErr:(w)=>K0.stderr.write(w),outputError:(w,E)=>E(w),getOutHelpWidth:()=>K0.stdout.isTTY?K0.stdout.columns:void 0,getErrHelpWidth:()=>K0.stderr.isTTY?K0.stderr.columns:void 0,getOutHasColors:()=>gO()??(K0.stdout.isTTY&&K0.stdout.hasColors?.()),getErrHasColors:()=>gO()??(K0.stderr.isTTY&&K0.stderr.hasColors?.()),stripColor:(w)=>yq(w)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let w=this;w;w=w.parent)$.push(w);return $}command($,w,E){let X=w,G=E;if(typeof X==="object"&&X!==null)G=X,X=null;G=G||{};let[,A,N]=$.match(/([^ ]+) *(.*)/),D=this.createCommand(A);if(X)D.description(X),D._executableHandler=!0;if(G.isDefault)this._defaultCommandName=D._name;if(D._hidden=!!(G.noHelp||G.hidden),D._executableFile=G.executableFile||null,N)D.arguments(N);if(this._registerCommand(D),D.parent=this,D.copyInheritedSettings(this),X)return this;return D}createCommand($){return new uO($)}createHelp(){return Object.assign(new xq,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,w){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
17
+ - specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new fq($,w)}argument($,w,E,X){let G=this.createArgument($,w);if(typeof E==="function")G.default(X).argParser(E);else G.default(E);return this.addArgument(G),this}arguments($){return $.trim().split(/ +/).forEach((w)=>{this.argument(w)}),this}addArgument($){let w=this.registeredArguments.slice(-1)[0];if(w&&w.variadic)throw Error(`only the last argument can be variadic '${w.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,w){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,E,X]=$.match(/([^ ]+) *(.*)/),G=w??"display help for command",A=this.createCommand(E);if(A.helpOption(!1),X)A.arguments(X);if(G)A.description(G);return this._addImplicitHelpCommand=!0,this._helpCommand=A,this}addHelpCommand($,w){if(typeof $!=="object")return this.helpCommand($,w),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,w){let E=["preSubcommand","preAction","postAction"];if(!E.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
18
+ Expecting one of '${E.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,E){if(this._exitCallback)this._exitCallback(new yO($,w,E));K0.exit($)}action($){let w=(E)=>{let X=this.registeredArguments.length,G=E.slice(0,X);if(this._storeOptionsAsProperties)G[X]=this;else G[X]=this.opts();return G.push(this),$.apply(this,G)};return this._actionHandler=w,this}createOption($,w){return new Y5($,w)}_callParseArg($,w,E,X){try{return $.parseArg(w,E)}catch(G){if(G.code==="commander.invalidArgument"){let A=`${X} ${G.message}`;this.error(A,{exitCode:G.exitCode,code:G.code})}throw G}}_registerOption($){let w=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(w){let E=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${E}'
19
+ - already used by option '${w.flags}'`)}this.options.push($)}_registerCommand($){let w=(X)=>{return[X.name()].concat(X.aliases())},E=w($).find((X)=>this._findCommand(X));if(E){let X=w(this._findCommand(E)).join("|"),G=w($).join("|");throw Error(`cannot add command '${G}' as already have command '${X}'`)}this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),E=$.attributeName();if($.negate){let G=$.long.replace(/^--no-/,"--");if(!this._findOption(G))this.setOptionValueWithSource(E,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(E,$.defaultValue,"default");let X=(G,A,N)=>{if(G==null&&$.presetArg!==void 0)G=$.presetArg;let D=this.getOptionValue(E);if(G!==null&&$.parseArg)G=this._callParseArg($,G,D,A);else if(G!==null&&$.variadic)G=$._concatValue(G,D);if(G==null)if($.negate)G=!1;else if($.isBoolean()||$.optional)G=!0;else G="";this.setOptionValueWithSource(E,G,N)};if(this.on("option:"+w,(G)=>{let A=`error: option '${$.flags}' argument '${G}' is invalid.`;X(G,A,"cli")}),$.envVar)this.on("optionEnv:"+w,(G)=>{let A=`error: option '${$.flags}' value '${G}' from env '${$.envVar}' is invalid.`;X(G,A,"env")});return this}_optionEx($,w,E,X,G){if(typeof w==="object"&&w instanceof Y5)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let A=this.createOption(w,E);if(A.makeOptionMandatory(!!$.mandatory),typeof X==="function")A.default(G).argParser(X);else if(X instanceof RegExp){let N=X;X=(D,O)=>{let W=N.exec(D);return W?W[0]:O},A.default(G).argParser(X)}else A.default(X);return this.addOption(A)}option($,w,E,X){return this._optionEx({},$,w,E,X)}requiredOption($,w,E,X){return this._optionEx({mandatory:!0},$,w,E,X)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,w){return this.setOptionValueWithSource($,w,void 0)}setOptionValueWithSource($,w,E){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=E,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((E)=>{if(E.getOptionValueSource($)!==void 0)w=E.getOptionValueSource($)}),w}_prepareUserArgs($,w){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(w=w||{},$===void 0&&w.from===void 0){if(K0.versions?.electron)w.from="electron";let X=K0.execArgv??[];if(X.includes("-e")||X.includes("--eval")||X.includes("-p")||X.includes("--print"))w.from="eval"}if($===void 0)$=K0.argv;this.rawArgs=$.slice();let E;switch(w.from){case void 0:case"node":this._scriptPath=$[1],E=$.slice(2);break;case"electron":if(K0.defaultApp)this._scriptPath=$[1],E=$.slice(2);else E=$.slice(1);break;case"user":E=$.slice(0);break;case"eval":E=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${w.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",E}parse($,w){this._prepareForParse();let E=this._prepareUserArgs($,w);return this._parseCommand([],E),this}async parseAsync($,w){this._prepareForParse();let E=this._prepareUserArgs($,w);return await this._parseCommand([],E),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
20
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,E){if(BN.existsSync($))return;let X=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",G=`'${$}' does not exist
21
21
  - if '${E}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
22
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
- - ${X}`;throw Error(G)}_executeSubCommand($,w){w=w.slice();let E=!1,X=[".js",".ts",".tsx",".mjs",".cjs"];function G(W,O){let Y=Hw.resolve(W,O);if(MJ.existsSync(Y))return Y;if(X.includes(Hw.extname(O)))return;let H=X.find((L)=>MJ.existsSync(`${Y}${L}`));if(H)return`${Y}${H}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=$._executableFile||`${this._name}-${$._name}`,A=this._executableDir||"";if(this._scriptPath){let W;try{W=MJ.realpathSync(this._scriptPath)}catch{W=this._scriptPath}A=Hw.resolve(Hw.dirname(W),A)}if(A){let W=G(A,J);if(!W&&!$._executableFile&&this._scriptPath){let O=Hw.basename(this._scriptPath,Hw.extname(this._scriptPath));if(O!==this._name)W=G(A,`${O}-${$._name}`)}J=W||J}E=X.includes(Hw.extname(J));let D;if(Q0.platform!=="win32")if(E)w.unshift(J),w=DU(Q0.execArgv).concat(w),D=_D.spawn(Q0.argv[0],w,{stdio:"inherit"});else D=_D.spawn(J,w,{stdio:"inherit"});else this._checkForMissingExecutable(J,A,$._name),w.unshift(J),w=DU(Q0.execArgv).concat(w),D=_D.spawn(Q0.execPath,w,{stdio:"inherit"});if(!D.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((O)=>{Q0.on(O,()=>{if(D.killed===!1&&D.exitCode===null)D.kill(O)})});let N=this._exitCallback;D.on("close",(W)=>{if(W=W??1,!N)Q0.exit(W);else N(new vD(W,"commander.executeSubCommandAsync","(close)"))}),D.on("error",(W)=>{if(W.code==="ENOENT")this._checkForMissingExecutable(J,A,$._name);else if(W.code==="EACCES")throw Error(`'${J}' not executable`);if(!N)Q0.exit(1);else{let O=new vD(1,"commander.executeSubCommandAsync","(error)");O.nestedError=W,N(O)}}),this.runningCommand=D}_dispatchSubcommand($,w,E){let X=this._findCommand($);if(!X)this.help({error:!0});X._prepareForParse();let G;return G=this._chainOrCallSubCommandHook(G,X,"preSubcommand"),G=this._chainOrCall(G,()=>{if(X._executableHandler)this._executeSubCommand(X,w.concat(E));else return X._parseCommand(w,E)}),G}_dispatchHelpCommand($){if(!$)this.help();let w=this._findCommand($);if(w&&!w._executableHandler)w.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,w)=>{if($.required&&this.args[w]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(E,X,G)=>{let J=X;if(X!==null&&E.parseArg){let A=`error: command-argument value '${X}' is invalid for argument '${E.name()}'.`;J=this._callParseArg(E,X,G,A)}return J};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((E,X)=>{let G=E.defaultValue;if(E.variadic){if(X<this.args.length){if(G=this.args.slice(X),E.parseArg)G=G.reduce((J,A)=>{return $(E,A,J)},E.defaultValue)}else if(G===void 0)G=[]}else if(X<this.args.length){if(G=this.args[X],E.parseArg)G=$(E,G,E.defaultValue)}w[X]=G}),this.processedArgs=w}_chainOrCall($,w){if($&&$.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let E=$,X=[];if(this._getCommandAndAncestors().reverse().filter((G)=>G._lifeCycleHooks[w]!==void 0).forEach((G)=>{G._lifeCycleHooks[w].forEach((J)=>{X.push({hookedCommand:G,callback:J})})}),w==="postAction")X.reverse();return X.forEach((G)=>{E=this._chainOrCall(E,()=>{return G.callback(G.hookedCommand,this)})}),E}_chainOrCallSubCommandHook($,w,E){let X=$;if(this._lifeCycleHooks[E]!==void 0)this._lifeCycleHooks[E].forEach((G)=>{X=this._chainOrCall(X,()=>{return G(this,w)})});return X}_parseCommand($,w){let E=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(E.operands),w=E.unknown,this.args=$.concat(w),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),w);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(w),this._dispatchSubcommand(this._defaultCommandName,$,w);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(E.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=()=>{if(E.unknown.length>0)this.unknownOption(E.unknown[0])},G=`command:${this.name()}`;if(this._actionHandler){X(),this._processArguments();let J;if(J=this._chainOrCallHooks(J,"preAction"),J=this._chainOrCall(J,()=>this._actionHandler(this.processedArgs)),this.parent)J=this._chainOrCall(J,()=>{this.parent.emit(G,$,w)});return J=this._chainOrCallHooks(J,"postAction"),J}if(this.parent&&this.parent.listenerCount(G))X(),this._processArguments(),this.parent.emit(G,$,w);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,w);if(this.listenerCount("command:*"))this.emit("command:*",$,w);else if(this.commands.length)this.unknownCommand();else X(),this._processArguments()}else if(this.commands.length)X(),this.help({error:!0});else X(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((w)=>w._name===$||w._aliases.includes($))}_findOption($){return this.options.find((w)=>w.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((w)=>{if(w.mandatory&&$.getOptionValue(w.attributeName())===void 0)$.missingMandatoryOptionValue(w)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((E)=>{let X=E.attributeName();if(this.getOptionValue(X)===void 0)return!1;return this.getOptionValueSource(X)!=="default"});$.filter((E)=>E.conflictsWith.length>0).forEach((E)=>{let X=$.find((G)=>E.conflictsWith.includes(G.attributeName()));if(X)this._conflictingOption(E,X)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],E=[],X=w,G=$.slice();function J(D){return D.length>1&&D[0]==="-"}let A=null;while(G.length){let D=G.shift();if(D==="--"){if(X===E)X.push(D);X.push(...G);break}if(A&&!J(D)){this.emit(`option:${A.name()}`,D);continue}if(A=null,J(D)){let N=this._findOption(D);if(N){if(N.required){let W=G.shift();if(W===void 0)this.optionMissingArgument(N);this.emit(`option:${N.name()}`,W)}else if(N.optional){let W=null;if(G.length>0&&!J(G[0]))W=G.shift();this.emit(`option:${N.name()}`,W)}else this.emit(`option:${N.name()}`);A=N.variadic?N:null;continue}}if(D.length>2&&D[0]==="-"&&D[1]!=="-"){let N=this._findOption(`-${D[1]}`);if(N){if(N.required||N.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${N.name()}`,D.slice(2));else this.emit(`option:${N.name()}`),G.unshift(`-${D.slice(2)}`);continue}}if(/^--[^=]+=/.test(D)){let N=D.indexOf("="),W=this._findOption(D.slice(0,N));if(W&&(W.required||W.optional)){this.emit(`option:${W.name()}`,D.slice(N+1));continue}}if(J(D))X=E;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&E.length===0){if(this._findCommand(D)){if(w.push(D),G.length>0)E.push(...G);break}else if(this._getHelpCommand()&&D===this._getHelpCommand().name()){if(w.push(D),G.length>0)w.push(...G);break}else if(this._defaultCommandName){if(E.push(D),G.length>0)E.push(...G);break}}if(this._passThroughOptions){if(X.push(D),G.length>0)X.push(...G);break}X.push(D)}return{operands:w,unknown:E}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let E=0;E<w;E++){let X=this.options[E].attributeName();$[X]=X===this._versionOptionName?this._version:this[X]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,w)=>Object.assign($,w.opts()),{})}error($,w){if(this._outputConfiguration.outputError(`${$}
23
+ - ${X}`;throw Error(G)}_executeSubCommand($,w){w=w.slice();let E=!1,X=[".js",".ts",".tsx",".mjs",".cjs"];function G(W,J){let Y=YE.resolve(W,J);if(BN.existsSync(Y))return Y;if(X.includes(YE.extname(J)))return;let H=X.find((L)=>BN.existsSync(`${Y}${L}`));if(H)return`${Y}${H}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let A=$._executableFile||`${this._name}-${$._name}`,N=this._executableDir||"";if(this._scriptPath){let W;try{W=BN.realpathSync(this._scriptPath)}catch{W=this._scriptPath}N=YE.resolve(YE.dirname(W),N)}if(N){let W=G(N,A);if(!W&&!$._executableFile&&this._scriptPath){let J=YE.basename(this._scriptPath,YE.extname(this._scriptPath));if(J!==this._name)W=G(N,`${J}-${$._name}`)}A=W||A}E=X.includes(YE.extname(A));let D;if(K0.platform!=="win32")if(E)w.unshift(A),w=L5(K0.execArgv).concat(w),D=xO.spawn(K0.argv[0],w,{stdio:"inherit"});else D=xO.spawn(A,w,{stdio:"inherit"});else this._checkForMissingExecutable(A,N,$._name),w.unshift(A),w=L5(K0.execArgv).concat(w),D=xO.spawn(K0.execPath,w,{stdio:"inherit"});if(!D.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((J)=>{K0.on(J,()=>{if(D.killed===!1&&D.exitCode===null)D.kill(J)})});let O=this._exitCallback;D.on("close",(W)=>{if(W=W??1,!O)K0.exit(W);else O(new yO(W,"commander.executeSubCommandAsync","(close)"))}),D.on("error",(W)=>{if(W.code==="ENOENT")this._checkForMissingExecutable(A,N,$._name);else if(W.code==="EACCES")throw Error(`'${A}' not executable`);if(!O)K0.exit(1);else{let J=new yO(1,"commander.executeSubCommandAsync","(error)");J.nestedError=W,O(J)}}),this.runningCommand=D}_dispatchSubcommand($,w,E){let X=this._findCommand($);if(!X)this.help({error:!0});X._prepareForParse();let G;return G=this._chainOrCallSubCommandHook(G,X,"preSubcommand"),G=this._chainOrCall(G,()=>{if(X._executableHandler)this._executeSubCommand(X,w.concat(E));else return X._parseCommand(w,E)}),G}_dispatchHelpCommand($){if(!$)this.help();let w=this._findCommand($);if(w&&!w._executableHandler)w.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,w)=>{if($.required&&this.args[w]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(E,X,G)=>{let A=X;if(X!==null&&E.parseArg){let N=`error: command-argument value '${X}' is invalid for argument '${E.name()}'.`;A=this._callParseArg(E,X,G,N)}return A};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((E,X)=>{let G=E.defaultValue;if(E.variadic){if(X<this.args.length){if(G=this.args.slice(X),E.parseArg)G=G.reduce((A,N)=>{return $(E,N,A)},E.defaultValue)}else if(G===void 0)G=[]}else if(X<this.args.length){if(G=this.args[X],E.parseArg)G=$(E,G,E.defaultValue)}w[X]=G}),this.processedArgs=w}_chainOrCall($,w){if($&&$.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let E=$,X=[];if(this._getCommandAndAncestors().reverse().filter((G)=>G._lifeCycleHooks[w]!==void 0).forEach((G)=>{G._lifeCycleHooks[w].forEach((A)=>{X.push({hookedCommand:G,callback:A})})}),w==="postAction")X.reverse();return X.forEach((G)=>{E=this._chainOrCall(E,()=>{return G.callback(G.hookedCommand,this)})}),E}_chainOrCallSubCommandHook($,w,E){let X=$;if(this._lifeCycleHooks[E]!==void 0)this._lifeCycleHooks[E].forEach((G)=>{X=this._chainOrCall(X,()=>{return G(this,w)})});return X}_parseCommand($,w){let E=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(E.operands),w=E.unknown,this.args=$.concat(w),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),w);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(w),this._dispatchSubcommand(this._defaultCommandName,$,w);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(E.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=()=>{if(E.unknown.length>0)this.unknownOption(E.unknown[0])},G=`command:${this.name()}`;if(this._actionHandler){X(),this._processArguments();let A;if(A=this._chainOrCallHooks(A,"preAction"),A=this._chainOrCall(A,()=>this._actionHandler(this.processedArgs)),this.parent)A=this._chainOrCall(A,()=>{this.parent.emit(G,$,w)});return A=this._chainOrCallHooks(A,"postAction"),A}if(this.parent&&this.parent.listenerCount(G))X(),this._processArguments(),this.parent.emit(G,$,w);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,w);if(this.listenerCount("command:*"))this.emit("command:*",$,w);else if(this.commands.length)this.unknownCommand();else X(),this._processArguments()}else if(this.commands.length)X(),this.help({error:!0});else X(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((w)=>w._name===$||w._aliases.includes($))}_findOption($){return this.options.find((w)=>w.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((w)=>{if(w.mandatory&&$.getOptionValue(w.attributeName())===void 0)$.missingMandatoryOptionValue(w)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((E)=>{let X=E.attributeName();if(this.getOptionValue(X)===void 0)return!1;return this.getOptionValueSource(X)!=="default"});$.filter((E)=>E.conflictsWith.length>0).forEach((E)=>{let X=$.find((G)=>E.conflictsWith.includes(G.attributeName()));if(X)this._conflictingOption(E,X)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],E=[],X=w,G=$.slice();function A(D){return D.length>1&&D[0]==="-"}let N=null;while(G.length){let D=G.shift();if(D==="--"){if(X===E)X.push(D);X.push(...G);break}if(N&&!A(D)){this.emit(`option:${N.name()}`,D);continue}if(N=null,A(D)){let O=this._findOption(D);if(O){if(O.required){let W=G.shift();if(W===void 0)this.optionMissingArgument(O);this.emit(`option:${O.name()}`,W)}else if(O.optional){let W=null;if(G.length>0&&!A(G[0]))W=G.shift();this.emit(`option:${O.name()}`,W)}else this.emit(`option:${O.name()}`);N=O.variadic?O:null;continue}}if(D.length>2&&D[0]==="-"&&D[1]!=="-"){let O=this._findOption(`-${D[1]}`);if(O){if(O.required||O.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${O.name()}`,D.slice(2));else this.emit(`option:${O.name()}`),G.unshift(`-${D.slice(2)}`);continue}}if(/^--[^=]+=/.test(D)){let O=D.indexOf("="),W=this._findOption(D.slice(0,O));if(W&&(W.required||W.optional)){this.emit(`option:${W.name()}`,D.slice(O+1));continue}}if(A(D))X=E;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&E.length===0){if(this._findCommand(D)){if(w.push(D),G.length>0)E.push(...G);break}else if(this._getHelpCommand()&&D===this._getHelpCommand().name()){if(w.push(D),G.length>0)w.push(...G);break}else if(this._defaultCommandName){if(E.push(D),G.length>0)E.push(...G);break}}if(this._passThroughOptions){if(X.push(D),G.length>0)X.push(...G);break}X.push(D)}return{operands:w,unknown:E}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let E=0;E<w;E++){let X=this.options[E].attributeName();$[X]=X===this._versionOptionName?this._version:this[X]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,w)=>Object.assign($,w.opts()),{})}error($,w){if(this._outputConfiguration.outputError(`${$}
24
24
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
25
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
26
- `),this.outputHelp({error:!0});let E=w||{},X=E.exitCode||1,G=E.code||"commander.error";this._exit(X,G,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in Q0.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,Q0.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new bq(this.options),w=(E)=>{return this.getOptionValue(E)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(E))};this.options.filter((E)=>E.implied!==void 0&&w(E.attributeName())&&$.valueFromOption(this.getOptionValue(E.attributeName()),E)).forEach((E)=>{Object.keys(E.implied).filter((X)=>!w(X)).forEach((X)=>{this.setOptionValueWithSource(X,E.implied[X],"implied")})})}missingArgument($){let w=`error: missing required argument '${$}'`;this.error(w,{code:"commander.missingArgument"})}optionMissingArgument($){let w=`error: option '${$.flags}' argument missing`;this.error(w,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let w=`error: required option '${$.flags}' not specified`;this.error(w,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,w){let E=(J)=>{let A=J.attributeName(),D=this.getOptionValue(A),N=this.options.find((O)=>O.negate&&A===O.attributeName()),W=this.options.find((O)=>!O.negate&&A===O.attributeName());if(N&&(N.presetArg===void 0&&D===!1||N.presetArg!==void 0&&D===N.presetArg))return N;return W||J},X=(J)=>{let A=E(J),D=A.attributeName();if(this.getOptionValueSource(D)==="env")return`environment variable '${A.envVar}'`;return`option '${A.flags}'`},G=`error: ${X($)} cannot be used with ${X(w)}`;this.error(G,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let w="";if($.startsWith("--")&&this._showSuggestionAfterError){let X=[],G=this;do{let J=G.createHelp().visibleOptions(G).filter((A)=>A.long).map((A)=>A.long);X=X.concat(J),G=G.parent}while(G&&!G._enablePositionalOptions);w=AU($,X)}let E=`error: unknown option '${$}'${w}`;this.error(E,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,E=w===1?"":"s",G=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${E} but got ${$.length}.`;this.error(G,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],w="";if(this._showSuggestionAfterError){let X=[];this.createHelp().visibleCommands(this).forEach((G)=>{if(X.push(G.name()),G.alias())X.push(G.alias())}),w=AU($,X)}let E=`error: unknown command '${$}'${w}`;this.error(E,{code:"commander.unknownCommand"})}version($,w,E){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",E=E||"output the version number";let X=this.createOption(w,E);return this._versionOptionName=X.attributeName(),this._registerOption(X),this.on("option:"+X.name(),()=>{this._outputConfiguration.writeOut(`${$}
27
- `),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let E=this.parent?._findCommand($);if(E){let X=[E.name()].concat(E.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${X}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((E)=>{return qq(E)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?w:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=Hw.basename($,Hw.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),E=this._getOutputContext($);w.prepareContext({error:E.error,helpWidth:E.helpWidth,outputHasColors:E.hasColors});let X=w.formatHelp(this,w);if(E.hasColors)return X;return this._outputConfiguration.stripColor(X)}_getOutputContext($){$=$||{};let w=!!$.error,E,X,G;if(w)E=(A)=>this._outputConfiguration.writeErr(A),X=this._outputConfiguration.getErrHasColors(),G=this._outputConfiguration.getErrHelpWidth();else E=(A)=>this._outputConfiguration.writeOut(A),X=this._outputConfiguration.getOutHasColors(),G=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(A)=>{if(!X)A=this._outputConfiguration.stripColor(A);return E(A)},hasColors:X,helpWidth:G}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let E=this._getOutputContext($),X={error:E.error,write:E.write,command:this};this._getCommandAndAncestors().reverse().forEach((J)=>J.emit("beforeAllHelp",X)),this.emit("beforeHelp",X);let G=this.helpInformation({error:E.error});if(w){if(G=w(G),typeof G!=="string"&&!Buffer.isBuffer(G))throw Error("outputHelp callback must return a string or a Buffer")}if(E.write(G),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",X),this._getCommandAndAncestors().forEach((J)=>J.emit("afterAllHelp",X))}helpOption($,w){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",w=w??"display help for command",this._helpOption=this.createOption($,w),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let w=Number(Q0.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let E=["beforeAll","before","after","afterAll"];if(!E.includes($))throw Error(`Unexpected value for position to addHelpText.
28
- Expecting one of '${E.join("', '")}'`);let X=`${$}Help`;return this.on(X,(G)=>{let J;if(typeof w==="function")J=w({error:G.error,command:G.command});else J=w;if(J)G.write(`${J}
29
- `)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((X)=>w.is(X)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function DU($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let E,X="127.0.0.1",G="9229",J;if((J=w.match(/^(--inspect(-brk)?)$/))!==null)E=J[1];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(E=J[1],/^\d+$/.test(J[3]))G=J[3];else X=J[3];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)E=J[1],X=J[3],G=J[4];if(E&&G!=="0")return`${E}=${X}:${parseInt(G)+1}`;return w})}function fD(){if(Q0.env.NO_COLOR||Q0.env.FORCE_COLOR==="0"||Q0.env.FORCE_COLOR==="false")return!1;if(Q0.env.FORCE_COLOR||Q0.env.CLICOLOR_FORCE!==void 0)return!0;return}Zq.Command=xD;Zq.useColor=fD});var YU=Z((xq)=>{var{Argument:WU}=jJ(),{Command:yD}=NU(),{CommanderError:vq,InvalidArgumentError:OU}=HG(),{Help:fq}=ZD(),{Option:UU}=CD();xq.program=new yD;xq.createCommand=($)=>new yD($);xq.createOption=($,w)=>new UU($,w);xq.createArgument=($,w)=>new WU($,w);xq.Command=yD;xq.Option=UU;xq.Argument=WU;xq.Help=fq;xq.CommanderError=vq;xq.InvalidArgumentError=OU;xq.InvalidOptionArgumentError=OU});function RJ($,w,E,X){if(LU[$]<LU[dq])return;let G=new Date().toISOString(),A=`${iq[$]}[${$.toUpperCase()}]\x1B[0m ${G} [${w}]`;if(X!==void 0)console.error(`${A} ${E}`,X);else console.error(`${A} ${E}`)}function Z0($){return{debug:(w,E)=>RJ("debug",$,w,E),info:(w,E)=>RJ("info",$,w,E),warn:(w,E)=>RJ("warn",$,w,E),error:(w,E)=>RJ("error",$,w,E)}}var LU,iq,dq;var p$=R(()=>{LU={debug:0,info:1,warn:2,error:3},iq={debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},dq=process.env.ORC_LOG_LEVEL??"info"});import{randomBytes as lq}from"crypto";function eq($,w){let E="";for(let X=w-1;X>=0;X--){let G=$%gD;E=uD[G]+E,$=Math.floor($/gD)}return E}function $2($){let w=lq($),E="";for(let X=0;X<$;X++)E+=uD[(w[X]??0)%gD];return E}function i(){return eq(Date.now(),sq)+$2(aq)}var uD="0123456789ABCDEFGHJKMNPQRSTVWXYZ",gD,sq=10,aq=16;var X1=R(()=>{gD=uD.length});function b($,w){if(!$||typeof $!=="object")return!1;if($ instanceof w)return!0;if(!Object.prototype.hasOwnProperty.call(w,K))throw Error(`Class "${w.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let E=Object.getPrototypeOf($).constructor;if(E)while(E){if(K in E&&E[K]===w[K])return!0;E=Object.getPrototypeOf(E)}return!1}var K;var E0=R(()=>{K=Symbol.for("drizzle:entityKind")});var FU,hD,cD;var zJ=R(()=>{E0();FU=class FU{static[K]="ConsoleLogWriter";write($){console.log($)}};hD=class hD{static[K]="DefaultLogger";writer;constructor($){this.writer=$?.writer??new FU}logQuery($,w){let E=w.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),X=E.length?` -- params: [${E.join(", ")}]`:"";this.writer.write(`Query: ${$}${X}`)}};cD=class cD{static[K]="NoopLogger";logQuery(){}}});var G1;var LG=R(()=>{G1=Symbol.for("drizzle:Name")});function xw($){return $[G1]}function UE($){return`${$[TJ]??"public"}.${$[G1]}`}var TJ,BJ,jU,nD,mD,FG,MU,w2,y;var _$=R(()=>{E0();LG();TJ=Symbol.for("drizzle:Schema"),BJ=Symbol.for("drizzle:Columns"),jU=Symbol.for("drizzle:ExtraConfigColumns"),nD=Symbol.for("drizzle:OriginalName"),mD=Symbol.for("drizzle:BaseName"),FG=Symbol.for("drizzle:IsAlias"),MU=Symbol.for("drizzle:ExtraConfigBuilder"),w2=Symbol.for("drizzle:IsDrizzleTable");y=class y{static[K]="Table";static Symbol={Name:G1,Schema:TJ,OriginalName:nD,Columns:BJ,ExtraConfigColumns:jU,BaseName:mD,IsAlias:FG,ExtraConfigBuilder:MU};[G1];[nD];[TJ];[BJ];[jU];[mD];[FG]=!1;[w2]=!0;[MU]=void 0;constructor($,w,E){this[G1]=this[nD]=$,this[TJ]=w,this[mD]=E}}});var V0;var b1=R(()=>{E0();V0=class V0{constructor($,w){this.table=$,this.config=w,this.name=w.name,this.keyAsName=w.keyAsName,this.notNull=w.notNull,this.default=w.default,this.defaultFn=w.defaultFn,this.onUpdateFn=w.onUpdateFn,this.hasDefault=w.hasDefault,this.primary=w.primaryKey,this.isUnique=w.isUnique,this.uniqueName=w.uniqueName,this.uniqueType=w.uniqueType,this.dataType=w.dataType,this.columnType=w.columnType,this.generated=w.generated,this.generatedIdentity=w.generatedIdentity}static[K]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var rD;var pD=R(()=>{E0();rD=class rD{static[K]="ColumnBuilder";config;constructor($,w,E){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:w,columnType:E,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}});function RU($,...w){return $(...w)}var zU=()=>{};function TU($,w){return`${$[G1]}_${w.join("_")}_unique`}var BU=R(()=>{LG()});var QJ,E2;var QU=R(()=>{b1();E0();BU();QJ=class QJ extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=TU($,[w.name]);super($,w);this.table=$}static[K]="PgColumn"};E2=class E2 extends QJ{static[K]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}});function KU($){return!!$&&typeof $==="function"&&IU in $&&$[IU]===!0}var IU,X2;var VU=R(()=>{E0();QU();IU=Symbol.for("drizzle:isPgEnum");X2=class X2 extends QJ{static[K]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,w){super($,w);this.enum=w.enum}getSQLType(){return this.enum.enumName}}});var Y$,jG;var d1=R(()=>{E0();Y$=class Y${static[K]="Subquery";constructor($,w,E,X=!1){this._={brand:"Subquery",sql:$,selectedFields:w,alias:E,isWith:X}}};jG=class jG extends Y${static[K]="WithSubquery"}});var PU="0.41.0";var qU=()=>{};var oD,tD,SU;var kU=R(()=>{zU();qU();SU={startActiveSpan($,w){if(!oD)return w();if(!tD)tD=oD.trace.getTracer("drizzle-orm",PU);return RU((E,X)=>X.startActiveSpan($,(G)=>{try{return w(G)}catch(J){throw G.setStatus({code:E.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),oD,tD)}}});var s0;var Lw=R(()=>{s0=Symbol.for("drizzle:ViewBaseConfig")});function iD($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function G2($){let w={sql:"",params:[]};for(let E of $)if(w.sql+=E.sql,w.params.push(...E.params),E.typings?.length){if(!w.typings)w.typings=[];w.typings.push(...E.typings)}return w}function bU($){return typeof $==="object"&&$!==null&&"mapToDriverValue"in $&&typeof $.mapToDriverValue==="function"}function T($,...w){let E=[];if(w.length>0||$.length>0&&$[0]!=="")E.push(new W$($[0]));for(let[X,G]of w.entries())E.push(G,new W$($[X+1]));return new h(E)}function MG($,w){return $.map((E)=>{if(b(E,yw)){if(!(E.name in w))throw Error(`No value for placeholder "${E.name}" was provided`);return w[E.name]}if(b(E,J1)&&b(E.value,yw)){if(!(E.value.name in w))throw Error(`No value for placeholder "${E.value.name}" was provided`);return E.encoder.mapToDriverValue(w[E.value.name])}return E})}var W$,h,IJ,ZU,CU,ut,J1,yw,J2,U1;var q$=R(()=>{E0();VU();d1();kU();Lw();b1();_$();W$=class W${static[K]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new h([this])}};h=class h{constructor($){this.queryChunks=$}static[K]="SQL";decoder=ZU;shouldInlineParams=!1;append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return SU.startActiveSpan("drizzle.buildSQL",(w)=>{let E=this.buildQueryFromSourceParams(this.queryChunks,$);return w?.setAttributes({"drizzle.query.text":E.sql,"drizzle.query.params":JSON.stringify(E.params)}),E})}buildQueryFromSourceParams($,w){let E=Object.assign({},w,{inlineParams:w.inlineParams||this.shouldInlineParams,paramStartIndex:w.paramStartIndex||{value:0}}),{casing:X,escapeName:G,escapeParam:J,prepareTyping:A,inlineParams:D,paramStartIndex:N}=E;return G2($.map((W)=>{if(b(W,W$))return{sql:W.value.join(""),params:[]};if(b(W,IJ))return{sql:G(W.value),params:[]};if(W===void 0)return{sql:"",params:[]};if(Array.isArray(W)){let O=[new W$("(")];for(let[Y,H]of W.entries())if(O.push(H),Y<W.length-1)O.push(new W$(", "));return O.push(new W$(")")),this.buildQueryFromSourceParams(O,E)}if(b(W,h))return this.buildQueryFromSourceParams(W.queryChunks,{...E,inlineParams:D||W.shouldInlineParams});if(b(W,y)){let O=W[y.Symbol.Schema],Y=W[y.Symbol.Name];return{sql:O===void 0||W[FG]?G(Y):G(O)+"."+G(Y),params:[]}}if(b(W,V0)){let O=X.getColumnCasing(W);if(w.invokeSource==="indexes")return{sql:G(O),params:[]};let Y=W.table[y.Symbol.Schema];return{sql:W.table[FG]||Y===void 0?G(W.table[y.Symbol.Name])+"."+G(O):G(Y)+"."+G(W.table[y.Symbol.Name])+"."+G(O),params:[]}}if(b(W,U1)){let O=W[s0].schema,Y=W[s0].name;return{sql:O===void 0||W[s0].isAlias?G(Y):G(O)+"."+G(Y),params:[]}}if(b(W,J1)){if(b(W.value,yw))return{sql:J(N.value++,W),params:[W],typings:["none"]};let O=W.value===null?null:W.encoder.mapToDriverValue(W.value);if(b(O,h))return this.buildQueryFromSourceParams([O],E);if(D)return{sql:this.mapInlineParam(O,E),params:[]};let Y=["none"];if(A)Y=[A(W.encoder)];return{sql:J(N.value++,O),params:[O],typings:Y}}if(b(W,yw))return{sql:J(N.value++,W),params:[W],typings:["none"]};if(b(W,h.Aliased)&&W.fieldAlias!==void 0)return{sql:G(W.fieldAlias),params:[]};if(b(W,Y$)){if(W._.isWith)return{sql:G(W._.alias),params:[]};return this.buildQueryFromSourceParams([new W$("("),W._.sql,new W$(") "),new IJ(W._.alias)],E)}if(KU(W)){if(W.schema)return{sql:G(W.schema)+"."+G(W.enumName),params:[]};return{sql:G(W.enumName),params:[]}}if(iD(W)){if(W.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([W.getSQL()],E);return this.buildQueryFromSourceParams([new W$("("),W.getSQL(),new W$(")")],E)}if(D)return{sql:this.mapInlineParam(W,E),params:[]};return{sql:J(N.value++,W),params:[W],typings:["none"]}}))}mapInlineParam($,{escapeString:w}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return w($);if(typeof $==="object"){let E=$.toString();if(E==="[object Object]")return w(JSON.stringify($));return w(E)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new h.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}};IJ=class IJ{constructor($){this.value=$}static[K]="Name";brand;getSQL(){return new h([this])}};ZU={mapFromDriverValue:($)=>$},CU={mapToDriverValue:($)=>$},ut={...ZU,...CU};J1=class J1{constructor($,w=CU){this.value=$,this.encoder=w}static[K]="Param";brand;getSQL(){return new h([this])}};(($)=>{function w(){return new h([])}$.empty=w;function E(N){return new h(N)}$.fromList=E;function X(N){return new h([new W$(N)])}$.raw=X;function G(N,W){let O=[];for(let[Y,H]of N.entries()){if(Y>0&&W!==void 0)O.push(W);O.push(H)}return new h(O)}$.join=G;function J(N){return new IJ(N)}$.identifier=J;function A(N){return new yw(N)}$.placeholder=A;function D(N,W){return new J1(N,W)}$.param=D})(T||(T={}));(($)=>{class w{constructor(E,X){this.sql=E,this.fieldAlias=X}static[K]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new w(this.sql,this.fieldAlias)}}$.Aliased=w})(h||(h={}));yw=class yw{constructor($){this.name=$}static[K]="Placeholder";getSQL(){return new h([this])}};J2=Symbol.for("drizzle:IsDrizzleView");U1=class U1{static[K]="View";[s0];[J2]=!0;constructor({name:$,schema:w,selectedFields:E,query:X}){this[s0]={name:$,originalName:$,schema:w,selectedFields:E,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new h([this])}};V0.prototype.getSQL=function(){return new h([this])};y.prototype.getSQL=function(){return new h([this])};Y$.prototype.getSQL=function(){return new h([this])}});function dD($,w,E){let X={},G=$.reduce((J,{path:A,field:D},N)=>{let W;if(b(D,V0))W=D;else if(b(D,h))W=D.decoder;else W=D.sql.decoder;let O=J;for(let[Y,H]of A.entries())if(Y<A.length-1){if(!(H in O))O[H]={};O=O[H]}else{let L=w[N],F=O[H]=L===null?null:W.mapFromDriverValue(L);if(E&&b(D,V0)&&A.length===2){let j=A[0];if(!(j in X))X[j]=F===null?xw(D.table):!1;else if(typeof X[j]==="string"&&X[j]!==xw(D.table))X[j]=!1}}return J},{});if(E&&Object.keys(X).length>0){for(let[J,A]of Object.entries(X))if(typeof A==="string"&&!E[A])G[J]=null}return G}function Y1($,w){return Object.entries($).reduce((E,[X,G])=>{if(typeof X!=="string")return E;let J=w?[...w,X]:[X];if(b(G,V0)||b(G,h)||b(G,h.Aliased))E.push({path:J,field:G});else if(b(G,y))E.push(...Y1(G[y.Symbol.Columns],J));else E.push(...Y1(G,J));return E},[])}function RG($,w){let E=Object.keys($),X=Object.keys(w);if(E.length!==X.length)return!1;for(let[G,J]of E.entries())if(J!==X[G])return!1;return!0}function KJ($,w){let E=Object.entries(w).filter(([,X])=>X!==void 0).map(([X,G])=>{if(b(G,h)||b(G,V0))return[X,G];else return[X,new J1(G,$[y.Symbol.Columns][X])]});if(E.length===0)throw Error("No values to set");return Object.fromEntries(E)}function _U($,w){for(let E of w)for(let X of Object.getOwnPropertyNames(E.prototype)){if(X==="constructor")continue;Object.defineProperty($.prototype,X,Object.getOwnPropertyDescriptor(E.prototype,X)||Object.create(null))}}function vU($){return $[y.Symbol.Columns]}function zG($){return b($,Y$)?$._.alias:b($,U1)?$[s0].name:b($,h)?void 0:$[y.Symbol.IsAlias]?$[y.Symbol.Name]:$[y.Symbol.BaseName]}function l1($,w){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:w}}function fU($){if(typeof $!=="object"||$===null)return!1;if($.constructor.name!=="Object")return!1;if("logger"in $){let w=typeof $.logger;if(w!=="boolean"&&(w!=="object"||typeof $.logger.logQuery!=="function")&&w!=="undefined")return!1;return!0}if("schema"in $){let w=typeof $.schema;if(w!=="object"&&w!=="undefined")return!1;return!0}if("casing"in $){let w=typeof $.casing;if(w!=="string"&&w!=="undefined")return!1;return!0}if("mode"in $){if($.mode!=="default"||$.mode!=="planetscale"||$.mode!==void 0)return!1;return!0}if("connection"in $){let w=typeof $.connection;if(w!=="string"&&w!=="object"&&w!=="undefined")return!1;return!0}if("client"in $){let w=typeof $.client;if(w!=="object"&&w!=="function"&&w!=="undefined")return!1;return!0}if(Object.keys($).length===0)return!0;return!1}var o$=R(()=>{b1();E0();q$();d1();_$();Lw()});var xU,yU,lD;var gU=R(()=>{E0();_$();xU=Symbol.for("drizzle:PgInlineForeignKeys"),yU=Symbol.for("drizzle:EnableRLS");lD=class lD extends y{static[K]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:xU,EnableRLS:yU});[xU]=[];[yU]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}});var sD,uU;var hU=R(()=>{E0();gU();sD=class sD{static[K]="PgPrimaryKeyBuilder";columns;name;constructor($,w){this.columns=$,this.name=w}build($){return new uU($,this.columns,this.name)}};uU=class uU{constructor($,w,E){this.table=$,this.columns=w,this.name=E}static[K]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[lD.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}});function t$($,w){if(bU(w)&&!iD($)&&!b($,J1)&&!b($,yw)&&!b($,V0)&&!b($,y)&&!b($,U1))return new J1($,w);return $}function S0(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new W$("("),T.join(w,new W$(" and ")),new W$(")")])}function VJ(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new W$("("),T.join(w,new W$(" or ")),new W$(")")])}function nU($){return T`not ${$}`}function PJ($,w){if(Array.isArray(w)){if(w.length===0)return T`false`;return T`${$} in ${w.map((E)=>t$(E,$))}`}return T`${$} in ${t$(w,$)}`}function tU($,w){if(Array.isArray(w)){if(w.length===0)return T`true`;return T`${$} not in ${w.map((E)=>t$(E,$))}`}return T`${$} not in ${t$(w,$)}`}function iU($){return T`${$} is null`}function dU($){return T`${$} is not null`}function lU($){return T`exists ${$}`}function sU($){return T`not exists ${$}`}function aU($,w,E){return T`${$} between ${t$(w,$)} and ${t$(E,$)}`}function eU($,w,E){return T`${$} not between ${t$(w,$)} and ${t$(E,$)}`}function $7($,w){return T`${$} like ${w}`}function w7($,w){return T`${$} not like ${w}`}function E7($,w){return T`${$} ilike ${w}`}function X7($,w){return T`${$} not ilike ${w}`}var V=($,w)=>{return T`${$} = ${t$(w,$)}`},cU=($,w)=>{return T`${$} <> ${t$(w,$)}`},mU=($,w)=>{return T`${$} > ${t$(w,$)}`},rU=($,w)=>{return T`${$} >= ${t$(w,$)}`},pU=($,w)=>{return T`${$} < ${t$(w,$)}`},oU=($,w)=>{return T`${$} <= ${t$(w,$)}`};var G7=R(()=>{b1();E0();_$();q$()});function qJ($){return T`${$} asc`}function x0($){return T`${$} desc`}var J7=R(()=>{q$()});var SJ=R(()=>{G7();J7()});function D7(){return{and:S0,between:aU,eq:V,exists:lU,gt:mU,gte:rU,ilike:E7,inArray:PJ,isNull:iU,isNotNull:dU,like:$7,lt:pU,lte:oU,ne:cU,not:nU,notBetween:eU,notExists:sU,notLike:w7,notIlike:X7,notInArray:tU,or:VJ,sql:T}}function N7(){return{sql:T,asc:qJ,desc:x0}}function W7($,w){if(Object.keys($).length===1&&"default"in $&&!b($.default,y))$=$.default;let E={},X={},G={};for(let[J,A]of Object.entries($))if(b(A,y)){let D=UE(A),N=X[D];E[D]=J,G[J]={tsName:J,dbName:A[y.Symbol.Name],schema:A[y.Symbol.Schema],columns:A[y.Symbol.Columns],relations:N?.relations??{},primaryKey:N?.primaryKey??[]};for(let O of Object.values(A[y.Symbol.Columns]))if(O.primary)G[J].primaryKey.push(O);let W=A[y.Symbol.ExtraConfigBuilder]?.(A[y.Symbol.ExtraConfigColumns]);if(W){for(let O of Object.values(W))if(b(O,sD))G[J].primaryKey.push(...O.columns)}}else if(b(A,A7)){let D=UE(A.table),N=E[D],W=A.config(w(A.table)),O;for(let[Y,H]of Object.entries(W))if(N){let L=G[N];if(L.relations[Y]=H,O)L.primaryKey.push(...O)}else{if(!(D in X))X[D]={relations:{},primaryKey:O};X[D].relations[Y]=H}}return{tables:G,tableNamesMap:E}}function A2($){return function(E,X){return new gw($,E,X,X?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function D2($){return function(E,X){return new TG($,E,X)}}function O7($,w,E){if(b(E,gw)&&E.config)return{fields:E.config.fields,references:E.config.references};let X=w[UE(E.referencedTable)];if(!X)throw Error(`Table "${E.referencedTable[y.Symbol.Name]}" not found in schema`);let G=$[X];if(!G)throw Error(`Table "${X}" not found in schema`);let J=E.sourceTable,A=w[UE(J)];if(!A)throw Error(`Table "${J[y.Symbol.Name]}" not found in schema`);let D=[];for(let N of Object.values(G.relations))if(E.relationName&&E!==N&&N.relationName===E.relationName||!E.relationName&&N.referencedTable===E.sourceTable)D.push(N);if(D.length>1)throw E.relationName?Error(`There are multiple relations with name "${E.relationName}" in table "${X}"`):Error(`There are multiple relations between "${X}" and "${E.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(D[0]&&b(D[0],gw)&&D[0].config)return{fields:D[0].config.references,references:D[0].config.fields};throw Error(`There is not enough information to infer relation "${A}.${E.fieldName}"`)}function U7($){return{one:A2($),many:D2($)}}function kJ($,w,E,X,G=(J)=>J){let J={};for(let[A,D]of X.entries())if(D.isJson){let N=w.relations[D.tsKey],W=E[A],O=typeof W==="string"?JSON.parse(W):W;J[D.tsKey]=b(N,gw)?O&&kJ($,$[D.relationTableTsKey],O,D.selection,G):O.map((Y)=>kJ($,$[D.relationTableTsKey],Y,D.selection,G))}else{let N=G(E[A]),W=D.field,O;if(b(W,V0))O=W;else if(b(W,h))O=W.decoder;else O=W.sql.decoder;J[D.tsKey]=N===null?null:O.mapFromDriverValue(N)}return J}var aD,A7,gw,TG;var BG=R(()=>{_$();b1();E0();hU();SJ();q$();aD=class aD{constructor($,w,E){this.sourceTable=$,this.referencedTable=w,this.relationName=E,this.referencedTableName=w[y.Symbol.Name]}static[K]="Relation";referencedTableName;fieldName};A7=class A7{constructor($,w){this.table=$,this.config=w}static[K]="Relations"};gw=class gw extends aD{constructor($,w,E,X){super($,w,E?.relationName);this.config=E,this.isNullable=X}static[K]="One";withFieldName($){let w=new gw(this.sourceTable,this.referencedTable,this.config,this.isNullable);return w.fieldName=$,w}};TG=class TG extends aD{constructor($,w,E){super($,w,E?.relationName);this.config=E}static[K]="Many";withFieldName($){let w=new TG(this.sourceTable,this.referencedTable,this.config);return w.fieldName=$,w}}});function bJ($,w){return new Proxy($,new QG(w,!1))}function s1($,w){return new Proxy($,new sE(new Proxy($.table,new QG(w,!1))))}function eD($,w){return new h.Aliased(IG($.sql,w),$.fieldAlias)}function IG($,w){return T.join($.queryChunks.map((E)=>{if(b(E,V0))return s1(E,w);if(b(E,h))return IG(E,w);if(b(E,h.Aliased))return eD(E,w);return E}))}var sE,QG;var ZJ=R(()=>{b1();E0();q$();_$();Lw();sE=class sE{constructor($){this.table=$}static[K]="ColumnAliasProxyHandler";get($,w){if(w==="table")return this.table;return $[w]}};QG=class QG{constructor($,w){this.alias=$,this.replaceOriginalName=w}static[K]="TableAliasProxyHandler";get($,w){if(w===y.Symbol.IsAlias)return!0;if(w===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&w===y.Symbol.OriginalName)return this.alias;if(w===s0)return{...$[s0],name:this.alias,isAlias:!0};if(w===y.Symbol.Columns){let X=$[y.Symbol.Columns];if(!X)return X;let G={};return Object.keys(X).map((J)=>{G[J]=new Proxy(X[J],new sE(new Proxy($,this)))}),G}let E=$[w];if(b(E,V0))return new Proxy(E,new sE(new Proxy($,this)));return E}}});var A$;var aE=R(()=>{ZJ();b1();E0();q$();d1();Lw();A$=class A${static[K]="SelectionProxyHandler";config;constructor($){this.config={...$}}get($,w){if(w==="_")return{...$._,selectedFields:new Proxy($._.selectedFields,this)};if(w===s0)return{...$[s0],selectedFields:new Proxy($[s0].selectedFields,this)};if(typeof w==="symbol")return $[w];let X=(b($,Y$)?$._.selectedFields:b($,U1)?$[s0].selectedFields:$)[w];if(b(X,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!X.isSelectionField)return X.sql;let G=X.clone();return G.isSelectionField=!0,G}if(b(X,h)){if(this.config.sqlBehavior==="sql")return X;throw Error(`You tried to reference "${w}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(b(X,V0)){if(this.config.alias)return new Proxy(X,new sE(new Proxy(X.table,new QG(this.config.alias,this.config.replaceOriginalName??!1))));return X}if(typeof X!=="object"||X===null)return X;return new Proxy(X,new A$(this.config))}}});var v$;var Fw=R(()=>{E0();v$=class v${static[K]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}then($,w){return this.execute().then($,w)}}});var $8,Y7;var w8=R(()=>{E0();LG();$8=class $8{static[K]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,w){if(this.reference=()=>{let{name:E,columns:X,foreignColumns:G}=$();return{name:E,columns:X,foreignTable:G[0].table,foreignColumns:G}},w)this._onUpdate=w.onUpdate,this._onDelete=w.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new Y7($,this)}};Y7=class Y7{constructor($,w){this.table=$,this.reference=w.reference,this.onUpdate=w._onUpdate,this.onDelete=w._onDelete}static[K]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:w,foreignColumns:E}=this.reference(),X=w.map((A)=>A.name),G=E.map((A)=>A.name),J=[this.table[G1],...X,E[0].table[G1],...G];return $??`${J.join("_")}_fk`}}});function H7($,w){return`${$[G1]}_${w.join("_")}_unique`}var E8=R(()=>{LG()});var H$,w$;var uw=R(()=>{pD();b1();E0();w8();E8();H$=class H$ extends rD{static[K]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,w={}){return this.foreignKeyConfigs.push({ref:$,actions:w}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,w){return this.config.generated={as:$,type:"always",mode:w?.mode??"virtual"},this}buildForeignKeys($,w){return this.foreignKeyConfigs.map(({ref:E,actions:X})=>{return((G,J)=>{let A=new $8(()=>{let D=G();return{columns:[$],foreignColumns:[D]}});if(J.onUpdate)A.onUpdate(J.onUpdate);if(J.onDelete)A.onDelete(J.onDelete);return A.build(w)})(E,X)})}};w$=class w$ extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=H7($,[w.name]);super($,w);this.table=$}static[K]="SQLiteColumn"}});function T7($,w){let{name:E,config:X}=l1($,w);if(X?.mode==="json")return new j7(E);if(X?.mode==="bigint")return new L7(E);return new R7(E)}var L7,F7,j7,M7,R7,z7;var X8=R(()=>{E0();o$();uw();L7=class L7 extends H${static[K]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new F7($,this.config)}};F7=class F7 extends w${static[K]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return BigInt($.toString());if($ instanceof ArrayBuffer)return BigInt(new TextDecoder().decode($));return BigInt(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from($.toString())}};j7=class j7 extends H${static[K]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new M7($,this.config)}};M7=class M7 extends w${static[K]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return JSON.parse($.toString());if($ instanceof ArrayBuffer)return JSON.parse(new TextDecoder().decode($));return JSON.parse(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}};R7=class R7 extends H${static[K]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new z7($,this.config)}};z7=class z7 extends w${static[K]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}});function I7($){return(w,E)=>{let{name:X,config:G}=l1(w,E);return new B7(X,G,$)}}var B7,Q7;var G8=R(()=>{E0();o$();uw();B7=class B7 extends H${static[K]="SQLiteCustomColumnBuilder";constructor($,w,E){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=w,this.config.customTypeParams=E}build($){return new Q7($,this.config)}};Q7=class Q7 extends w${static[K]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,w){super($,w);this.sqlName=w.customTypeParams.dataType(w.fieldConfig),this.mapTo=w.customTypeParams.toDriver,this.mapFrom=w.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}});function s($,w){let{name:E,config:X}=l1($,w);if(X?.mode==="timestamp"||X?.mode==="timestamp_ms")return new P7(E,X.mode);if(X?.mode==="boolean")return new S7(E,X.mode);return new K7(E)}var CJ,_J,K7,V7,P7,q7,S7,k7;var J8=R(()=>{E0();q$();o$();uw();CJ=class CJ extends H${static[K]="SQLiteBaseIntegerBuilder";constructor($,w,E){super($,w,E);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};_J=class _J extends w${static[K]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};K7=class K7 extends CJ{static[K]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new V7($,this.config)}};V7=class V7 extends _J{static[K]="SQLiteInteger"};P7=class P7 extends CJ{static[K]="SQLiteTimestampBuilder";constructor($,w){super($,"date","SQLiteTimestamp");this.config.mode=w}defaultNow(){return this.default(T`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new q7($,this.config)}};q7=class q7 extends _J{static[K]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let w=$.getTime();if(this.config.mode==="timestamp")return Math.floor(w/1000);return w}};S7=class S7 extends CJ{static[K]="SQLiteBooleanBuilder";constructor($,w){super($,"boolean","SQLiteBoolean");this.config.mode=w}build($){return new k7($,this.config)}};k7=class k7 extends _J{static[K]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}});function x7($,w){let{name:E,config:X}=l1($,w),G=X?.mode;return G==="number"?new C7(E):G==="bigint"?new v7(E):new b7(E)}var b7,Z7,C7,_7,v7,f7;var A8=R(()=>{E0();o$();uw();b7=class b7 extends H${static[K]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Z7($,this.config)}};Z7=class Z7 extends w${static[K]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}};C7=class C7 extends H${static[K]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new _7($,this.config)}};_7=class _7 extends w${static[K]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}};v7=class v7 extends H${static[K]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new f7($,this.config)}};f7=class f7 extends w${static[K]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function u7($){return new y7($??"")}var y7,g7;var D8=R(()=>{E0();uw();y7=class y7 extends H${static[K]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new g7($,this.config)}};g7=class g7 extends w${static[K]="SQLiteReal";getSQLType(){return"real"}}});function q($,w={}){let{name:E,config:X}=l1($,w);if(X.mode==="json")return new n7(E);return new h7(E,X)}var h7,c7,n7,m7;var N8=R(()=>{E0();o$();uw();h7=class h7 extends H${static[K]="SQLiteTextBuilder";constructor($,w){super($,"string","SQLiteText");this.config.enumValues=w.enum,this.config.length=w.length}build($){return new c7($,this.config)}};c7=class c7 extends w${static[K]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,w){super($,w)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};n7=class n7 extends H${static[K]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new m7($,this.config)}};m7=class m7 extends w${static[K]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}});function r7(){return{blob:T7,customType:I7,integer:s,numeric:x7,real:u7,text:q}}var p7=R(()=>{X8();G8();J8();A8();D8();N8()});function N2($,w,E,X,G=$){let J=new S$($,X,G),A=typeof w==="function"?w(r7()):w,D=Object.fromEntries(Object.entries(A).map(([W,O])=>{let Y=O;Y.setName(W);let H=Y.build(J);return J[W8].push(...Y.buildForeignKeys(H,J)),[W,H]})),N=Object.assign(J,D);if(N[y.Symbol.Columns]=D,N[y.Symbol.ExtraConfigColumns]=D,E)N[S$.Symbol.ExtraConfigBuilder]=E;return N}var W8,S$,M$=($,w,E)=>{return N2($,w,E)};var eE=R(()=>{E0();_$();p7();W8=Symbol.for("drizzle:SQLiteInlineForeignKeys");S$=class S$ extends y{static[K]="SQLiteTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:W8});[y.Symbol.Columns];[W8]=[];[y.Symbol.ExtraConfigBuilder]=void 0}});var vJ;var o7=R(()=>{E0();Fw();aE();eE();_$();o$();vJ=class vJ extends v${constructor($,w,E,X){super();this.table=$,this.session=w,this.dialect=E,this.config={table:$,withList:X}}static[K]="SQLiteDelete";config;where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute($){return this._prepare().execute($)}$dynamic(){return this}}});function W2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((E)=>E.toLowerCase()).join("_")}function O2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((E,X,G)=>{let J=G===0?X.toLowerCase():`${X[0].toUpperCase()}${X.slice(1)}`;return E+J},"")}function U2($){return $}var O8;var t7=R(()=>{E0();_$();O8=class O8{static[K]="CasingCache";cache={};cachedTables={};convert;constructor($){this.convert=$==="snake_case"?W2:$==="camelCase"?O2:U2}getColumnCasing($){if(!$.keyAsName)return $.name;let w=$.table[y.Symbol.Schema]??"public",E=$.table[y.Symbol.OriginalName],X=`${w}.${E}.${$.name}`;if(!this.cache[X])this.cacheTable($.table);return this.cache[X]}cacheTable($){let w=$[y.Symbol.Schema]??"public",E=$[y.Symbol.OriginalName],X=`${w}.${E}`;if(!this.cachedTables[X]){for(let G of Object.values($[y.Symbol.Columns])){let J=`${X}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[X]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var $X,U8;var fJ=R(()=>{E0();$X=class $X extends Error{static[K]="DrizzleError";constructor({message:$,cause:w}){super($);this.name="DrizzleError",this.cause=w}};U8=class U8 extends $X{static[K]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var i7=()=>{};var d7=()=>{};var l7=R(()=>{i7();d7()});var Y8=R(()=>{SJ();l7();q$()});var H8=R(()=>{X8();uw();G8();J8();A8();D8();N8()});var YE;var xJ=R(()=>{E0();q$();YE=class YE extends U1{static[K]="SQLiteViewBase"}});var KG,VG;var yJ=R(()=>{ZJ();t7();b1();E0();fJ();BG();Y8();q$();H8();eE();d1();_$();o$();Lw();xJ();KG=class KG{static[K]="SQLiteDialect";casing;constructor($){this.casing=new O8($?.casing)}escapeName($){return`"${$}"`}escapeParam($){return"?"}escapeString($){return`'${$.replace(/'/g,"''")}'`}buildWithCTE($){if(!$?.length)return;let w=[T`with `];for(let[E,X]of $.entries())if(w.push(T`${T.identifier(X._.alias)} as (${X._.sql})`),E<$.length-1)w.push(T`, `);return w.push(T` `),T.join(w)}buildDeleteQuery({table:$,where:w,returning:E,withList:X,limit:G,orderBy:J}){let A=this.buildWithCTE(X),D=E?T` returning ${this.buildSelection(E,{isSingleTable:!0})}`:void 0,N=w?T` where ${w}`:void 0,W=this.buildOrderBy(J),O=this.buildLimit(G);return T`${A}delete from ${$}${N}${D}${W}${O}`}buildUpdateSet($,w){let E=$[y.Symbol.Columns],X=Object.keys(E).filter((J)=>w[J]!==void 0||E[J]?.onUpdateFn!==void 0),G=X.length;return T.join(X.flatMap((J,A)=>{let D=E[J],N=w[J]??T.param(D.onUpdateFn(),D),W=T`${T.identifier(this.casing.getColumnCasing(D))} = ${N}`;if(A<G-1)return[W,T.raw(", ")];return[W]}))}buildUpdateQuery({table:$,set:w,where:E,returning:X,withList:G,joins:J,from:A,limit:D,orderBy:N}){let W=this.buildWithCTE(G),O=this.buildUpdateSet($,w),Y=A&&T.join([T.raw(" from "),this.buildFromTable(A)]),H=this.buildJoins(J),L=X?T` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,F=E?T` where ${E}`:void 0,j=this.buildOrderBy(N),M=this.buildLimit(D);return T`${W}update ${$} set ${O}${Y}${H}${F}${L}${j}${M}`}buildSelection($,{isSingleTable:w=!1}={}){let E=$.length,X=$.flatMap(({field:G},J)=>{let A=[];if(b(G,h.Aliased)&&G.isSelectionField)A.push(T.identifier(G.fieldAlias));else if(b(G,h.Aliased)||b(G,h)){let D=b(G,h.Aliased)?G.sql:G;if(w)A.push(new h(D.queryChunks.map((N)=>{if(b(N,V0))return T.identifier(this.casing.getColumnCasing(N));return N})));else A.push(D);if(b(G,h.Aliased))A.push(T` as ${T.identifier(G.fieldAlias)}`)}else if(b(G,V0)){let D=G.table[y.Symbol.Name];if(G.columnType==="SQLiteNumericBigInt")if(w)A.push(T`cast(${T.identifier(this.casing.getColumnCasing(G))} as text)`);else A.push(T`cast(${T.identifier(D)}.${T.identifier(this.casing.getColumnCasing(G))} as text)`);else if(w)A.push(T.identifier(this.casing.getColumnCasing(G)));else A.push(T`${T.identifier(D)}.${T.identifier(this.casing.getColumnCasing(G))}`)}if(J<E-1)A.push(T`, `);return A});return T.join(X)}buildJoins($){if(!$||$.length===0)return;let w=[];if($)for(let[E,X]of $.entries()){if(E===0)w.push(T` `);let G=X.table;if(b(G,S$)){let J=G[S$.Symbol.Name],A=G[S$.Symbol.Schema],D=G[S$.Symbol.OriginalName],N=J===D?void 0:X.alias;w.push(T`${T.raw(X.joinType)} join ${A?T`${T.identifier(A)}.`:void 0}${T.identifier(D)}${N&&T` ${T.identifier(N)}`} on ${X.on}`)}else w.push(T`${T.raw(X.joinType)} join ${G} on ${X.on}`);if(E<$.length-1)w.push(T` `)}return T.join(w)}buildLimit($){return typeof $==="object"||typeof $==="number"&&$>=0?T` limit ${$}`:void 0}buildOrderBy($){let w=[];if($){for(let[E,X]of $.entries())if(w.push(X),E<$.length-1)w.push(T`, `)}return w.length>0?T` order by ${T.join(w)}`:void 0}buildFromTable($){if(b($,y)&&$[y.Symbol.IsAlias])return T`${T`${T.identifier($[y.Symbol.Schema]??"")}.`.if($[y.Symbol.Schema])}${T.identifier($[y.Symbol.OriginalName])} ${T.identifier($[y.Symbol.Name])}`;return $}buildSelectQuery({withList:$,fields:w,fieldsFlat:E,where:X,having:G,table:J,joins:A,orderBy:D,groupBy:N,limit:W,offset:O,distinct:Y,setOperators:H}){let L=E??Y1(w);for(let K0 of L)if(b(K0.field,V0)&&xw(K0.field.table)!==(b(J,Y$)?J._.alias:b(J,YE)?J[s0].name:b(J,h)?void 0:xw(J))&&!((U$)=>A?.some(({alias:O1})=>O1===(U$[y.Symbol.IsAlias]?xw(U$):U$[y.Symbol.BaseName])))(K0.field.table)){let U$=xw(K0.field.table);throw Error(`Your "${K0.path.join("->")}" field references a column "${U$}"."${K0.field.name}", but the table "${U$}" is not part of the query! Did you forget to join it?`)}let F=!A||A.length===0,j=this.buildWithCTE($),M=Y?T` distinct`:void 0,z=this.buildSelection(L,{isSingleTable:F}),B=this.buildFromTable(J),Q=this.buildJoins(A),k=X?T` where ${X}`:void 0,v=G?T` having ${G}`:void 0,C=[];if(N){for(let[K0,U$]of N.entries())if(C.push(U$),K0<N.length-1)C.push(T`, `)}let n=C.length>0?T` group by ${T.join(C)}`:void 0,T0=this.buildOrderBy(D),f0=this.buildLimit(W),c0=O?T` offset ${O}`:void 0,d0=T`${j}select${M} ${z} from ${B}${Q}${k}${n}${v}${T0}${f0}${c0}`;if(H.length>0)return this.buildSetOperations(d0,H);return d0}buildSetOperations($,w){let[E,...X]=w;if(!E)throw Error("Cannot pass undefined values to any set operator");if(X.length===0)return this.buildSetOperationQuery({leftSelect:$,setOperator:E});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:$,setOperator:E}),X)}buildSetOperationQuery({leftSelect:$,setOperator:{type:w,isAll:E,rightSelect:X,limit:G,orderBy:J,offset:A}}){let D=T`${$.getSQL()} `,N=T`${X.getSQL()}`,W;if(J&&J.length>0){let L=[];for(let F of J)if(b(F,w$))L.push(T.identifier(F.name));else if(b(F,h)){for(let j=0;j<F.queryChunks.length;j++){let M=F.queryChunks[j];if(b(M,w$))F.queryChunks[j]=T.identifier(this.casing.getColumnCasing(M))}L.push(T`${F}`)}else L.push(T`${F}`);W=T` order by ${T.join(L,T`, `)}`}let O=typeof G==="object"||typeof G==="number"&&G>=0?T` limit ${G}`:void 0,Y=T.raw(`${w} ${E?"all ":""}`),H=A?T` offset ${A}`:void 0;return T`${D}${Y}${N}${W}${O}${H}`}buildInsertQuery({table:$,values:w,onConflict:E,returning:X,withList:G,select:J}){let A=[],D=$[y.Symbol.Columns],N=Object.entries(D).filter(([F,j])=>!j.shouldDisableInsert()),W=N.map(([,F])=>T.identifier(this.casing.getColumnCasing(F)));if(J){let F=w;if(b(F,h))A.push(F);else A.push(F.getSQL())}else{let F=w;A.push(T.raw("values "));for(let[j,M]of F.entries()){let z=[];for(let[B,Q]of N){let k=M[B];if(k===void 0||b(k,J1)&&k.value===void 0){let v;if(Q.default!==null&&Q.default!==void 0)v=b(Q.default,h)?Q.default:T.param(Q.default,Q);else if(Q.defaultFn!==void 0){let C=Q.defaultFn();v=b(C,h)?C:T.param(C,Q)}else if(!Q.default&&Q.onUpdateFn!==void 0){let C=Q.onUpdateFn();v=b(C,h)?C:T.param(C,Q)}else v=T`null`;z.push(v)}else z.push(k)}if(A.push(z),j<F.length-1)A.push(T`, `)}}let O=this.buildWithCTE(G),Y=T.join(A),H=X?T` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,L=E?.length?T.join(E):void 0;return T`${O}insert into ${$} ${W} ${Y}${L}${H}`}sqlToQuery($,w){return $.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:w})}buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:X,tableConfig:G,queryConfig:J,tableAlias:A,nestedQueryRelation:D,joinOn:N}){let W=[],O,Y,H=[],L,F=[];if(J===!0)W=Object.entries(G.columns).map(([z,B])=>({dbKey:B.name,tsKey:z,field:s1(B,A),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let M=Object.fromEntries(Object.entries(G.columns).map(([C,n])=>[C,s1(n,A)]));if(J.where){let C=typeof J.where==="function"?J.where(M,D7()):J.where;L=C&&IG(C,A)}let z=[],B=[];if(J.columns){let C=!1;for(let[n,T0]of Object.entries(J.columns)){if(T0===void 0)continue;if(n in G.columns){if(!C&&T0===!0)C=!0;B.push(n)}}if(B.length>0)B=C?B.filter((n)=>J.columns?.[n]===!0):Object.keys(G.columns).filter((n)=>!B.includes(n))}else B=Object.keys(G.columns);for(let C of B){let n=G.columns[C];z.push({tsKey:C,value:n})}let Q=[];if(J.with)Q=Object.entries(J.with).filter((C)=>!!C[1]).map(([C,n])=>({tsKey:C,queryConfig:n,relation:G.relations[C]}));let k;if(J.extras){k=typeof J.extras==="function"?J.extras(M,{sql:T}):J.extras;for(let[C,n]of Object.entries(k))z.push({tsKey:C,value:eD(n,A)})}for(let{tsKey:C,value:n}of z)W.push({dbKey:b(n,h.Aliased)?n.fieldAlias:G.columns[C].name,tsKey:C,field:b(n,V0)?s1(n,A):n,relationTableTsKey:void 0,isJson:!1,selection:[]});let v=typeof J.orderBy==="function"?J.orderBy(M,N7()):J.orderBy??[];if(!Array.isArray(v))v=[v];H=v.map((C)=>{if(b(C,V0))return s1(C,A);return IG(C,A)}),O=J.limit,Y=J.offset;for(let{tsKey:C,queryConfig:n,relation:T0}of Q){let f0=O7(w,E,T0),c0=UE(T0.referencedTable),d0=E[c0],K0=`${A}_${C}`,U$=S0(...f0.fields.map((SV,kV)=>V(s1(f0.references[kV],K0),s1(SV,A)))),O1=this.buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:$[d0],tableConfig:w[d0],queryConfig:b(T0,gw)?n===!0?{limit:1}:{...n,limit:1}:n,tableAlias:K0,joinOn:U$,nestedQueryRelation:T0}),qV=T`(${O1.sql})`.as(C);W.push({dbKey:C,tsKey:C,field:qV,relationTableTsKey:d0,isJson:!0,selection:O1.selection})}}if(W.length===0)throw new $X({message:`No fields selected for table "${G.tsName}" ("${A}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let j;if(L=S0(N,L),D){let M=T`json_array(${T.join(W.map(({field:Q})=>b(Q,w$)?T.identifier(this.casing.getColumnCasing(Q)):b(Q,h.Aliased)?Q.sql:Q),T`, `)})`;if(b(D,TG))M=T`coalesce(json_group_array(${M}), json_array())`;let z=[{dbKey:"data",tsKey:"data",field:M.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:W}];if(O!==void 0||Y!==void 0||H.length>0)j=this.buildSelectQuery({table:bJ(X,A),fields:{},fieldsFlat:[{path:[],field:T.raw("*")}],where:L,limit:O,offset:Y,orderBy:H,setOperators:[]}),L=void 0,O=void 0,Y=void 0,H=void 0;else j=bJ(X,A);j=this.buildSelectQuery({table:b(j,S$)?j:new Y$(j,{},A),fields:{},fieldsFlat:z.map(({field:Q})=>({path:[],field:b(Q,V0)?s1(Q,A):Q})),joins:F,where:L,limit:O,offset:Y,orderBy:H,setOperators:[]})}else j=this.buildSelectQuery({table:bJ(X,A),fields:{},fieldsFlat:W.map(({field:M})=>({path:[],field:b(M,V0)?s1(M,A):M})),joins:F,where:L,limit:O,offset:Y,orderBy:H,setOperators:[]});return{tableTsKey:G.tsName,sql:j,selection:W}}};VG=class VG extends KG{static[K]="SQLiteSyncDialect";migrate($,w,E){let X=E===void 0?"__drizzle_migrations":typeof E==="string"?"__drizzle_migrations":E.migrationsTable??"__drizzle_migrations",G=T`
30
- CREATE TABLE IF NOT EXISTS ${T.identifier(X)} (
26
+ `),this.outputHelp({error:!0});let E=w||{},X=E.exitCode||1,G=E.code||"commander.error";this._exit(X,G,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in K0.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,K0.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new gq(this.options),w=(E)=>{return this.getOptionValue(E)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(E))};this.options.filter((E)=>E.implied!==void 0&&w(E.attributeName())&&$.valueFromOption(this.getOptionValue(E.attributeName()),E)).forEach((E)=>{Object.keys(E.implied).filter((X)=>!w(X)).forEach((X)=>{this.setOptionValueWithSource(X,E.implied[X],"implied")})})}missingArgument($){let w=`error: missing required argument '${$}'`;this.error(w,{code:"commander.missingArgument"})}optionMissingArgument($){let w=`error: option '${$.flags}' argument missing`;this.error(w,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let w=`error: required option '${$.flags}' not specified`;this.error(w,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,w){let E=(A)=>{let N=A.attributeName(),D=this.getOptionValue(N),O=this.options.find((J)=>J.negate&&N===J.attributeName()),W=this.options.find((J)=>!J.negate&&N===J.attributeName());if(O&&(O.presetArg===void 0&&D===!1||O.presetArg!==void 0&&D===O.presetArg))return O;return W||A},X=(A)=>{let N=E(A),D=N.attributeName();if(this.getOptionValueSource(D)==="env")return`environment variable '${N.envVar}'`;return`option '${N.flags}'`},G=`error: ${X($)} cannot be used with ${X(w)}`;this.error(G,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let w="";if($.startsWith("--")&&this._showSuggestionAfterError){let X=[],G=this;do{let A=G.createHelp().visibleOptions(G).filter((N)=>N.long).map((N)=>N.long);X=X.concat(A),G=G.parent}while(G&&!G._enablePositionalOptions);w=H5($,X)}let E=`error: unknown option '${$}'${w}`;this.error(E,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,E=w===1?"":"s",G=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${E} but got ${$.length}.`;this.error(G,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],w="";if(this._showSuggestionAfterError){let X=[];this.createHelp().visibleCommands(this).forEach((G)=>{if(X.push(G.name()),G.alias())X.push(G.alias())}),w=H5($,X)}let E=`error: unknown command '${$}'${w}`;this.error(E,{code:"commander.unknownCommand"})}version($,w,E){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",E=E||"output the version number";let X=this.createOption(w,E);return this._versionOptionName=X.attributeName(),this._registerOption(X),this.on("option:"+X.name(),()=>{this._outputConfiguration.writeOut(`${$}
27
+ `),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let E=this.parent?._findCommand($);if(E){let X=[E.name()].concat(E.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${X}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((E)=>{return vq(E)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?w:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=YE.basename($,YE.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),E=this._getOutputContext($);w.prepareContext({error:E.error,helpWidth:E.helpWidth,outputHasColors:E.hasColors});let X=w.formatHelp(this,w);if(E.hasColors)return X;return this._outputConfiguration.stripColor(X)}_getOutputContext($){$=$||{};let w=!!$.error,E,X,G;if(w)E=(N)=>this._outputConfiguration.writeErr(N),X=this._outputConfiguration.getErrHasColors(),G=this._outputConfiguration.getErrHelpWidth();else E=(N)=>this._outputConfiguration.writeOut(N),X=this._outputConfiguration.getOutHasColors(),G=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(N)=>{if(!X)N=this._outputConfiguration.stripColor(N);return E(N)},hasColors:X,helpWidth:G}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let E=this._getOutputContext($),X={error:E.error,write:E.write,command:this};this._getCommandAndAncestors().reverse().forEach((A)=>A.emit("beforeAllHelp",X)),this.emit("beforeHelp",X);let G=this.helpInformation({error:E.error});if(w){if(G=w(G),typeof G!=="string"&&!Buffer.isBuffer(G))throw Error("outputHelp callback must return a string or a Buffer")}if(E.write(G),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",X),this._getCommandAndAncestors().forEach((A)=>A.emit("afterAllHelp",X))}helpOption($,w){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",w=w??"display help for command",this._helpOption=this.createOption($,w),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let w=Number(K0.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let E=["beforeAll","before","after","afterAll"];if(!E.includes($))throw Error(`Unexpected value for position to addHelpText.
28
+ Expecting one of '${E.join("', '")}'`);let X=`${$}Help`;return this.on(X,(G)=>{let A;if(typeof w==="function")A=w({error:G.error,command:G.command});else A=w;if(A)G.write(`${A}
29
+ `)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((X)=>w.is(X)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function L5($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let E,X="127.0.0.1",G="9229",A;if((A=w.match(/^(--inspect(-brk)?)$/))!==null)E=A[1];else if((A=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(E=A[1],/^\d+$/.test(A[3]))G=A[3];else X=A[3];else if((A=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)E=A[1],X=A[3],G=A[4];if(E&&G!=="0")return`${E}=${X}:${parseInt(G)+1}`;return w})}function gO(){if(K0.env.NO_COLOR||K0.env.FORCE_COLOR==="0"||K0.env.FORCE_COLOR==="false")return!1;if(K0.env.FORCE_COLOR||K0.env.CLICOLOR_FORCE!==void 0)return!0;return}uq.Command=uO;uq.useColor=gO});var R5=_((tq)=>{var{Argument:j5}=zN(),{Command:nO}=F5(),{CommanderError:cq,InvalidArgumentError:M5}=MG(),{Help:rq}=fO(),{Option:T5}=vO();tq.program=new nO;tq.createCommand=($)=>new nO($);tq.createOption=($,w)=>new T5($,w);tq.createArgument=($,w)=>new j5($,w);tq.Command=nO;tq.Option=T5;tq.Argument=j5;tq.Help=rq;tq.CommanderError=cq;tq.InvalidArgumentError=M5;tq.InvalidOptionArgumentError=M5});function IN($,w,E,X){if(B5[$]<B5[XS])return;let G=new Date().toISOString(),N=`${ES[$]}[${$.toUpperCase()}]\x1B[0m ${G} [${w}]`;if(X!==void 0)console.error(`${N} ${E}`,X);else console.error(`${N} ${E}`)}function B0($){return{debug:(w,E)=>IN("debug",$,w,E),info:(w,E)=>IN("info",$,w,E),warn:(w,E)=>IN("warn",$,w,E),error:(w,E)=>IN("error",$,w,E)}}var B5,ES,XS;var z$=T(()=>{B5={debug:0,info:1,warn:2,error:3},ES={debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},XS=process.env.ORC_LOG_LEVEL??"info"});import{randomBytes as GS}from"crypto";function DS($,w){let E="";for(let X=w-1;X>=0;X--){let G=$%hO;E=cO[G]+E,$=Math.floor($/hO)}return E}function OS($){let w=GS($),E="";for(let X=0;X<$;X++)E+=cO[(w[X]??0)%hO];return E}function r(){return DS(Date.now(),AS)+OS(NS)}var cO="0123456789ABCDEFGHJKMNPQRSTVWXYZ",hO,AS=10,NS=16;var B$=T(()=>{hO=cO.length});function b($,w){if(!$||typeof $!=="object")return!1;if($ instanceof w)return!0;if(!Object.prototype.hasOwnProperty.call(w,K))throw Error(`Class "${w.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let E=Object.getPrototypeOf($).constructor;if(E)while(E){if(K in E&&E[K]===w[K])return!0;E=Object.getPrototypeOf(E)}return!1}var K;var E0=T(()=>{K=Symbol.for("drizzle:entityKind")});var I5,rO,tO;var QN=T(()=>{E0();I5=class I5{static[K]="ConsoleLogWriter";write($){console.log($)}};rO=class rO{static[K]="DefaultLogger";writer;constructor($){this.writer=$?.writer??new I5}logQuery($,w){let E=w.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),X=E.length?` -- params: [${E.join(", ")}]`:"";this.writer.write(`Query: ${$}${X}`)}};tO=class tO{static[K]="NoopLogger";logQuery(){}}});var Gw;var TG=T(()=>{Gw=Symbol.for("drizzle:Name")});function xE($){return $[Gw]}function Y1($){return`${$[KN]??"public"}.${$[Gw]}`}var KN,VN,Q5,oO,mO,RG,K5,WS,y;var u$=T(()=>{E0();TG();KN=Symbol.for("drizzle:Schema"),VN=Symbol.for("drizzle:Columns"),Q5=Symbol.for("drizzle:ExtraConfigColumns"),oO=Symbol.for("drizzle:OriginalName"),mO=Symbol.for("drizzle:BaseName"),RG=Symbol.for("drizzle:IsAlias"),K5=Symbol.for("drizzle:ExtraConfigBuilder"),WS=Symbol.for("drizzle:IsDrizzleTable");y=class y{static[K]="Table";static Symbol={Name:Gw,Schema:KN,OriginalName:oO,Columns:VN,ExtraConfigColumns:Q5,BaseName:mO,IsAlias:RG,ExtraConfigBuilder:K5};[Gw];[oO];[KN];[VN];[Q5];[mO];[RG]=!1;[WS]=!0;[K5]=void 0;constructor($,w,E){this[Gw]=this[oO]=$,this[KN]=w,this[mO]=E}}});var P0;var kw=T(()=>{E0();P0=class P0{constructor($,w){this.table=$,this.config=w,this.name=w.name,this.keyAsName=w.keyAsName,this.notNull=w.notNull,this.default=w.default,this.defaultFn=w.defaultFn,this.onUpdateFn=w.onUpdateFn,this.hasDefault=w.hasDefault,this.primary=w.primaryKey,this.isUnique=w.isUnique,this.uniqueName=w.uniqueName,this.uniqueType=w.uniqueType,this.dataType=w.dataType,this.columnType=w.columnType,this.generated=w.generated,this.generatedIdentity=w.generatedIdentity}static[K]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var iO;var pO=T(()=>{E0();iO=class iO{static[K]="ColumnBuilder";config;constructor($,w,E){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:w,columnType:E,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}});function V5($,...w){return $(...w)}var P5=()=>{};function q5($,w){return`${$[Gw]}_${w.join("_")}_unique`}var S5=T(()=>{TG()});var PN,JS;var k5=T(()=>{kw();E0();S5();PN=class PN extends P0{constructor($,w){if(!w.uniqueName)w.uniqueName=q5($,[w.name]);super($,w);this.table=$}static[K]="PgColumn"};JS=class JS extends PN{static[K]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}});function _5($){return!!$&&typeof $==="function"&&b5 in $&&$[b5]===!0}var b5,US;var Z5=T(()=>{E0();k5();b5=Symbol.for("drizzle:isPgEnum");US=class US extends PN{static[K]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,w){super($,w);this.enum=w.enum}getSQLType(){return this.enum.enumName}}});var H$,zG;var pw=T(()=>{E0();H$=class H${static[K]="Subquery";constructor($,w,E,X=!1){this._={brand:"Subquery",sql:$,selectedFields:w,alias:E,isWith:X}}};zG=class zG extends H${static[K]="WithSubquery"}});var C5="0.41.0";var f5=()=>{};var dO,lO,v5;var x5=T(()=>{P5();f5();v5={startActiveSpan($,w){if(!dO)return w();if(!lO)lO=dO.trace.getTracer("drizzle-orm",C5);return V5((E,X)=>X.startActiveSpan($,(G)=>{try{return w(G)}catch(A){throw G.setStatus({code:E.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{G.end()}}),dO,lO)}}});var a0;var HE=T(()=>{a0=Symbol.for("drizzle:ViewBaseConfig")});function sO($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function YS($){let w={sql:"",params:[]};for(let E of $)if(w.sql+=E.sql,w.params.push(...E.params),E.typings?.length){if(!w.typings)w.typings=[];w.typings.push(...E.typings)}return w}function y5($){return typeof $==="object"&&$!==null&&"mapToDriverValue"in $&&typeof $.mapToDriverValue==="function"}function z($,...w){let E=[];if(w.length>0||$.length>0&&$[0]!=="")E.push(new O$($[0]));for(let[X,G]of w.entries())E.push(G,new O$($[X+1]));return new h(E)}function BG($,w){return $.map((E)=>{if(b(E,yE)){if(!(E.name in w))throw Error(`No value for placeholder "${E.name}" was provided`);return w[E.name]}if(b(E,Aw)&&b(E.value,yE)){if(!(E.value.name in w))throw Error(`No value for placeholder "${E.value.name}" was provided`);return E.encoder.mapToDriverValue(w[E.value.name])}return E})}var O$,h,qN,g5,u5,ei,Aw,yE,HS,Uw;var Z$=T(()=>{E0();Z5();pw();x5();HE();kw();u$();O$=class O${static[K]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new h([this])}};h=class h{constructor($){this.queryChunks=$}static[K]="SQL";decoder=g5;shouldInlineParams=!1;append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return v5.startActiveSpan("drizzle.buildSQL",(w)=>{let E=this.buildQueryFromSourceParams(this.queryChunks,$);return w?.setAttributes({"drizzle.query.text":E.sql,"drizzle.query.params":JSON.stringify(E.params)}),E})}buildQueryFromSourceParams($,w){let E=Object.assign({},w,{inlineParams:w.inlineParams||this.shouldInlineParams,paramStartIndex:w.paramStartIndex||{value:0}}),{casing:X,escapeName:G,escapeParam:A,prepareTyping:N,inlineParams:D,paramStartIndex:O}=E;return YS($.map((W)=>{if(b(W,O$))return{sql:W.value.join(""),params:[]};if(b(W,qN))return{sql:G(W.value),params:[]};if(W===void 0)return{sql:"",params:[]};if(Array.isArray(W)){let J=[new O$("(")];for(let[Y,H]of W.entries())if(J.push(H),Y<W.length-1)J.push(new O$(", "));return J.push(new O$(")")),this.buildQueryFromSourceParams(J,E)}if(b(W,h))return this.buildQueryFromSourceParams(W.queryChunks,{...E,inlineParams:D||W.shouldInlineParams});if(b(W,y)){let J=W[y.Symbol.Schema],Y=W[y.Symbol.Name];return{sql:J===void 0||W[RG]?G(Y):G(J)+"."+G(Y),params:[]}}if(b(W,P0)){let J=X.getColumnCasing(W);if(w.invokeSource==="indexes")return{sql:G(J),params:[]};let Y=W.table[y.Symbol.Schema];return{sql:W.table[RG]||Y===void 0?G(W.table[y.Symbol.Name])+"."+G(J):G(Y)+"."+G(W.table[y.Symbol.Name])+"."+G(J),params:[]}}if(b(W,Uw)){let J=W[a0].schema,Y=W[a0].name;return{sql:J===void 0||W[a0].isAlias?G(Y):G(J)+"."+G(Y),params:[]}}if(b(W,Aw)){if(b(W.value,yE))return{sql:A(O.value++,W),params:[W],typings:["none"]};let J=W.value===null?null:W.encoder.mapToDriverValue(W.value);if(b(J,h))return this.buildQueryFromSourceParams([J],E);if(D)return{sql:this.mapInlineParam(J,E),params:[]};let Y=["none"];if(N)Y=[N(W.encoder)];return{sql:A(O.value++,J),params:[J],typings:Y}}if(b(W,yE))return{sql:A(O.value++,W),params:[W],typings:["none"]};if(b(W,h.Aliased)&&W.fieldAlias!==void 0)return{sql:G(W.fieldAlias),params:[]};if(b(W,H$)){if(W._.isWith)return{sql:G(W._.alias),params:[]};return this.buildQueryFromSourceParams([new O$("("),W._.sql,new O$(") "),new qN(W._.alias)],E)}if(_5(W)){if(W.schema)return{sql:G(W.schema)+"."+G(W.enumName),params:[]};return{sql:G(W.enumName),params:[]}}if(sO(W)){if(W.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([W.getSQL()],E);return this.buildQueryFromSourceParams([new O$("("),W.getSQL(),new O$(")")],E)}if(D)return{sql:this.mapInlineParam(W,E),params:[]};return{sql:A(O.value++,W),params:[W],typings:["none"]}}))}mapInlineParam($,{escapeString:w}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return w($);if(typeof $==="object"){let E=$.toString();if(E==="[object Object]")return w(JSON.stringify($));return w(E)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new h.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}};qN=class qN{constructor($){this.value=$}static[K]="Name";brand;getSQL(){return new h([this])}};g5={mapFromDriverValue:($)=>$},u5={mapToDriverValue:($)=>$},ei={...g5,...u5};Aw=class Aw{constructor($,w=u5){this.value=$,this.encoder=w}static[K]="Param";brand;getSQL(){return new h([this])}};(($)=>{function w(){return new h([])}$.empty=w;function E(O){return new h(O)}$.fromList=E;function X(O){return new h([new O$(O)])}$.raw=X;function G(O,W){let J=[];for(let[Y,H]of O.entries()){if(Y>0&&W!==void 0)J.push(W);J.push(H)}return new h(J)}$.join=G;function A(O){return new qN(O)}$.identifier=A;function N(O){return new yE(O)}$.placeholder=N;function D(O,W){return new Aw(O,W)}$.param=D})(z||(z={}));(($)=>{class w{constructor(E,X){this.sql=E,this.fieldAlias=X}static[K]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new w(this.sql,this.fieldAlias)}}$.Aliased=w})(h||(h={}));yE=class yE{constructor($){this.name=$}static[K]="Placeholder";getSQL(){return new h([this])}};HS=Symbol.for("drizzle:IsDrizzleView");Uw=class Uw{static[K]="View";[a0];[HS]=!0;constructor({name:$,schema:w,selectedFields:E,query:X}){this[a0]={name:$,originalName:$,schema:w,selectedFields:E,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new h([this])}};P0.prototype.getSQL=function(){return new h([this])};y.prototype.getSQL=function(){return new h([this])};H$.prototype.getSQL=function(){return new h([this])}});function aO($,w,E){let X={},G=$.reduce((A,{path:N,field:D},O)=>{let W;if(b(D,P0))W=D;else if(b(D,h))W=D.decoder;else W=D.sql.decoder;let J=A;for(let[Y,H]of N.entries())if(Y<N.length-1){if(!(H in J))J[H]={};J=J[H]}else{let L=w[O],F=J[H]=L===null?null:W.mapFromDriverValue(L);if(E&&b(D,P0)&&N.length===2){let j=N[0];if(!(j in X))X[j]=F===null?xE(D.table):!1;else if(typeof X[j]==="string"&&X[j]!==xE(D.table))X[j]=!1}}return A},{});if(E&&Object.keys(X).length>0){for(let[A,N]of Object.entries(X))if(typeof N==="string"&&!E[N])G[A]=null}return G}function Yw($,w){return Object.entries($).reduce((E,[X,G])=>{if(typeof X!=="string")return E;let A=w?[...w,X]:[X];if(b(G,P0)||b(G,h)||b(G,h.Aliased))E.push({path:A,field:G});else if(b(G,y))E.push(...Yw(G[y.Symbol.Columns],A));else E.push(...Yw(G,A));return E},[])}function IG($,w){let E=Object.keys($),X=Object.keys(w);if(E.length!==X.length)return!1;for(let[G,A]of E.entries())if(A!==X[G])return!1;return!0}function SN($,w){let E=Object.entries(w).filter(([,X])=>X!==void 0).map(([X,G])=>{if(b(G,h)||b(G,P0))return[X,G];else return[X,new Aw(G,$[y.Symbol.Columns][X])]});if(E.length===0)throw Error("No values to set");return Object.fromEntries(E)}function n5($,w){for(let E of w)for(let X of Object.getOwnPropertyNames(E.prototype)){if(X==="constructor")continue;Object.defineProperty($.prototype,X,Object.getOwnPropertyDescriptor(E.prototype,X)||Object.create(null))}}function h5($){return $[y.Symbol.Columns]}function QG($){return b($,H$)?$._.alias:b($,Uw)?$[a0].name:b($,h)?void 0:$[y.Symbol.IsAlias]?$[y.Symbol.Name]:$[y.Symbol.BaseName]}function dw($,w){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:w}}function c5($){if(typeof $!=="object"||$===null)return!1;if($.constructor.name!=="Object")return!1;if("logger"in $){let w=typeof $.logger;if(w!=="boolean"&&(w!=="object"||typeof $.logger.logQuery!=="function")&&w!=="undefined")return!1;return!0}if("schema"in $){let w=typeof $.schema;if(w!=="object"&&w!=="undefined")return!1;return!0}if("casing"in $){let w=typeof $.casing;if(w!=="string"&&w!=="undefined")return!1;return!0}if("mode"in $){if($.mode!=="default"||$.mode!=="planetscale"||$.mode!==void 0)return!1;return!0}if("connection"in $){let w=typeof $.connection;if(w!=="string"&&w!=="object"&&w!=="undefined")return!1;return!0}if("client"in $){let w=typeof $.client;if(w!=="object"&&w!=="function"&&w!=="undefined")return!1;return!0}if(Object.keys($).length===0)return!0;return!1}var d$=T(()=>{kw();E0();Z$();pw();u$();HE()});var r5,t5,eO;var o5=T(()=>{E0();u$();r5=Symbol.for("drizzle:PgInlineForeignKeys"),t5=Symbol.for("drizzle:EnableRLS");eO=class eO extends y{static[K]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:r5,EnableRLS:t5});[r5]=[];[t5]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}});var $W,m5;var i5=T(()=>{E0();o5();$W=class $W{static[K]="PgPrimaryKeyBuilder";columns;name;constructor($,w){this.columns=$,this.name=w}build($){return new m5($,this.columns,this.name)}};m5=class m5{constructor($,w,E){this.table=$,this.columns=w,this.name=E}static[K]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[eO.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}});function l$($,w){if(y5(w)&&!sO($)&&!b($,Aw)&&!b($,yE)&&!b($,P0)&&!b($,y)&&!b($,Uw))return new Aw($,w);return $}function _0(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new O$("("),z.join(w,new O$(" and ")),new O$(")")])}function kN(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new O$("("),z.join(w,new O$(" or ")),new O$(")")])}function d5($){return z`not ${$}`}function bN($,w){if(Array.isArray(w)){if(w.length===0)return z`false`;return z`${$} in ${w.map((E)=>l$(E,$))}`}return z`${$} in ${l$(w,$)}`}function $Y($,w){if(Array.isArray(w)){if(w.length===0)return z`true`;return z`${$} not in ${w.map((E)=>l$(E,$))}`}return z`${$} not in ${l$(w,$)}`}function wY($){return z`${$} is null`}function EY($){return z`${$} is not null`}function XY($){return z`exists ${$}`}function GY($){return z`not exists ${$}`}function AY($,w,E){return z`${$} between ${l$(w,$)} and ${l$(E,$)}`}function NY($,w,E){return z`${$} not between ${l$(w,$)} and ${l$(E,$)}`}function DY($,w){return z`${$} like ${w}`}function OY($,w){return z`${$} not like ${w}`}function WY($,w){return z`${$} ilike ${w}`}function JY($,w){return z`${$} not ilike ${w}`}var V=($,w)=>{return z`${$} = ${l$(w,$)}`},p5=($,w)=>{return z`${$} <> ${l$(w,$)}`},l5=($,w)=>{return z`${$} > ${l$(w,$)}`},s5=($,w)=>{return z`${$} >= ${l$(w,$)}`},a5=($,w)=>{return z`${$} < ${l$(w,$)}`},e5=($,w)=>{return z`${$} <= ${l$(w,$)}`};var UY=T(()=>{kw();E0();u$();Z$()});function _N($){return z`${$} asc`}function r0($){return z`${$} desc`}var YY=T(()=>{Z$()});var ZN=T(()=>{UY();YY()});function LY(){return{and:_0,between:AY,eq:V,exists:XY,gt:l5,gte:s5,ilike:WY,inArray:bN,isNull:wY,isNotNull:EY,like:DY,lt:a5,lte:e5,ne:p5,not:d5,notBetween:NY,notExists:GY,notLike:OY,notIlike:JY,notInArray:$Y,or:kN,sql:z}}function FY(){return{sql:z,asc:_N,desc:r0}}function jY($,w){if(Object.keys($).length===1&&"default"in $&&!b($.default,y))$=$.default;let E={},X={},G={};for(let[A,N]of Object.entries($))if(b(N,y)){let D=Y1(N),O=X[D];E[D]=A,G[A]={tsName:A,dbName:N[y.Symbol.Name],schema:N[y.Symbol.Schema],columns:N[y.Symbol.Columns],relations:O?.relations??{},primaryKey:O?.primaryKey??[]};for(let J of Object.values(N[y.Symbol.Columns]))if(J.primary)G[A].primaryKey.push(J);let W=N[y.Symbol.ExtraConfigBuilder]?.(N[y.Symbol.ExtraConfigColumns]);if(W){for(let J of Object.values(W))if(b(J,$W))G[A].primaryKey.push(...J.columns)}}else if(b(N,HY)){let D=Y1(N.table),O=E[D],W=N.config(w(N.table)),J;for(let[Y,H]of Object.entries(W))if(O){let L=G[O];if(L.relations[Y]=H,J)L.primaryKey.push(...J)}else{if(!(D in X))X[D]={relations:{},primaryKey:J};X[D].relations[Y]=H}}return{tables:G,tableNamesMap:E}}function LS($){return function(E,X){return new gE($,E,X,X?.fields.reduce((G,A)=>G&&A.notNull,!0)??!1)}}function FS($){return function(E,X){return new KG($,E,X)}}function MY($,w,E){if(b(E,gE)&&E.config)return{fields:E.config.fields,references:E.config.references};let X=w[Y1(E.referencedTable)];if(!X)throw Error(`Table "${E.referencedTable[y.Symbol.Name]}" not found in schema`);let G=$[X];if(!G)throw Error(`Table "${X}" not found in schema`);let A=E.sourceTable,N=w[Y1(A)];if(!N)throw Error(`Table "${A[y.Symbol.Name]}" not found in schema`);let D=[];for(let O of Object.values(G.relations))if(E.relationName&&E!==O&&O.relationName===E.relationName||!E.relationName&&O.referencedTable===E.sourceTable)D.push(O);if(D.length>1)throw E.relationName?Error(`There are multiple relations with name "${E.relationName}" in table "${X}"`):Error(`There are multiple relations between "${X}" and "${E.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(D[0]&&b(D[0],gE)&&D[0].config)return{fields:D[0].config.references,references:D[0].config.fields};throw Error(`There is not enough information to infer relation "${N}.${E.fieldName}"`)}function TY($){return{one:LS($),many:FS($)}}function CN($,w,E,X,G=(A)=>A){let A={};for(let[N,D]of X.entries())if(D.isJson){let O=w.relations[D.tsKey],W=E[N],J=typeof W==="string"?JSON.parse(W):W;A[D.tsKey]=b(O,gE)?J&&CN($,$[D.relationTableTsKey],J,D.selection,G):J.map((Y)=>CN($,$[D.relationTableTsKey],Y,D.selection,G))}else{let O=G(E[N]),W=D.field,J;if(b(W,P0))J=W;else if(b(W,h))J=W.decoder;else J=W.sql.decoder;A[D.tsKey]=O===null?null:J.mapFromDriverValue(O)}return A}var wW,HY,gE,KG;var VG=T(()=>{u$();kw();E0();i5();ZN();Z$();wW=class wW{constructor($,w,E){this.sourceTable=$,this.referencedTable=w,this.relationName=E,this.referencedTableName=w[y.Symbol.Name]}static[K]="Relation";referencedTableName;fieldName};HY=class HY{constructor($,w){this.table=$,this.config=w}static[K]="Relations"};gE=class gE extends wW{constructor($,w,E,X){super($,w,E?.relationName);this.config=E,this.isNullable=X}static[K]="One";withFieldName($){let w=new gE(this.sourceTable,this.referencedTable,this.config,this.isNullable);return w.fieldName=$,w}};KG=class KG extends wW{constructor($,w,E){super($,w,E?.relationName);this.config=E}static[K]="Many";withFieldName($){let w=new KG(this.sourceTable,this.referencedTable,this.config);return w.fieldName=$,w}}});function fN($,w){return new Proxy($,new PG(w,!1))}function lw($,w){return new Proxy($,new e1(new Proxy($.table,new PG(w,!1))))}function EW($,w){return new h.Aliased(qG($.sql,w),$.fieldAlias)}function qG($,w){return z.join($.queryChunks.map((E)=>{if(b(E,P0))return lw(E,w);if(b(E,h))return qG(E,w);if(b(E,h.Aliased))return EW(E,w);return E}))}var e1,PG;var vN=T(()=>{kw();E0();Z$();u$();HE();e1=class e1{constructor($){this.table=$}static[K]="ColumnAliasProxyHandler";get($,w){if(w==="table")return this.table;return $[w]}};PG=class PG{constructor($,w){this.alias=$,this.replaceOriginalName=w}static[K]="TableAliasProxyHandler";get($,w){if(w===y.Symbol.IsAlias)return!0;if(w===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&w===y.Symbol.OriginalName)return this.alias;if(w===a0)return{...$[a0],name:this.alias,isAlias:!0};if(w===y.Symbol.Columns){let X=$[y.Symbol.Columns];if(!X)return X;let G={};return Object.keys(X).map((A)=>{G[A]=new Proxy(X[A],new e1(new Proxy($,this)))}),G}let E=$[w];if(b(E,P0))return new Proxy(E,new e1(new Proxy($,this)));return E}}});var N$;var $X=T(()=>{vN();kw();E0();Z$();pw();HE();N$=class N${static[K]="SelectionProxyHandler";config;constructor($){this.config={...$}}get($,w){if(w==="_")return{...$._,selectedFields:new Proxy($._.selectedFields,this)};if(w===a0)return{...$[a0],selectedFields:new Proxy($[a0].selectedFields,this)};if(typeof w==="symbol")return $[w];let X=(b($,H$)?$._.selectedFields:b($,Uw)?$[a0].selectedFields:$)[w];if(b(X,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!X.isSelectionField)return X.sql;let G=X.clone();return G.isSelectionField=!0,G}if(b(X,h)){if(this.config.sqlBehavior==="sql")return X;throw Error(`You tried to reference "${w}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(b(X,P0)){if(this.config.alias)return new Proxy(X,new e1(new Proxy(X.table,new PG(this.config.alias,this.config.replaceOriginalName??!1))));return X}if(typeof X!=="object"||X===null)return X;return new Proxy(X,new N$(this.config))}}});var n$;var LE=T(()=>{E0();n$=class n${static[K]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}then($,w){return this.execute().then($,w)}}});var XW,RY;var GW=T(()=>{E0();TG();XW=class XW{static[K]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,w){if(this.reference=()=>{let{name:E,columns:X,foreignColumns:G}=$();return{name:E,columns:X,foreignTable:G[0].table,foreignColumns:G}},w)this._onUpdate=w.onUpdate,this._onDelete=w.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new RY($,this)}};RY=class RY{constructor($,w){this.table=$,this.reference=w.reference,this.onUpdate=w._onUpdate,this.onDelete=w._onDelete}static[K]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:w,foreignColumns:E}=this.reference(),X=w.map((N)=>N.name),G=E.map((N)=>N.name),A=[this.table[Gw],...X,E[0].table[Gw],...G];return $??`${A.join("_")}_fk`}}});function zY($,w){return`${$[Gw]}_${w.join("_")}_unique`}var AW=T(()=>{TG()});var L$,X$;var uE=T(()=>{pO();kw();E0();GW();AW();L$=class L$ extends iO{static[K]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,w={}){return this.foreignKeyConfigs.push({ref:$,actions:w}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,w){return this.config.generated={as:$,type:"always",mode:w?.mode??"virtual"},this}buildForeignKeys($,w){return this.foreignKeyConfigs.map(({ref:E,actions:X})=>{return((G,A)=>{let N=new XW(()=>{let D=G();return{columns:[$],foreignColumns:[D]}});if(A.onUpdate)N.onUpdate(A.onUpdate);if(A.onDelete)N.onDelete(A.onDelete);return N.build(w)})(E,X)})}};X$=class X$ extends P0{constructor($,w){if(!w.uniqueName)w.uniqueName=zY($,[w.name]);super($,w);this.table=$}static[K]="SQLiteColumn"}});function qY($,w){let{name:E,config:X}=dw($,w);if(X?.mode==="json")return new QY(E);if(X?.mode==="bigint")return new BY(E);return new VY(E)}var BY,IY,QY,KY,VY,PY;var NW=T(()=>{E0();d$();uE();BY=class BY extends L${static[K]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new IY($,this.config)}};IY=class IY extends X${static[K]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return BigInt($.toString());if($ instanceof ArrayBuffer)return BigInt(new TextDecoder().decode($));return BigInt(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from($.toString())}};QY=class QY extends L${static[K]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new KY($,this.config)}};KY=class KY extends X${static[K]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return JSON.parse($.toString());if($ instanceof ArrayBuffer)return JSON.parse(new TextDecoder().decode($));return JSON.parse(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}};VY=class VY extends L${static[K]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new PY($,this.config)}};PY=class PY extends X${static[K]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}});function bY($){return(w,E)=>{let{name:X,config:G}=dw(w,E);return new SY(X,G,$)}}var SY,kY;var DW=T(()=>{E0();d$();uE();SY=class SY extends L${static[K]="SQLiteCustomColumnBuilder";constructor($,w,E){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=w,this.config.customTypeParams=E}build($){return new kY($,this.config)}};kY=class kY extends X${static[K]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,w){super($,w);this.sqlName=w.customTypeParams.dataType(w.fieldConfig),this.mapTo=w.customTypeParams.toDriver,this.mapFrom=w.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}});function d($,w){let{name:E,config:X}=dw($,w);if(X?.mode==="timestamp"||X?.mode==="timestamp_ms")return new CY(E,X.mode);if(X?.mode==="boolean")return new vY(E,X.mode);return new _Y(E)}var xN,yN,_Y,ZY,CY,fY,vY,xY;var OW=T(()=>{E0();Z$();d$();uE();xN=class xN extends L${static[K]="SQLiteBaseIntegerBuilder";constructor($,w,E){super($,w,E);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};yN=class yN extends X${static[K]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};_Y=class _Y extends xN{static[K]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new ZY($,this.config)}};ZY=class ZY extends yN{static[K]="SQLiteInteger"};CY=class CY extends xN{static[K]="SQLiteTimestampBuilder";constructor($,w){super($,"date","SQLiteTimestamp");this.config.mode=w}defaultNow(){return this.default(z`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new fY($,this.config)}};fY=class fY extends yN{static[K]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let w=$.getTime();if(this.config.mode==="timestamp")return Math.floor(w/1000);return w}};vY=class vY extends xN{static[K]="SQLiteBooleanBuilder";constructor($,w){super($,"boolean","SQLiteBoolean");this.config.mode=w}build($){return new xY($,this.config)}};xY=class xY extends yN{static[K]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}});function rY($,w){let{name:E,config:X}=dw($,w),G=X?.mode;return G==="number"?new uY(E):G==="bigint"?new hY(E):new yY(E)}var yY,gY,uY,nY,hY,cY;var WW=T(()=>{E0();d$();uE();yY=class yY extends L${static[K]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new gY($,this.config)}};gY=class gY extends X${static[K]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}};uY=class uY extends L${static[K]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new nY($,this.config)}};nY=class nY extends X${static[K]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}};hY=class hY extends L${static[K]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new cY($,this.config)}};cY=class cY extends X${static[K]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function mY($){return new tY($??"")}var tY,oY;var JW=T(()=>{E0();uE();tY=class tY extends L${static[K]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new oY($,this.config)}};oY=class oY extends X${static[K]="SQLiteReal";getSQLType(){return"real"}}});function q($,w={}){let{name:E,config:X}=dw($,w);if(X.mode==="json")return new dY(E);return new iY(E,X)}var iY,pY,dY,lY;var UW=T(()=>{E0();d$();uE();iY=class iY extends L${static[K]="SQLiteTextBuilder";constructor($,w){super($,"string","SQLiteText");this.config.enumValues=w.enum,this.config.length=w.length}build($){return new pY($,this.config)}};pY=class pY extends X${static[K]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,w){super($,w)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};dY=class dY extends L${static[K]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new lY($,this.config)}};lY=class lY extends X${static[K]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}});function sY(){return{blob:qY,customType:bY,integer:d,numeric:rY,real:mY,text:q}}var aY=T(()=>{NW();DW();OW();WW();JW();UW()});function jS($,w,E,X,G=$){let A=new C$($,X,G),N=typeof w==="function"?w(sY()):w,D=Object.fromEntries(Object.entries(N).map(([W,J])=>{let Y=J;Y.setName(W);let H=Y.build(A);return A[YW].push(...Y.buildForeignKeys(H,A)),[W,H]})),O=Object.assign(A,D);if(O[y.Symbol.Columns]=D,O[y.Symbol.ExtraConfigColumns]=D,E)O[C$.Symbol.ExtraConfigBuilder]=E;return O}var YW,C$,I$=($,w,E)=>{return jS($,w,E)};var wX=T(()=>{E0();u$();aY();YW=Symbol.for("drizzle:SQLiteInlineForeignKeys");C$=class C$ extends y{static[K]="SQLiteTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:YW});[y.Symbol.Columns];[YW]=[];[y.Symbol.ExtraConfigBuilder]=void 0}});var gN;var eY=T(()=>{E0();LE();$X();wX();u$();d$();gN=class gN extends n${constructor($,w,E,X){super();this.table=$,this.session=w,this.dialect=E,this.config={table:$,withList:X}}static[K]="SQLiteDelete";config;where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new N$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.table[C$.Symbol.Columns]){return this.config.returning=Yw($),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute($){return this._prepare().execute($)}$dynamic(){return this}}});function MS($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((E)=>E.toLowerCase()).join("_")}function TS($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((E,X,G)=>{let A=G===0?X.toLowerCase():`${X[0].toUpperCase()}${X.slice(1)}`;return E+A},"")}function RS($){return $}var HW;var $7=T(()=>{E0();u$();HW=class HW{static[K]="CasingCache";cache={};cachedTables={};convert;constructor($){this.convert=$==="snake_case"?MS:$==="camelCase"?TS:RS}getColumnCasing($){if(!$.keyAsName)return $.name;let w=$.table[y.Symbol.Schema]??"public",E=$.table[y.Symbol.OriginalName],X=`${w}.${E}.${$.name}`;if(!this.cache[X])this.cacheTable($.table);return this.cache[X]}cacheTable($){let w=$[y.Symbol.Schema]??"public",E=$[y.Symbol.OriginalName],X=`${w}.${E}`;if(!this.cachedTables[X]){for(let G of Object.values($[y.Symbol.Columns])){let A=`${X}.${G.name}`;this.cache[A]=this.convert(G.name)}this.cachedTables[X]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var EX,LW;var uN=T(()=>{E0();EX=class EX extends Error{static[K]="DrizzleError";constructor({message:$,cause:w}){super($);this.name="DrizzleError",this.cause=w}};LW=class LW extends EX{static[K]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var w7=()=>{};var E7=()=>{};var X7=T(()=>{w7();E7()});var FW=T(()=>{ZN();X7();Z$()});var jW=T(()=>{NW();uE();DW();OW();WW();JW();UW()});var H1;var nN=T(()=>{E0();Z$();H1=class H1 extends Uw{static[K]="SQLiteViewBase"}});var SG,kG;var hN=T(()=>{vN();$7();kw();E0();uN();VG();FW();Z$();jW();wX();pw();u$();d$();HE();nN();SG=class SG{static[K]="SQLiteDialect";casing;constructor($){this.casing=new HW($?.casing)}escapeName($){return`"${$}"`}escapeParam($){return"?"}escapeString($){return`'${$.replace(/'/g,"''")}'`}buildWithCTE($){if(!$?.length)return;let w=[z`with `];for(let[E,X]of $.entries())if(w.push(z`${z.identifier(X._.alias)} as (${X._.sql})`),E<$.length-1)w.push(z`, `);return w.push(z` `),z.join(w)}buildDeleteQuery({table:$,where:w,returning:E,withList:X,limit:G,orderBy:A}){let N=this.buildWithCTE(X),D=E?z` returning ${this.buildSelection(E,{isSingleTable:!0})}`:void 0,O=w?z` where ${w}`:void 0,W=this.buildOrderBy(A),J=this.buildLimit(G);return z`${N}delete from ${$}${O}${D}${W}${J}`}buildUpdateSet($,w){let E=$[y.Symbol.Columns],X=Object.keys(E).filter((A)=>w[A]!==void 0||E[A]?.onUpdateFn!==void 0),G=X.length;return z.join(X.flatMap((A,N)=>{let D=E[A],O=w[A]??z.param(D.onUpdateFn(),D),W=z`${z.identifier(this.casing.getColumnCasing(D))} = ${O}`;if(N<G-1)return[W,z.raw(", ")];return[W]}))}buildUpdateQuery({table:$,set:w,where:E,returning:X,withList:G,joins:A,from:N,limit:D,orderBy:O}){let W=this.buildWithCTE(G),J=this.buildUpdateSet($,w),Y=N&&z.join([z.raw(" from "),this.buildFromTable(N)]),H=this.buildJoins(A),L=X?z` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,F=E?z` where ${E}`:void 0,j=this.buildOrderBy(O),M=this.buildLimit(D);return z`${W}update ${$} set ${J}${Y}${H}${F}${L}${j}${M}`}buildSelection($,{isSingleTable:w=!1}={}){let E=$.length,X=$.flatMap(({field:G},A)=>{let N=[];if(b(G,h.Aliased)&&G.isSelectionField)N.push(z.identifier(G.fieldAlias));else if(b(G,h.Aliased)||b(G,h)){let D=b(G,h.Aliased)?G.sql:G;if(w)N.push(new h(D.queryChunks.map((O)=>{if(b(O,P0))return z.identifier(this.casing.getColumnCasing(O));return O})));else N.push(D);if(b(G,h.Aliased))N.push(z` as ${z.identifier(G.fieldAlias)}`)}else if(b(G,P0)){let D=G.table[y.Symbol.Name];if(G.columnType==="SQLiteNumericBigInt")if(w)N.push(z`cast(${z.identifier(this.casing.getColumnCasing(G))} as text)`);else N.push(z`cast(${z.identifier(D)}.${z.identifier(this.casing.getColumnCasing(G))} as text)`);else if(w)N.push(z.identifier(this.casing.getColumnCasing(G)));else N.push(z`${z.identifier(D)}.${z.identifier(this.casing.getColumnCasing(G))}`)}if(A<E-1)N.push(z`, `);return N});return z.join(X)}buildJoins($){if(!$||$.length===0)return;let w=[];if($)for(let[E,X]of $.entries()){if(E===0)w.push(z` `);let G=X.table;if(b(G,C$)){let A=G[C$.Symbol.Name],N=G[C$.Symbol.Schema],D=G[C$.Symbol.OriginalName],O=A===D?void 0:X.alias;w.push(z`${z.raw(X.joinType)} join ${N?z`${z.identifier(N)}.`:void 0}${z.identifier(D)}${O&&z` ${z.identifier(O)}`} on ${X.on}`)}else w.push(z`${z.raw(X.joinType)} join ${G} on ${X.on}`);if(E<$.length-1)w.push(z` `)}return z.join(w)}buildLimit($){return typeof $==="object"||typeof $==="number"&&$>=0?z` limit ${$}`:void 0}buildOrderBy($){let w=[];if($){for(let[E,X]of $.entries())if(w.push(X),E<$.length-1)w.push(z`, `)}return w.length>0?z` order by ${z.join(w)}`:void 0}buildFromTable($){if(b($,y)&&$[y.Symbol.IsAlias])return z`${z`${z.identifier($[y.Symbol.Schema]??"")}.`.if($[y.Symbol.Schema])}${z.identifier($[y.Symbol.OriginalName])} ${z.identifier($[y.Symbol.Name])}`;return $}buildSelectQuery({withList:$,fields:w,fieldsFlat:E,where:X,having:G,table:A,joins:N,orderBy:D,groupBy:O,limit:W,offset:J,distinct:Y,setOperators:H}){let L=E??Yw(w);for(let V0 of L)if(b(V0.field,P0)&&xE(V0.field.table)!==(b(A,H$)?A._.alias:b(A,H1)?A[a0].name:b(A,h)?void 0:xE(A))&&!((Y$)=>N?.some(({alias:Jw})=>Jw===(Y$[y.Symbol.IsAlias]?xE(Y$):Y$[y.Symbol.BaseName])))(V0.field.table)){let Y$=xE(V0.field.table);throw Error(`Your "${V0.path.join("->")}" field references a column "${Y$}"."${V0.field.name}", but the table "${Y$}" is not part of the query! Did you forget to join it?`)}let F=!N||N.length===0,j=this.buildWithCTE($),M=Y?z` distinct`:void 0,R=this.buildSelection(L,{isSingleTable:F}),B=this.buildFromTable(A),I=this.buildJoins(N),C=X?z` where ${X}`:void 0,v=G?z` having ${G}`:void 0,k=[];if(O){for(let[V0,Y$]of O.entries())if(k.push(Y$),V0<O.length-1)k.push(z`, `)}let n=k.length>0?z` group by ${z.join(k)}`:void 0,H0=this.buildOrderBy(D),b0=this.buildLimit(W),c0=J?z` offset ${J}`:void 0,l0=z`${j}select${M} ${R} from ${B}${I}${C}${n}${v}${H0}${b0}${c0}`;if(H.length>0)return this.buildSetOperations(l0,H);return l0}buildSetOperations($,w){let[E,...X]=w;if(!E)throw Error("Cannot pass undefined values to any set operator");if(X.length===0)return this.buildSetOperationQuery({leftSelect:$,setOperator:E});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:$,setOperator:E}),X)}buildSetOperationQuery({leftSelect:$,setOperator:{type:w,isAll:E,rightSelect:X,limit:G,orderBy:A,offset:N}}){let D=z`${$.getSQL()} `,O=z`${X.getSQL()}`,W;if(A&&A.length>0){let L=[];for(let F of A)if(b(F,X$))L.push(z.identifier(F.name));else if(b(F,h)){for(let j=0;j<F.queryChunks.length;j++){let M=F.queryChunks[j];if(b(M,X$))F.queryChunks[j]=z.identifier(this.casing.getColumnCasing(M))}L.push(z`${F}`)}else L.push(z`${F}`);W=z` order by ${z.join(L,z`, `)}`}let J=typeof G==="object"||typeof G==="number"&&G>=0?z` limit ${G}`:void 0,Y=z.raw(`${w} ${E?"all ":""}`),H=N?z` offset ${N}`:void 0;return z`${D}${Y}${O}${W}${J}${H}`}buildInsertQuery({table:$,values:w,onConflict:E,returning:X,withList:G,select:A}){let N=[],D=$[y.Symbol.Columns],O=Object.entries(D).filter(([F,j])=>!j.shouldDisableInsert()),W=O.map(([,F])=>z.identifier(this.casing.getColumnCasing(F)));if(A){let F=w;if(b(F,h))N.push(F);else N.push(F.getSQL())}else{let F=w;N.push(z.raw("values "));for(let[j,M]of F.entries()){let R=[];for(let[B,I]of O){let C=M[B];if(C===void 0||b(C,Aw)&&C.value===void 0){let v;if(I.default!==null&&I.default!==void 0)v=b(I.default,h)?I.default:z.param(I.default,I);else if(I.defaultFn!==void 0){let k=I.defaultFn();v=b(k,h)?k:z.param(k,I)}else if(!I.default&&I.onUpdateFn!==void 0){let k=I.onUpdateFn();v=b(k,h)?k:z.param(k,I)}else v=z`null`;R.push(v)}else R.push(C)}if(N.push(R),j<F.length-1)N.push(z`, `)}}let J=this.buildWithCTE(G),Y=z.join(N),H=X?z` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,L=E?.length?z.join(E):void 0;return z`${J}insert into ${$} ${W} ${Y}${L}${H}`}sqlToQuery($,w){return $.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:w})}buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:X,tableConfig:G,queryConfig:A,tableAlias:N,nestedQueryRelation:D,joinOn:O}){let W=[],J,Y,H=[],L,F=[];if(A===!0)W=Object.entries(G.columns).map(([R,B])=>({dbKey:B.name,tsKey:R,field:lw(B,N),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let M=Object.fromEntries(Object.entries(G.columns).map(([k,n])=>[k,lw(n,N)]));if(A.where){let k=typeof A.where==="function"?A.where(M,LY()):A.where;L=k&&qG(k,N)}let R=[],B=[];if(A.columns){let k=!1;for(let[n,H0]of Object.entries(A.columns)){if(H0===void 0)continue;if(n in G.columns){if(!k&&H0===!0)k=!0;B.push(n)}}if(B.length>0)B=k?B.filter((n)=>A.columns?.[n]===!0):Object.keys(G.columns).filter((n)=>!B.includes(n))}else B=Object.keys(G.columns);for(let k of B){let n=G.columns[k];R.push({tsKey:k,value:n})}let I=[];if(A.with)I=Object.entries(A.with).filter((k)=>!!k[1]).map(([k,n])=>({tsKey:k,queryConfig:n,relation:G.relations[k]}));let C;if(A.extras){C=typeof A.extras==="function"?A.extras(M,{sql:z}):A.extras;for(let[k,n]of Object.entries(C))R.push({tsKey:k,value:EW(n,N)})}for(let{tsKey:k,value:n}of R)W.push({dbKey:b(n,h.Aliased)?n.fieldAlias:G.columns[k].name,tsKey:k,field:b(n,P0)?lw(n,N):n,relationTableTsKey:void 0,isJson:!1,selection:[]});let v=typeof A.orderBy==="function"?A.orderBy(M,FY()):A.orderBy??[];if(!Array.isArray(v))v=[v];H=v.map((k)=>{if(b(k,P0))return lw(k,N);return qG(k,N)}),J=A.limit,Y=A.offset;for(let{tsKey:k,queryConfig:n,relation:H0}of I){let b0=MY(w,E,H0),c0=Y1(H0.referencedTable),l0=E[c0],V0=`${N}_${k}`,Y$=_0(...b0.fields.map((xV,yV)=>V(lw(b0.references[yV],V0),lw(xV,N)))),Jw=this.buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:$[l0],tableConfig:w[l0],queryConfig:b(H0,gE)?n===!0?{limit:1}:{...n,limit:1}:n,tableAlias:V0,joinOn:Y$,nestedQueryRelation:H0}),vV=z`(${Jw.sql})`.as(k);W.push({dbKey:k,tsKey:k,field:vV,relationTableTsKey:l0,isJson:!0,selection:Jw.selection})}}if(W.length===0)throw new EX({message:`No fields selected for table "${G.tsName}" ("${N}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let j;if(L=_0(O,L),D){let M=z`json_array(${z.join(W.map(({field:I})=>b(I,X$)?z.identifier(this.casing.getColumnCasing(I)):b(I,h.Aliased)?I.sql:I),z`, `)})`;if(b(D,KG))M=z`coalesce(json_group_array(${M}), json_array())`;let R=[{dbKey:"data",tsKey:"data",field:M.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:W}];if(J!==void 0||Y!==void 0||H.length>0)j=this.buildSelectQuery({table:fN(X,N),fields:{},fieldsFlat:[{path:[],field:z.raw("*")}],where:L,limit:J,offset:Y,orderBy:H,setOperators:[]}),L=void 0,J=void 0,Y=void 0,H=void 0;else j=fN(X,N);j=this.buildSelectQuery({table:b(j,C$)?j:new H$(j,{},N),fields:{},fieldsFlat:R.map(({field:I})=>({path:[],field:b(I,P0)?lw(I,N):I})),joins:F,where:L,limit:J,offset:Y,orderBy:H,setOperators:[]})}else j=this.buildSelectQuery({table:fN(X,N),fields:{},fieldsFlat:W.map(({field:M})=>({path:[],field:b(M,P0)?lw(M,N):M})),joins:F,where:L,limit:J,offset:Y,orderBy:H,setOperators:[]});return{tableTsKey:G.tsName,sql:j,selection:W}}};kG=class kG extends SG{static[K]="SQLiteSyncDialect";migrate($,w,E){let X=E===void 0?"__drizzle_migrations":typeof E==="string"?"__drizzle_migrations":E.migrationsTable??"__drizzle_migrations",G=z`
30
+ CREATE TABLE IF NOT EXISTS ${z.identifier(X)} (
31
31
  id SERIAL PRIMARY KEY,
32
32
  hash text NOT NULL,
33
33
  created_at numeric
34
34
  )
35
- `;w.run(G);let A=w.values(T`SELECT id, hash, created_at FROM ${T.identifier(X)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;w.run(T`BEGIN`);try{for(let D of $)if(!A||Number(A[2])<D.folderMillis){for(let N of D.sql)w.run(T.raw(N));w.run(T`INSERT INTO ${T.identifier(X)} ("hash", "created_at") VALUES(${D.hash}, ${D.folderMillis})`)}w.run(T`COMMIT`)}catch(D){throw w.run(T`ROLLBACK`),D}}}});var L8;var s7=R(()=>{E0();L8=class L8{static[K]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function gJ($,w){return(E,X,...G)=>{let J=[X,...G].map((A)=>({type:$,isAll:w,rightSelect:A}));for(let A of J)if(!RG(E.getSelectedFields(),A.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return E.addSetOperators(J)}}var Z1,a7,F8,Y2=()=>({union:H2,unionAll:L2,intersect:F2,except:j2}),H2,L2,F2,j2;var j8=R(()=>{E0();s7();Fw();aE();q$();d1();_$();o$();Lw();xJ();Z1=class Z1{static[K]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor($){this.fields=$.fields,this.session=$.session,this.dialect=$.dialect,this.withList=$.withList,this.distinct=$.distinct}from($){let w=!!this.fields,E;if(this.fields)E=this.fields;else if(b($,Y$))E=Object.fromEntries(Object.keys($._.selectedFields).map((X)=>[X,$[X]]));else if(b($,YE))E=$[s0].selectedFields;else if(b($,h))E={};else E=vU($);return new F8({table:$,fields:E,isPartialSelect:w,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};a7=class a7 extends L8{static[K]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:$,fields:w,isPartialSelect:E,session:X,dialect:G,withList:J,distinct:A}){super();this.config={withList:J,table:$,fields:{...w},distinct:A,setOperators:[]},this.isPartialSelect=E,this.session=X,this.dialect=G,this._={selectedFields:w},this.tableName=zG($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin($){return(w,E)=>{let X=this.tableName,G=zG(w);if(typeof G==="string"&&this.config.joins?.some((J)=>J.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof X==="string")this.config.fields={[X]:this.config.fields};if(typeof G==="string"&&!b(w,h)){let J=b(w,Y$)?w._.selectedFields:b(w,U1)?w[s0].selectedFields:w[y.Symbol.Columns];this.config.fields[G]=J}}if(typeof E==="function")E=E(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:E,table:w,joinType:$,alias:G}),typeof G==="string")switch($){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator($,w){return(E)=>{let X=typeof E==="function"?E(Y2()):E;if(!RG(this.getSelectedFields(),X.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:$,isAll:w,rightSelect:X}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators($){return this.config.setOperators.push(...$),this}where($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=$,this}having($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=$,this}groupBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(w)?w:[w]}else this.config.groupBy=$;return this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=E;else this.config.orderBy=E}else{let w=$;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=w;else this.config.orderBy=w}return this}limit($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=$;else this.config.limit=$;return this}offset($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=$;else this.config.offset=$;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}as($){return new Proxy(new Y$(this.getSQL(),this.config.fields,$),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new A$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};F8=class F8 extends a7{static[K]="SQLiteSelect";_prepare($=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let w=Y1(this.config.fields),E=this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),w,"all",!0);return E.joinsNotNullableMap=this.joinsNotNullableMap,E}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.all()}};_U(F8,[v$]);H2=gJ("union",!1),L2=gJ("union",!0),F2=gJ("intersect",!1),j2=gJ("except",!1)});var PG;var M8=R(()=>{E0();aE();yJ();d1();j8();PG=class PG{static[K]="SQLiteQueryBuilder";dialect;dialectConfig;constructor($){this.dialect=b($,KG)?$:void 0,this.dialectConfig=b($,KG)?void 0:$}$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(E);return new Proxy(new jG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...$){let w=this;function E(G){return new Z1({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$})}function X(G){return new Z1({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$,distinct:!0})}return{select:E,selectDistinct:X}}select($){return new Z1({fields:$??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct($){return new Z1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new VG(this.dialectConfig);return this.dialect}}});var uJ,R8;var e7=R(()=>{E0();Fw();q$();eE();_$();o$();M8();uJ=class uJ{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteInsertBuilder";values($){if($=Array.isArray($)?$:[$],$.length===0)throw Error("values() must be called with at least one value");let w=$.map((E)=>{let X={},G=this.table[y.Symbol.Columns];for(let J of Object.keys(E)){let A=E[J];X[J]=b(A,h)?A:new J1(A,G[J])}return X});return new R8(this.table,w,this.session,this.dialect,this.withList)}select($){let w=typeof $==="function"?$(new PG):$;if(!b(w,h)&&!RG(this.table[BJ],w._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new R8(this.table,w,this.session,this.dialect,this.withList,!0)}};R8=class R8 extends v${constructor($,w,E,X,G,J){super();this.session=E,this.dialect=X,this.config={table:$,values:w,withList:G,select:J}}static[K]="SQLiteInsert";config;returning($=this.config.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}onConflictDoNothing($={}){if(!this.config.onConflict)this.config.onConflict=[];if($.target===void 0)this.config.onConflict.push(T` on conflict do nothing`);else{let w=Array.isArray($.target)?T`${$.target}`:T`${[$.target]}`,E=$.where?T` where ${$.where}`:T``;this.config.onConflict.push(T` on conflict ${w} do nothing${E}`)}return this}onConflictDoUpdate($){if($.where&&($.targetWhere||$.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let w=$.where?T` where ${$.where}`:void 0,E=$.targetWhere?T` where ${$.targetWhere}`:void 0,X=$.setWhere?T` where ${$.setWhere}`:void 0,G=Array.isArray($.target)?T`${$.target}`:T`${[$.target]}`,J=this.dialect.buildUpdateSet(this.config.table,KJ(this.config.table,$.set));return this.config.onConflict.push(T` on conflict ${G}${E} do update set ${J}${w}${X}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var hJ,$Y;var wY=R(()=>{E0();Fw();aE();eE();d1();_$();o$();Lw();xJ();hJ=class hJ{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteUpdateBuilder";set($){return new $Y(this.table,KJ(this.table,$),this.session,this.dialect,this.withList)}};$Y=class $Y extends v${constructor($,w,E,X,G){super();this.session=E,this.dialect=X,this.config={set:w,table:$,withList:G,joins:[]}}static[K]="SQLiteUpdate";config;from($){return this.config.from=$,this}createJoin($){return(w,E)=>{let X=zG(w);if(typeof X==="string"&&this.config.joins.some((G)=>G.alias===X))throw Error(`Alias "${X}" is already used in this query`);if(typeof E==="function"){let G=this.config.from?b(w,S$)?w[y.Symbol.Columns]:b(w,Y$)?w._.selectedFields:b(w,YE)?w[s0].selectedFields:void 0:void 0;E=E(new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:E,table:w,joinType:$,alias:X}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.config.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var z8=R(()=>{o7();e7();M8();j8();wY()});var qG;var EY=R(()=>{E0();q$();qG=class qG extends h{constructor($){super(qG.buildEmbeddedCount($.source,$.filters).queryChunks);this.params=$,this.session=$.session,this.sql=qG.buildCount($.source,$.filters)}sql;static[K]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount($,w){return T`(select count(*) from ${$}${T.raw(" where ").if(w)}${w})`}static buildCount($,w){return T`select count(*) from ${$}${T.raw(" where ").if(w)}${w}`}then($,w){return Promise.resolve(this.session.count(this.sql)).then($,w)}catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}}});var B8,cJ,T8;var XY=R(()=>{E0();Fw();BG();B8=class B8{constructor($,w,E,X,G,J,A,D){this.mode=$,this.fullSchema=w,this.schema=E,this.tableNamesMap=X,this.table=G,this.tableConfig=J,this.dialect=A,this.session=D}static[K]="SQLiteAsyncRelationalQueryBuilder";findMany($){return this.mode==="sync"?new T8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many"):new cJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many")}findFirst($){return this.mode==="sync"?new T8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first"):new cJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first")}};cJ=class cJ extends v${constructor($,w,E,X,G,J,A,D,N){super();this.fullSchema=$,this.schema=w,this.tableNamesMap=E,this.table=X,this.tableConfig=G,this.dialect=J,this.session=A,this.config=D,this.mode=N}static[K]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare($=!1){let{query:w,builtQuery:E}=this._toSQL();return this.session[$?"prepareOneTimeQuery":"prepareQuery"](E,void 0,this.mode==="first"?"get":"all",!0,(X,G)=>{let J=X.map((A)=>kJ(this.schema,this.tableConfig,A,w.selection,G));if(this.mode==="first")return J[0];return J})}prepare(){return this._prepare(!1)}_toSQL(){let $=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),w=this.dialect.sqlToQuery($.sql);return{query:$,builtQuery:w}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};T8=class T8 extends cJ{static[K]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var wX;var GY=R(()=>{E0();Fw();wX=class wX extends v${constructor($,w,E,X,G){super();this.execute=$,this.getSQL=w,this.dialect=X,this.mapBatchResult=G,this.config={action:E}}static[K]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult($,w){return w?this.mapBatchResult($):$}_prepare(){return this}isResponseInArrayMode(){return!1}}});var SG;var nJ=R(()=>{E0();aE();q$();z8();d1();EY();XY();GY();SG=class SG{constructor($,w,E,X){this.resultKind=$,this.dialect=w,this.session=E,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let G=this.query;if(this._.schema)for(let[J,A]of Object.entries(this._.schema))G[J]=new B8($,X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[J],A,w,E)}static[K]="BaseSQLiteDatabase";query;$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(new PG(E.dialect));return new Proxy(new jG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count($,w){return new qG({source:$,filters:w,session:this.session})}with(...$){let w=this;function E(D){return new Z1({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$})}function X(D){return new Z1({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$,distinct:!0})}function G(D){return new hJ(D,w.session,w.dialect,$)}function J(D){return new uJ(D,w.session,w.dialect,$)}function A(D){return new vJ(D,w.session,w.dialect,$)}return{select:E,selectDistinct:X,update:G,insert:J,delete:A}}select($){return new Z1({fields:$??void 0,session:this.session,dialect:this.dialect})}selectDistinct($){return new Z1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update($){return new hJ($,this.session,this.dialect)}insert($){return new uJ($,this.session,this.dialect)}delete($){return new vJ($,this.session,this.dialect)}run($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.run(w),()=>w,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(w)}all($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.all(w),()=>w,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(w)}get($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.get(w),()=>w,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(w)}values($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.values(w),()=>w,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(w)}transaction($,w){return this.session.transaction($,w)}}});var JY=()=>{};var AY=()=>{};function hw($){return new Q8($,!1)}function kG($){return new Q8($,!0)}var Q8,DY,NY;var WY=R(()=>{E0();Q8=class Q8{constructor($,w){this.name=$,this.unique=w}static[K]="SQLiteIndexBuilderOn";on(...$){return new DY(this.name,$,this.unique)}};DY=class DY{static[K]="SQLiteIndexBuilder";config;constructor($,w,E){this.config={name:$,columns:w,unique:E,where:void 0}}where($){return this.config.where=$,this}build($){return new NY(this.config,$)}};NY=class NY{static[K]="SQLiteIndex";config;constructor($,w){this.config={...$,table:w}}}});var OY=()=>{};var UY,I8,K8,V8;var P8=R(()=>{E0();fJ();Fw();nJ();UY=class UY extends v${constructor($){super();this.resultCb=$}static[K]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};I8=class I8{constructor($,w,E){this.mode=$,this.executeMethod=w,this.query=E}static[K]="PreparedQuery";joinsNotNullableMap;getQuery(){return this.query}mapRunResult($,w){return $}mapAllResult($,w){throw Error("Not implemented")}mapGetResult($,w){throw Error("Not implemented")}execute($){if(this.mode==="async")return this[this.executeMethod]($);return new UY(()=>this[this.executeMethod]($))}mapResult($,w){switch(this.executeMethod){case"run":return this.mapRunResult($,w);case"all":return this.mapAllResult($,w);case"get":return this.mapGetResult($,w)}}};K8=class K8{constructor($){this.dialect=$}static[K]="SQLiteSession";prepareOneTimeQuery($,w,E,X){return this.prepareQuery($,w,E,X)}run($){let w=this.dialect.sqlToQuery($);try{return this.prepareOneTimeQuery(w,void 0,"run",!1).run()}catch(E){throw new $X({cause:E,message:`Failed to run the query '${w.sql}'`})}}extractRawRunValueFromBatchResult($){return $}all($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).all()}extractRawAllValueFromBatchResult($){throw Error("Not implemented")}get($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).get()}extractRawGetValueFromBatchResult($){throw Error("Not implemented")}values($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).values()}async count($){return(await this.values($))[0][0]}extractRawValuesValueFromBatchResult($){throw Error("Not implemented")}};V8=class V8 extends SG{constructor($,w,E,X,G=0){super($,w,E,X);this.schema=X,this.nestedIndex=G}static[K]="SQLiteTransaction";rollback(){throw new U8}}});var YY=()=>{};var HY=()=>{};var q8=R(()=>{JY();AY();H8();nJ();yJ();w8();WY();OY();z8();P8();eE();E8();YY();HY()});var S8,k8,LY;var b8=R(()=>{E0();zJ();q$();q8();P8();o$();S8=class S8 extends K8{constructor($,w,E,X={}){super(w);this.client=$,this.schema=E,this.logger=X.logger??new cD}static[K]="SQLiteBunSession";logger;exec($){this.client.exec($)}prepareQuery($,w,E,X,G){let J=this.client.prepare($.sql);return new LY(J,$,this.logger,w,E,X,G)}transaction($,w={}){let E=new k8("sync",this.dialect,this,this.schema),X;return this.client.transaction(()=>{X=$(E)})[w.behavior??"deferred"](),X}};k8=class k8 extends V8{static[K]="SQLiteBunTransaction";transaction($){let w=`sp${this.nestedIndex}`,E=new k8("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(T.raw(`savepoint ${w}`));try{let X=$(E);return this.session.run(T.raw(`release savepoint ${w}`)),X}catch(X){throw this.session.run(T.raw(`rollback to savepoint ${w}`)),X}}};LY=class LY extends I8{constructor($,w,E,X,G,J,A){super("sync",G,w);this.stmt=$,this.logger=E,this.fields=X,this._isResponseInArrayMode=J,this.customResultMapper=A}static[K]="SQLiteBunPreparedQuery";run($){let w=MG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.run(...w)}all($){let{fields:w,query:E,logger:X,joinsNotNullableMap:G,stmt:J,customResultMapper:A}=this;if(!w&&!A){let N=MG(E.params,$??{});return X.logQuery(E.sql,N),J.all(...N)}let D=this.values($);if(A)return A(D);return D.map((N)=>dD(w,N,G))}get($){let w=MG(this.query.params,$??{});this.logger.logQuery(this.query.sql,w);let E=this.stmt.values(...w)[0];if(!E)return;let{fields:X,joinsNotNullableMap:G,customResultMapper:J}=this;if(!X&&!J)return E;if(J)return J([E]);return dD(X,E,G)}values($){let w=MG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.values(...w)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as mJ}from"bun:sqlite";function EX($,w={}){let E=new VG({casing:w.casing}),X;if(w.logger===!0)X=new hD;else if(w.logger!==!1)X=w.logger;let G;if(w.schema){let D=W7(w.schema,U7);G={fullSchema:w.schema,schema:D.tables,tableNamesMap:D.tableNamesMap}}let J=new S8($,E,G,{logger:X}),A=new FY("sync",E,J,G);return A.$client=$,A}function rJ(...$){if($[0]===void 0||typeof $[0]==="string"){let w=$[0]===void 0?new mJ:new mJ($[0]);return EX(w,$[1])}if(fU($[0])){let{connection:w,client:E,...X}=$[0];if(E)return EX(E,X);if(typeof w==="object"){let{source:J,...A}=w,D=Object.values(A).filter((W)=>W!==void 0).length?A:void 0,N=new mJ(J,D);return EX(N,X)}let G=new mJ(w);return EX(G,X)}return EX($[0],$[1])}var FY;var jY=R(()=>{E0();zJ();BG();nJ();yJ();o$();b8();FY=class FY extends SG{static[K]="BunSQLiteDatabase"};(($)=>{function w(E){return EX({},E)}$.mock=w})(rJ||(rJ={}))});var MY=R(()=>{jY();b8()});var RY=R(()=>{SJ()});var i$=R(()=>{ZJ();pD();b1();E0();fJ();RY();zJ();Fw();BG();Y8();d1();_$();o$();Lw()});var C8={};Ww(C8,{webhooks:()=>M2,tasks:()=>r,task_links:()=>f$,sessions:()=>C1,prompts:()=>D$,prompt_history:()=>ZG,projects:()=>n0,memories:()=>H1,jobs:()=>I0,job_runs:()=>E$,job_run_logs:()=>cw,gateway_sessions:()=>x$,comments:()=>G$,bridge_permissions:()=>XX,bridge_messages:()=>Z8,bridge_chats:()=>X$});var bG,n0,r,G$,f$,H1,D$,ZG,I0,E$,cw,C1,X$,Z8,XX,x$,M2;var d$=R(()=>{i$();q8();bG={created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},n0=M$("projects",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),status:q("status",{enum:["active","archived","paused"]}).default("active").notNull(),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),obsidian_path:q("obsidian_path"),...bG},($)=>[kG("projects_name_idx").on($.name)]),r=M$("tasks",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),title:q("title").notNull(),body:q("body"),status:q("status",{enum:["todo","doing","review","changes_requested","blocked","done","cancelled"]}).default("todo").notNull(),priority:q("priority",{enum:["low","normal","high","critical"]}).default("normal").notNull(),progress:s("progress").default(0).notNull(),due_at:s("due_at",{mode:"timestamp"}),tags:q("tags",{mode:"json"}).$type(),author:q("author").default("human").notNull(),claimed_by:q("claimed_by"),claim_expires_at:s("claim_expires_at",{mode:"timestamp"}),...bG}),G$=M$("comments",{id:q("id").primaryKey(),resource_type:q("resource_type",{enum:["task","project","job","memory"]}).notNull(),resource_id:q("resource_id").notNull(),content:q("content").notNull(),author:q("author").default("human").notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("comments_resource_idx").on($.resource_type,$.resource_id)]),f$=M$("task_links",{id:q("id").primaryKey(),from_task_id:q("from_task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),to_task_id:q("to_task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),link_type:q("link_type",{enum:["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]}).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("task_links_from_idx").on($.from_task_id),hw("task_links_to_idx").on($.to_task_id)]),H1=M$("memories",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),title:q("title"),type:q("type",{enum:["fact","decision","event","rule","discovery"]}).default("fact").notNull(),content:q("content").notNull(),source:q("source"),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),importance:q("importance",{enum:["low","normal","high","critical"]}).default("normal").notNull(),expires_at:s("expires_at",{mode:"timestamp"}),access_count:s("access_count").notNull().default(0),last_accessed_at:s("last_accessed_at",{mode:"timestamp"}),...bG}),D$=M$("prompts",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),is_skill:s("is_skill",{mode:"boolean"}).default(!1).notNull(),skill_dir:q("skill_dir"),skill_version:q("skill_version"),frontmatter:q("frontmatter",{mode:"json"}).$type(),tags:q("tags",{mode:"json"}).$type(),version:s("version").default(1).notNull(),pinned:s("pinned",{mode:"boolean"}).default(!1).notNull(),last_used_at:s("last_used_at",{mode:"timestamp"}),...bG},($)=>[kG("prompts_name_idx").on($.name)]),ZG=M$("prompt_history",{id:q("id").primaryKey(),prompt_id:q("prompt_id").notNull().references(()=>D$.id,{onDelete:"cascade"}),version:s("version").notNull(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),tags:q("tags",{mode:"json"}).$type(),changed_by:q("changed_by").default("human").notNull(),changed_at:s("changed_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("prompt_history_prompt_id_idx").on($.prompt_id,$.version)]),I0=M$("jobs",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),name:q("name").notNull(),description:q("description"),command:q("command").notNull(),prompt_id:q("prompt_id").references(()=>D$.id),prompt_vars:q("prompt_vars",{mode:"json"}).$type(),inject_context:s("inject_context",{mode:"boolean"}).default(!0).notNull(),trigger_type:q("trigger_type",{enum:["one-shot","cron","watch","webhook","manual","bridge-msg"]}).notNull(),cron_expr:q("cron_expr"),watch_path:q("watch_path"),run_at:s("run_at",{mode:"timestamp"}),timeout_secs:s("timeout_secs").default(300).notNull(),max_retries:s("max_retries").default(0).notNull(),overlap:q("overlap",{enum:["skip","queue","kill"]}).default("skip").notNull(),env_vars:q("env_vars",{mode:"json"}).$type(),working_dir:q("working_dir"),notify_on:q("notify_on",{enum:["never","failure","always"]}).default("failure").notNull(),notify_channel:q("notify_channel").default("telegram").notNull(),os_installed:s("os_installed",{mode:"boolean"}).default(!1).notNull(),enabled:s("enabled",{mode:"boolean"}).default(!0).notNull(),last_run_at:s("last_run_at",{mode:"timestamp"}),next_run_at:s("next_run_at",{mode:"timestamp"}),run_count:s("run_count").default(0).notNull(),...bG},($)=>[kG("jobs_name_idx").on($.name)]),E$=M$("job_runs",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),status:q("status",{enum:["pending","running","success","failed","cancelled","skipped"]}).notNull(),trigger_by:q("trigger_by"),started_at:s("started_at",{mode:"timestamp"}),ended_at:s("ended_at",{mode:"timestamp"}),exit_code:s("exit_code"),stdout:q("stdout"),stderr:q("stderr"),error_msg:q("error_msg"),retry_num:s("retry_num").default(0).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("job_runs_job_id_idx").on($.job_id)]),cw=M$("job_run_logs",{id:s("id",{mode:"number"}).primaryKey({autoIncrement:!0}),run_id:q("run_id").notNull().references(()=>E$.id,{onDelete:"cascade"}),ts:s("ts",{mode:"timestamp"}).notNull(),stream:q("stream",{enum:["stdout","stderr"]}).notNull(),line:q("line").notNull()},($)=>[hw("job_run_logs_run_id_idx").on($.run_id,$.ts)]),C1=M$("sessions",{id:q("id").primaryKey(),agent:q("agent").notNull(),agent_version:q("agent_version"),project_id:q("project_id").references(()=>n0.id),job_run_id:q("job_run_id").references(()=>E$.id),summary:q("summary"),events:q("events",{mode:"json"}).$type(),snapshot:q("snapshot"),tokens_used:s("tokens_used"),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)}),X$=M$("bridge_chats",{id:q("id").primaryKey(),platform:q("platform",{enum:["telegram","slack","discord","feishu"]}).notNull(),chat_id:q("chat_id").notNull(),username:q("username"),display_name:q("display_name"),mode:q("mode").default("direct").notNull(),authorized:s("authorized",{mode:"boolean"}).default(!1).notNull(),session_id:q("session_id"),thread_id:q("thread_id"),working_dir:q("working_dir"),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[kG("bridge_chats_platform_chat_idx").on($.platform,$.chat_id)]),Z8=M$("bridge_messages",{id:q("id").primaryKey(),chat_id:q("chat_id").references(()=>X$.id),direction:q("direction",{enum:["in","out"]}).notNull(),role:q("role",{enum:["system","user","assistant"]}).default("user").notNull(),text:q("text"),job_run_id:q("job_run_id").references(()=>E$.id),gateway_session_id:q("gateway_session_id").references(()=>x$.id),platform_msg_id:q("platform_msg_id"),thread_id:q("thread_id"),metadata:q("metadata",{mode:"json"}).$type(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)}),XX=M$("bridge_permissions",{id:q("id").primaryKey(),chat_id:q("chat_id"),gateway_session_id:q("gateway_session_id").references(()=>x$.id),job_run_id:q("job_run_id").references(()=>E$.id),tool:q("tool").notNull(),command:q("command"),scope:q("scope",{enum:["once","session"]}).default("once").notNull(),message:q("message"),status:q("status",{enum:["pending","approved","denied","expired"]}).default("pending").notNull(),expires_at:s("expires_at",{mode:"timestamp"}),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),resolved_at:s("resolved_at",{mode:"timestamp"})}),x$=M$("gateway_sessions",{id:q("id").primaryKey(),chat_id:q("chat_id").notNull().references(()=>X$.id,{onDelete:"cascade"}),backend:q("backend",{enum:["claude","codex","cursor"]}).notNull(),mode:q("mode").notNull(),runtime_session_id:q("runtime_session_id"),cwd:q("cwd"),title:q("title"),model:q("model"),status:q("status",{enum:["idle","running","stopped","error"]}).default("idle").notNull(),auto_approve:s("auto_approve",{mode:"boolean"}).default(!1).notNull(),task_id:q("task_id").references(()=>r.id,{onDelete:"set null"}),last_error:q("last_error"),last_activity_at:s("last_activity_at",{mode:"timestamp"}),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("gateway_sessions_chat_idx").on($.chat_id,$.updated_at)]),M2=M$("webhooks",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),token:q("token").notNull().unique(),enabled:s("enabled",{mode:"boolean"}).default(!0).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)})});import{Database as R2}from"bun:sqlite";import{mkdirSync as z2}from"fs";import{dirname as T2}from"path";function B2($){$.exec(`
35
+ `;w.run(G);let N=w.values(z`SELECT id, hash, created_at FROM ${z.identifier(X)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;w.run(z`BEGIN`);try{for(let D of $)if(!N||Number(N[2])<D.folderMillis){for(let O of D.sql)w.run(z.raw(O));w.run(z`INSERT INTO ${z.identifier(X)} ("hash", "created_at") VALUES(${D.hash}, ${D.folderMillis})`)}w.run(z`COMMIT`)}catch(D){throw w.run(z`ROLLBACK`),D}}}});var MW;var G7=T(()=>{E0();MW=class MW{static[K]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function cN($,w){return(E,X,...G)=>{let A=[X,...G].map((N)=>({type:$,isAll:w,rightSelect:N}));for(let N of A)if(!IG(E.getSelectedFields(),N.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return E.addSetOperators(A)}}var bw,A7,TW,zS=()=>({union:BS,unionAll:IS,intersect:QS,except:KS}),BS,IS,QS,KS;var RW=T(()=>{E0();G7();LE();$X();Z$();pw();u$();d$();HE();nN();bw=class bw{static[K]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor($){this.fields=$.fields,this.session=$.session,this.dialect=$.dialect,this.withList=$.withList,this.distinct=$.distinct}from($){let w=!!this.fields,E;if(this.fields)E=this.fields;else if(b($,H$))E=Object.fromEntries(Object.keys($._.selectedFields).map((X)=>[X,$[X]]));else if(b($,H1))E=$[a0].selectedFields;else if(b($,h))E={};else E=h5($);return new TW({table:$,fields:E,isPartialSelect:w,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};A7=class A7 extends MW{static[K]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:$,fields:w,isPartialSelect:E,session:X,dialect:G,withList:A,distinct:N}){super();this.config={withList:A,table:$,fields:{...w},distinct:N,setOperators:[]},this.isPartialSelect=E,this.session=X,this.dialect=G,this._={selectedFields:w},this.tableName=QG($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin($){return(w,E)=>{let X=this.tableName,G=QG(w);if(typeof G==="string"&&this.config.joins?.some((A)=>A.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof X==="string")this.config.fields={[X]:this.config.fields};if(typeof G==="string"&&!b(w,h)){let A=b(w,H$)?w._.selectedFields:b(w,Uw)?w[a0].selectedFields:w[y.Symbol.Columns];this.config.fields[G]=A}}if(typeof E==="function")E=E(new Proxy(this.config.fields,new N$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:E,table:w,joinType:$,alias:G}),typeof G==="string")switch($){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator($,w){return(E)=>{let X=typeof E==="function"?E(zS()):E;if(!IG(this.getSelectedFields(),X.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:$,isAll:w,rightSelect:X}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators($){return this.config.setOperators.push(...$),this}where($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new N$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=$,this}having($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new N$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=$,this}groupBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new N$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(w)?w:[w]}else this.config.groupBy=$;return this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new N$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=E;else this.config.orderBy=E}else{let w=$;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=w;else this.config.orderBy=w}return this}limit($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=$;else this.config.limit=$;return this}offset($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=$;else this.config.offset=$;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}as($){return new Proxy(new H$(this.getSQL(),this.config.fields,$),new N$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new N$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};TW=class TW extends A7{static[K]="SQLiteSelect";_prepare($=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let w=Yw(this.config.fields),E=this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),w,"all",!0);return E.joinsNotNullableMap=this.joinsNotNullableMap,E}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.all()}};n5(TW,[n$]);BS=cN("union",!1),IS=cN("union",!0),QS=cN("intersect",!1),KS=cN("except",!1)});var bG;var zW=T(()=>{E0();$X();hN();pw();RW();bG=class bG{static[K]="SQLiteQueryBuilder";dialect;dialectConfig;constructor($){this.dialect=b($,SG)?$:void 0,this.dialectConfig=b($,SG)?void 0:$}$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(E);return new Proxy(new zG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new N$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...$){let w=this;function E(G){return new bw({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$})}function X(G){return new bw({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$,distinct:!0})}return{select:E,selectDistinct:X}}select($){return new bw({fields:$??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct($){return new bw({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new kG(this.dialectConfig);return this.dialect}}});var rN,BW;var N7=T(()=>{E0();LE();Z$();wX();u$();d$();zW();rN=class rN{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteInsertBuilder";values($){if($=Array.isArray($)?$:[$],$.length===0)throw Error("values() must be called with at least one value");let w=$.map((E)=>{let X={},G=this.table[y.Symbol.Columns];for(let A of Object.keys(E)){let N=E[A];X[A]=b(N,h)?N:new Aw(N,G[A])}return X});return new BW(this.table,w,this.session,this.dialect,this.withList)}select($){let w=typeof $==="function"?$(new bG):$;if(!b(w,h)&&!IG(this.table[VN],w._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new BW(this.table,w,this.session,this.dialect,this.withList,!0)}};BW=class BW extends n${constructor($,w,E,X,G,A){super();this.session=E,this.dialect=X,this.config={table:$,values:w,withList:G,select:A}}static[K]="SQLiteInsert";config;returning($=this.config.table[C$.Symbol.Columns]){return this.config.returning=Yw($),this}onConflictDoNothing($={}){if(!this.config.onConflict)this.config.onConflict=[];if($.target===void 0)this.config.onConflict.push(z` on conflict do nothing`);else{let w=Array.isArray($.target)?z`${$.target}`:z`${[$.target]}`,E=$.where?z` where ${$.where}`:z``;this.config.onConflict.push(z` on conflict ${w} do nothing${E}`)}return this}onConflictDoUpdate($){if($.where&&($.targetWhere||$.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let w=$.where?z` where ${$.where}`:void 0,E=$.targetWhere?z` where ${$.targetWhere}`:void 0,X=$.setWhere?z` where ${$.setWhere}`:void 0,G=Array.isArray($.target)?z`${$.target}`:z`${[$.target]}`,A=this.dialect.buildUpdateSet(this.config.table,SN(this.config.table,$.set));return this.config.onConflict.push(z` on conflict ${G}${E} do update set ${A}${w}${X}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var tN,D7;var O7=T(()=>{E0();LE();$X();wX();pw();u$();d$();HE();nN();tN=class tN{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteUpdateBuilder";set($){return new D7(this.table,SN(this.table,$),this.session,this.dialect,this.withList)}};D7=class D7 extends n${constructor($,w,E,X,G){super();this.session=E,this.dialect=X,this.config={set:w,table:$,withList:G,joins:[]}}static[K]="SQLiteUpdate";config;from($){return this.config.from=$,this}createJoin($){return(w,E)=>{let X=QG(w);if(typeof X==="string"&&this.config.joins.some((G)=>G.alias===X))throw Error(`Alias "${X}" is already used in this query`);if(typeof E==="function"){let G=this.config.from?b(w,C$)?w[y.Symbol.Columns]:b(w,H$)?w._.selectedFields:b(w,H1)?w[a0].selectedFields:void 0:void 0;E=E(new Proxy(this.config.table[y.Symbol.Columns],new N$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new N$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:E,table:w,joinType:$,alias:X}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new N$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.config.table[C$.Symbol.Columns]){return this.config.returning=Yw($),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var IW=T(()=>{eY();N7();zW();RW();O7()});var _G;var W7=T(()=>{E0();Z$();_G=class _G extends h{constructor($){super(_G.buildEmbeddedCount($.source,$.filters).queryChunks);this.params=$,this.session=$.session,this.sql=_G.buildCount($.source,$.filters)}sql;static[K]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount($,w){return z`(select count(*) from ${$}${z.raw(" where ").if(w)}${w})`}static buildCount($,w){return z`select count(*) from ${$}${z.raw(" where ").if(w)}${w}`}then($,w){return Promise.resolve(this.session.count(this.sql)).then($,w)}catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}}});var KW,oN,QW;var J7=T(()=>{E0();LE();VG();KW=class KW{constructor($,w,E,X,G,A,N,D){this.mode=$,this.fullSchema=w,this.schema=E,this.tableNamesMap=X,this.table=G,this.tableConfig=A,this.dialect=N,this.session=D}static[K]="SQLiteAsyncRelationalQueryBuilder";findMany($){return this.mode==="sync"?new QW(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many"):new oN(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many")}findFirst($){return this.mode==="sync"?new QW(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first"):new oN(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first")}};oN=class oN extends n${constructor($,w,E,X,G,A,N,D,O){super();this.fullSchema=$,this.schema=w,this.tableNamesMap=E,this.table=X,this.tableConfig=G,this.dialect=A,this.session=N,this.config=D,this.mode=O}static[K]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare($=!1){let{query:w,builtQuery:E}=this._toSQL();return this.session[$?"prepareOneTimeQuery":"prepareQuery"](E,void 0,this.mode==="first"?"get":"all",!0,(X,G)=>{let A=X.map((N)=>CN(this.schema,this.tableConfig,N,w.selection,G));if(this.mode==="first")return A[0];return A})}prepare(){return this._prepare(!1)}_toSQL(){let $=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),w=this.dialect.sqlToQuery($.sql);return{query:$,builtQuery:w}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};QW=class QW extends oN{static[K]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var XX;var U7=T(()=>{E0();LE();XX=class XX extends n${constructor($,w,E,X,G){super();this.execute=$,this.getSQL=w,this.dialect=X,this.mapBatchResult=G,this.config={action:E}}static[K]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult($,w){return w?this.mapBatchResult($):$}_prepare(){return this}isResponseInArrayMode(){return!1}}});var ZG;var mN=T(()=>{E0();$X();Z$();IW();pw();W7();J7();U7();ZG=class ZG{constructor($,w,E,X){this.resultKind=$,this.dialect=w,this.session=E,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let G=this.query;if(this._.schema)for(let[A,N]of Object.entries(this._.schema))G[A]=new KW($,X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[A],N,w,E)}static[K]="BaseSQLiteDatabase";query;$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(new bG(E.dialect));return new Proxy(new zG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new N$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count($,w){return new _G({source:$,filters:w,session:this.session})}with(...$){let w=this;function E(D){return new bw({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$})}function X(D){return new bw({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$,distinct:!0})}function G(D){return new tN(D,w.session,w.dialect,$)}function A(D){return new rN(D,w.session,w.dialect,$)}function N(D){return new gN(D,w.session,w.dialect,$)}return{select:E,selectDistinct:X,update:G,insert:A,delete:N}}select($){return new bw({fields:$??void 0,session:this.session,dialect:this.dialect})}selectDistinct($){return new bw({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update($){return new tN($,this.session,this.dialect)}insert($){return new rN($,this.session,this.dialect)}delete($){return new gN($,this.session,this.dialect)}run($){let w=typeof $==="string"?z.raw($):$.getSQL();if(this.resultKind==="async")return new XX(async()=>this.session.run(w),()=>w,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(w)}all($){let w=typeof $==="string"?z.raw($):$.getSQL();if(this.resultKind==="async")return new XX(async()=>this.session.all(w),()=>w,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(w)}get($){let w=typeof $==="string"?z.raw($):$.getSQL();if(this.resultKind==="async")return new XX(async()=>this.session.get(w),()=>w,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(w)}values($){let w=typeof $==="string"?z.raw($):$.getSQL();if(this.resultKind==="async")return new XX(async()=>this.session.values(w),()=>w,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(w)}transaction($,w){return this.session.transaction($,w)}}});var Y7=()=>{};var H7=()=>{};function nE($){return new VW($,!1)}function CG($){return new VW($,!0)}var VW,L7,F7;var j7=T(()=>{E0();VW=class VW{constructor($,w){this.name=$,this.unique=w}static[K]="SQLiteIndexBuilderOn";on(...$){return new L7(this.name,$,this.unique)}};L7=class L7{static[K]="SQLiteIndexBuilder";config;constructor($,w,E){this.config={name:$,columns:w,unique:E,where:void 0}}where($){return this.config.where=$,this}build($){return new F7(this.config,$)}};F7=class F7{static[K]="SQLiteIndex";config;constructor($,w){this.config={...$,table:w}}}});var M7=()=>{};var T7,PW,qW,SW;var kW=T(()=>{E0();uN();LE();mN();T7=class T7 extends n${constructor($){super();this.resultCb=$}static[K]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};PW=class PW{constructor($,w,E){this.mode=$,this.executeMethod=w,this.query=E}static[K]="PreparedQuery";joinsNotNullableMap;getQuery(){return this.query}mapRunResult($,w){return $}mapAllResult($,w){throw Error("Not implemented")}mapGetResult($,w){throw Error("Not implemented")}execute($){if(this.mode==="async")return this[this.executeMethod]($);return new T7(()=>this[this.executeMethod]($))}mapResult($,w){switch(this.executeMethod){case"run":return this.mapRunResult($,w);case"all":return this.mapAllResult($,w);case"get":return this.mapGetResult($,w)}}};qW=class qW{constructor($){this.dialect=$}static[K]="SQLiteSession";prepareOneTimeQuery($,w,E,X){return this.prepareQuery($,w,E,X)}run($){let w=this.dialect.sqlToQuery($);try{return this.prepareOneTimeQuery(w,void 0,"run",!1).run()}catch(E){throw new EX({cause:E,message:`Failed to run the query '${w.sql}'`})}}extractRawRunValueFromBatchResult($){return $}all($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).all()}extractRawAllValueFromBatchResult($){throw Error("Not implemented")}get($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).get()}extractRawGetValueFromBatchResult($){throw Error("Not implemented")}values($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).values()}async count($){return(await this.values($))[0][0]}extractRawValuesValueFromBatchResult($){throw Error("Not implemented")}};SW=class SW extends ZG{constructor($,w,E,X,G=0){super($,w,E,X);this.schema=X,this.nestedIndex=G}static[K]="SQLiteTransaction";rollback(){throw new LW}}});var R7=()=>{};var z7=()=>{};var bW=T(()=>{Y7();H7();jW();mN();hN();GW();j7();M7();IW();kW();wX();AW();R7();z7()});var _W,ZW,B7;var CW=T(()=>{E0();QN();Z$();bW();kW();d$();_W=class _W extends qW{constructor($,w,E,X={}){super(w);this.client=$,this.schema=E,this.logger=X.logger??new tO}static[K]="SQLiteBunSession";logger;exec($){this.client.exec($)}prepareQuery($,w,E,X,G){let A=this.client.prepare($.sql);return new B7(A,$,this.logger,w,E,X,G)}transaction($,w={}){let E=new ZW("sync",this.dialect,this,this.schema),X;return this.client.transaction(()=>{X=$(E)})[w.behavior??"deferred"](),X}};ZW=class ZW extends SW{static[K]="SQLiteBunTransaction";transaction($){let w=`sp${this.nestedIndex}`,E=new ZW("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(z.raw(`savepoint ${w}`));try{let X=$(E);return this.session.run(z.raw(`release savepoint ${w}`)),X}catch(X){throw this.session.run(z.raw(`rollback to savepoint ${w}`)),X}}};B7=class B7 extends PW{constructor($,w,E,X,G,A,N){super("sync",G,w);this.stmt=$,this.logger=E,this.fields=X,this._isResponseInArrayMode=A,this.customResultMapper=N}static[K]="SQLiteBunPreparedQuery";run($){let w=BG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.run(...w)}all($){let{fields:w,query:E,logger:X,joinsNotNullableMap:G,stmt:A,customResultMapper:N}=this;if(!w&&!N){let O=BG(E.params,$??{});return X.logQuery(E.sql,O),A.all(...O)}let D=this.values($);if(N)return N(D);return D.map((O)=>aO(w,O,G))}get($){let w=BG(this.query.params,$??{});this.logger.logQuery(this.query.sql,w);let E=this.stmt.values(...w)[0];if(!E)return;let{fields:X,joinsNotNullableMap:G,customResultMapper:A}=this;if(!X&&!A)return E;if(A)return A([E]);return aO(X,E,G)}values($){let w=BG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.values(...w)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as iN}from"bun:sqlite";function GX($,w={}){let E=new kG({casing:w.casing}),X;if(w.logger===!0)X=new rO;else if(w.logger!==!1)X=w.logger;let G;if(w.schema){let D=jY(w.schema,TY);G={fullSchema:w.schema,schema:D.tables,tableNamesMap:D.tableNamesMap}}let A=new _W($,E,G,{logger:X}),N=new I7("sync",E,A,G);return N.$client=$,N}function pN(...$){if($[0]===void 0||typeof $[0]==="string"){let w=$[0]===void 0?new iN:new iN($[0]);return GX(w,$[1])}if(c5($[0])){let{connection:w,client:E,...X}=$[0];if(E)return GX(E,X);if(typeof w==="object"){let{source:A,...N}=w,D=Object.values(N).filter((W)=>W!==void 0).length?N:void 0,O=new iN(A,D);return GX(O,X)}let G=new iN(w);return GX(G,X)}return GX($[0],$[1])}var I7;var Q7=T(()=>{E0();QN();VG();mN();hN();d$();CW();I7=class I7 extends ZG{static[K]="BunSQLiteDatabase"};(($)=>{function w(E){return GX({},E)}$.mock=w})(pN||(pN={}))});var K7=T(()=>{Q7();CW()});var V7=T(()=>{ZN()});var f$=T(()=>{vN();pO();kw();E0();uN();V7();QN();LE();VG();FW();pw();u$();d$();HE()});var vW={};OE(vW,{webhooks:()=>VS,tasks:()=>t,task_links:()=>h$,sessions:()=>_w,prompts:()=>S0,prompt_history:()=>vG,projects:()=>y0,memories:()=>Hw,jobs:()=>I0,job_runs:()=>e0,job_run_logs:()=>hE,gateway_sessions:()=>v$,comments:()=>F$,bridge_permissions:()=>AX,bridge_messages:()=>fW,bridge_chats:()=>G$});var fG,y0,t,F$,h$,Hw,S0,vG,I0,e0,hE,_w,G$,fW,AX,v$,VS;var Q$=T(()=>{f$();bW();fG={created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`),updated_at:d("updated_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},y0=I$("projects",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),status:q("status",{enum:["active","archived","paused"]}).default("active").notNull(),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),obsidian_path:q("obsidian_path"),max_workers:d("max_workers"),...fG},($)=>[CG("projects_name_idx").on($.name)]),t=I$("tasks",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>y0.id),title:q("title").notNull(),body:q("body"),status:q("status",{enum:["todo","queued","doing","review","changes_requested","blocked","done","paused","cancelled"]}).default("todo").notNull(),priority:q("priority",{enum:["low","normal","high","critical"]}).default("normal").notNull(),progress:d("progress").default(0).notNull(),due_at:d("due_at",{mode:"timestamp"}),tags:q("tags",{mode:"json"}).$type(),author:q("author").default("human").notNull(),claimed_by:q("claimed_by"),claim_expires_at:d("claim_expires_at",{mode:"timestamp"}),prompt_id:q("prompt_id").references(()=>S0.id,{onDelete:"set null"}),required_review:d("required_review",{mode:"boolean"}).default(!0).notNull(),agent_backend:q("agent_backend",{enum:["claude","codex","cursor"]}),max_review_rounds:d("max_review_rounds").default(3).notNull(),...fG}),F$=I$("comments",{id:q("id").primaryKey(),resource_type:q("resource_type",{enum:["task","project","job","memory"]}).notNull(),resource_id:q("resource_id").notNull(),content:q("content").notNull(),author:q("author").default("human").notNull(),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},($)=>[nE("comments_resource_idx").on($.resource_type,$.resource_id)]),h$=I$("task_links",{id:q("id").primaryKey(),from_task_id:q("from_task_id").notNull().references(()=>t.id,{onDelete:"cascade"}),to_task_id:q("to_task_id").notNull().references(()=>t.id,{onDelete:"cascade"}),link_type:q("link_type",{enum:["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]}).notNull(),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},($)=>[nE("task_links_from_idx").on($.from_task_id),nE("task_links_to_idx").on($.to_task_id)]),Hw=I$("memories",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>y0.id),title:q("title"),type:q("type",{enum:["fact","decision","event","rule","discovery"]}).default("fact").notNull(),content:q("content").notNull(),source:q("source"),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),importance:q("importance",{enum:["low","normal","high","critical"]}).default("normal").notNull(),expires_at:d("expires_at",{mode:"timestamp"}),access_count:d("access_count").notNull().default(0),last_accessed_at:d("last_accessed_at",{mode:"timestamp"}),...fG}),S0=I$("prompts",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),is_skill:d("is_skill",{mode:"boolean"}).default(!1).notNull(),skill_dir:q("skill_dir"),skill_version:q("skill_version"),frontmatter:q("frontmatter",{mode:"json"}).$type(),tags:q("tags",{mode:"json"}).$type(),version:d("version").default(1).notNull(),pinned:d("pinned",{mode:"boolean"}).default(!1).notNull(),last_used_at:d("last_used_at",{mode:"timestamp"}),...fG},($)=>[CG("prompts_name_idx").on($.name)]),vG=I$("prompt_history",{id:q("id").primaryKey(),prompt_id:q("prompt_id").notNull().references(()=>S0.id,{onDelete:"cascade"}),version:d("version").notNull(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),tags:q("tags",{mode:"json"}).$type(),changed_by:q("changed_by").default("human").notNull(),changed_at:d("changed_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},($)=>[nE("prompt_history_prompt_id_idx").on($.prompt_id,$.version)]),I0=I$("jobs",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>y0.id),name:q("name").notNull(),description:q("description"),command:q("command").notNull(),prompt_id:q("prompt_id").references(()=>S0.id),prompt_vars:q("prompt_vars",{mode:"json"}).$type(),inject_context:d("inject_context",{mode:"boolean"}).default(!0).notNull(),trigger_type:q("trigger_type",{enum:["one-shot","cron","watch","webhook","manual","bridge-msg"]}).notNull(),cron_expr:q("cron_expr"),watch_path:q("watch_path"),run_at:d("run_at",{mode:"timestamp"}),timeout_secs:d("timeout_secs").default(300).notNull(),max_retries:d("max_retries").default(0).notNull(),overlap:q("overlap",{enum:["skip","queue","kill"]}).default("skip").notNull(),env_vars:q("env_vars",{mode:"json"}).$type(),working_dir:q("working_dir"),notify_on:q("notify_on",{enum:["never","failure","always"]}).default("failure").notNull(),notify_channel:q("notify_channel").default("telegram").notNull(),os_installed:d("os_installed",{mode:"boolean"}).default(!1).notNull(),enabled:d("enabled",{mode:"boolean"}).default(!0).notNull(),last_run_at:d("last_run_at",{mode:"timestamp"}),next_run_at:d("next_run_at",{mode:"timestamp"}),run_count:d("run_count").default(0).notNull(),...fG},($)=>[CG("jobs_name_idx").on($.name)]),e0=I$("job_runs",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),status:q("status",{enum:["pending","running","success","failed","cancelled","skipped"]}).notNull(),trigger_by:q("trigger_by"),started_at:d("started_at",{mode:"timestamp"}),ended_at:d("ended_at",{mode:"timestamp"}),exit_code:d("exit_code"),stdout:q("stdout"),stderr:q("stderr"),error_msg:q("error_msg"),retry_num:d("retry_num").default(0).notNull(),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},($)=>[nE("job_runs_job_id_idx").on($.job_id)]),hE=I$("job_run_logs",{id:d("id",{mode:"number"}).primaryKey({autoIncrement:!0}),run_id:q("run_id").notNull().references(()=>e0.id,{onDelete:"cascade"}),ts:d("ts",{mode:"timestamp"}).notNull(),stream:q("stream",{enum:["stdout","stderr"]}).notNull(),line:q("line").notNull()},($)=>[nE("job_run_logs_run_id_idx").on($.run_id,$.ts)]),_w=I$("sessions",{id:q("id").primaryKey(),agent:q("agent").notNull(),agent_version:q("agent_version"),project_id:q("project_id").references(()=>y0.id),job_run_id:q("job_run_id").references(()=>e0.id),summary:q("summary"),events:q("events",{mode:"json"}).$type(),snapshot:q("snapshot"),tokens_used:d("tokens_used"),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)}),G$=I$("bridge_chats",{id:q("id").primaryKey(),platform:q("platform",{enum:["telegram","slack","discord","feishu"]}).notNull(),chat_id:q("chat_id").notNull(),username:q("username"),display_name:q("display_name"),mode:q("mode").default("direct").notNull(),authorized:d("authorized",{mode:"boolean"}).default(!1).notNull(),session_id:q("session_id"),thread_id:q("thread_id"),working_dir:q("working_dir"),updated_at:d("updated_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},($)=>[CG("bridge_chats_platform_chat_idx").on($.platform,$.chat_id)]),fW=I$("bridge_messages",{id:q("id").primaryKey(),chat_id:q("chat_id").references(()=>G$.id),direction:q("direction",{enum:["in","out"]}).notNull(),role:q("role",{enum:["system","user","assistant"]}).default("user").notNull(),text:q("text"),job_run_id:q("job_run_id").references(()=>e0.id),gateway_session_id:q("gateway_session_id").references(()=>v$.id),platform_msg_id:q("platform_msg_id"),thread_id:q("thread_id"),metadata:q("metadata",{mode:"json"}).$type(),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)}),AX=I$("bridge_permissions",{id:q("id").primaryKey(),chat_id:q("chat_id"),gateway_session_id:q("gateway_session_id").references(()=>v$.id),job_run_id:q("job_run_id").references(()=>e0.id),tool:q("tool").notNull(),command:q("command"),scope:q("scope",{enum:["once","session"]}).default("once").notNull(),message:q("message"),status:q("status",{enum:["pending","approved","denied","expired"]}).default("pending").notNull(),expires_at:d("expires_at",{mode:"timestamp"}),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`),resolved_at:d("resolved_at",{mode:"timestamp"})}),v$=I$("gateway_sessions",{id:q("id").primaryKey(),chat_id:q("chat_id").references(()=>G$.id,{onDelete:"cascade"}),backend:q("backend",{enum:["claude","codex","cursor"]}).notNull(),mode:q("mode").notNull(),runtime_session_id:q("runtime_session_id"),cwd:q("cwd"),title:q("title"),model:q("model"),status:q("status",{enum:["idle","running","stopped","error"]}).default("idle").notNull(),auto_approve:d("auto_approve",{mode:"boolean"}).default(!1).notNull(),task_id:q("task_id").references(()=>t.id,{onDelete:"set null"}),last_error:q("last_error"),role:q("role",{enum:["main","worker"]}),pid:d("pid"),project_id:q("project_id").references(()=>y0.id,{onDelete:"set null"}),review_rounds:d("review_rounds").default(0).notNull(),last_activity_at:d("last_activity_at",{mode:"timestamp"}),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`),updated_at:d("updated_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)},($)=>[nE("gateway_sessions_chat_idx").on($.chat_id,$.updated_at)]),VS=I$("webhooks",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),token:q("token").notNull().unique(),enabled:d("enabled",{mode:"boolean"}).default(!0).notNull(),created_at:d("created_at",{mode:"timestamp"}).notNull().default(z`(unixepoch())`)})});import{Database as PS}from"bun:sqlite";import{mkdirSync as qS}from"fs";import{dirname as SS}from"path";function kS($){$.exec(`
36
36
  CREATE TABLE IF NOT EXISTS projects (
37
37
  id TEXT PRIMARY KEY,
38
38
  name TEXT NOT NULL,
@@ -359,62 +359,82 @@ Expecting one of '${E.join("', '")}'`);let X=`${$}Help`;return this.on(X,(G)=>{l
359
359
  );
360
360
 
361
361
  CREATE INDEX IF NOT EXISTS idx_snapshots_session ON session_snapshots(session_id, created_at DESC);
362
- `);let w=["ALTER TABLE memories ADD COLUMN title TEXT","ALTER TABLE memories ADD COLUMN type TEXT NOT NULL DEFAULT 'fact'","ALTER TABLE session_events ADD COLUMN data_hash TEXT","ALTER TABLE tasks ADD COLUMN progress INTEGER NOT NULL DEFAULT 0","ALTER TABLE tasks ADD COLUMN claimed_by TEXT","ALTER TABLE tasks ADD COLUMN claim_expires_at INTEGER","ALTER TABLE sessions ADD COLUMN agent_version TEXT","ALTER TABLE bridge_chats ADD COLUMN display_name TEXT","ALTER TABLE bridge_chats ADD COLUMN thread_id TEXT","ALTER TABLE bridge_chats ADD COLUMN working_dir TEXT","ALTER TABLE bridge_chats ADD COLUMN updated_at INTEGER NOT NULL DEFAULT (unixepoch())","ALTER TABLE bridge_messages ADD COLUMN role TEXT NOT NULL DEFAULT 'user'","ALTER TABLE bridge_messages ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_messages ADD COLUMN thread_id TEXT","ALTER TABLE bridge_messages ADD COLUMN metadata TEXT","ALTER TABLE bridge_permissions ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_permissions ADD COLUMN scope TEXT NOT NULL DEFAULT 'once'","ALTER TABLE bridge_permissions ADD COLUMN message TEXT","ALTER TABLE bridge_permissions ADD COLUMN expires_at INTEGER","ALTER TABLE gateway_sessions ADD COLUMN auto_approve INTEGER NOT NULL DEFAULT 0","ALTER TABLE gateway_sessions ADD COLUMN task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL","UPDATE jobs SET enabled=0 WHERE trigger_type='repeat'","ALTER TABLE memories ADD COLUMN project_id TEXT REFERENCES projects(id)","ALTER TABLE jobs ADD COLUMN project_id TEXT REFERENCES projects(id)","CREATE UNIQUE INDEX IF NOT EXISTS projects_name_idx ON projects(name)","ALTER TABLE memories ADD COLUMN access_count INTEGER NOT NULL DEFAULT 0","ALTER TABLE memories ADD COLUMN last_accessed_at INTEGER","INSERT INTO comments (id, resource_type, resource_id, content, author, created_at) SELECT id, 'task', task_id, content, author, created_at FROM task_notes WHERE 1","DROP TABLE IF EXISTS task_notes","DROP TABLE IF EXISTS task_comments","DROP TABLE IF EXISTS project_comments"];for(let E of w)try{$.exec(E)}catch{}}function Q2($){let w=O0(),E=$??w.db.path;if(E!==":memory:")z2(T2(E),{recursive:!0});let X=new R2(E);return X.exec("PRAGMA journal_mode=WAL;"),X.exec("PRAGMA foreign_keys=ON;"),X.exec("PRAGMA synchronous=NORMAL;"),B2(X),rJ(X,{schema:C8})}function x(){if(!_8)_8=Q2();return _8}var _8=null;var y$=R(()=>{C$();MY();d$()});async function A1($){let w=x(),E=await w.query.jobs.findFirst({where:V(I0.id,$.jobId)});if(!E)throw Error(`Job not found: ${$.jobId}`);let X=$.runId??i(),G=new Date;if($.runId)await w.update(E$).set({status:"running",started_at:G}).where(V(E$.id,X));else await w.insert(E$).values({id:X,job_id:E.id,status:"running",trigger_by:$.triggerBy??"manual",started_at:G,created_at:G});await w.update(I0).set({last_run_at:G,run_count:E.run_count+1,updated_at:G}).where(V(I0.id,E.id)),v8.info(`Starting job: ${E.name} [${X}]`);let J={...process.env,ORC_JOB_RUN_ID:X,...E.env_vars??{},...$.envOverrides??{}},A=(E.timeout_secs??300)*1000;try{let D=Bun.spawn({cmd:["sh","-c",E.command],cwd:E.working_dir??process.cwd(),env:J,stdout:"pipe",stderr:"pipe"}),N=[],W=[],O=[],Y=setTimeout(()=>D.kill(),A),H=async(z,B)=>{let Q=new TextDecoder,k="";for await(let v of z){k+=Q.decode(v,{stream:!0});let C=k.split(`
363
- `);k=C.pop()??"";for(let n of C){if(B==="stdout")N.push(n);else W.push(n);O.push({run_id:X,ts:new Date,stream:B,line:n})}}};await Promise.all([H(D.stdout,"stdout"),H(D.stderr,"stderr"),D.exited]),clearTimeout(Y);let L=D.exitCode??-1,F=new Date,j=L===0;if(O.length>0)await w.insert(cw).values(O);await w.update(E$).set({status:j?"success":"failed",exit_code:L,ended_at:F,stdout:N.join(`
362
+ `);let w=["ALTER TABLE memories ADD COLUMN title TEXT","ALTER TABLE memories ADD COLUMN type TEXT NOT NULL DEFAULT 'fact'","ALTER TABLE session_events ADD COLUMN data_hash TEXT","ALTER TABLE tasks ADD COLUMN progress INTEGER NOT NULL DEFAULT 0","ALTER TABLE tasks ADD COLUMN claimed_by TEXT","ALTER TABLE tasks ADD COLUMN claim_expires_at INTEGER","ALTER TABLE sessions ADD COLUMN agent_version TEXT","ALTER TABLE bridge_chats ADD COLUMN display_name TEXT","ALTER TABLE bridge_chats ADD COLUMN thread_id TEXT","ALTER TABLE bridge_chats ADD COLUMN working_dir TEXT","ALTER TABLE bridge_chats ADD COLUMN updated_at INTEGER NOT NULL DEFAULT (unixepoch())","ALTER TABLE bridge_messages ADD COLUMN role TEXT NOT NULL DEFAULT 'user'","ALTER TABLE bridge_messages ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_messages ADD COLUMN thread_id TEXT","ALTER TABLE bridge_messages ADD COLUMN metadata TEXT","ALTER TABLE bridge_permissions ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_permissions ADD COLUMN scope TEXT NOT NULL DEFAULT 'once'","ALTER TABLE bridge_permissions ADD COLUMN message TEXT","ALTER TABLE bridge_permissions ADD COLUMN expires_at INTEGER","ALTER TABLE gateway_sessions ADD COLUMN auto_approve INTEGER NOT NULL DEFAULT 0","ALTER TABLE gateway_sessions ADD COLUMN task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL","UPDATE jobs SET enabled=0 WHERE trigger_type='repeat'","ALTER TABLE memories ADD COLUMN project_id TEXT REFERENCES projects(id)","ALTER TABLE jobs ADD COLUMN project_id TEXT REFERENCES projects(id)","CREATE UNIQUE INDEX IF NOT EXISTS projects_name_idx ON projects(name)","ALTER TABLE memories ADD COLUMN access_count INTEGER NOT NULL DEFAULT 0","ALTER TABLE memories ADD COLUMN last_accessed_at INTEGER","INSERT INTO comments (id, resource_type, resource_id, content, author, created_at) SELECT id, 'task', task_id, content, author, created_at FROM task_notes WHERE 1","DROP TABLE IF EXISTS task_notes","DROP TABLE IF EXISTS task_comments","DROP TABLE IF EXISTS project_comments","ALTER TABLE tasks ADD COLUMN prompt_id TEXT REFERENCES prompts(id) ON DELETE SET NULL","ALTER TABLE tasks ADD COLUMN required_review INTEGER NOT NULL DEFAULT 1","ALTER TABLE tasks ADD COLUMN agent_backend TEXT","ALTER TABLE tasks ADD COLUMN max_review_rounds INTEGER NOT NULL DEFAULT 3","ALTER TABLE gateway_sessions ADD COLUMN role TEXT","ALTER TABLE gateway_sessions ADD COLUMN pid INTEGER","ALTER TABLE gateway_sessions ADD COLUMN project_id TEXT REFERENCES projects(id) ON DELETE SET NULL","ALTER TABLE gateway_sessions ADD COLUMN review_rounds INTEGER NOT NULL DEFAULT 0","ALTER TABLE projects ADD COLUMN max_workers INTEGER"];for(let E of w)try{$.exec(E)}catch{}try{$.exec(`INSERT OR IGNORE INTO bridge_chats (id, platform, chat_id, mode, authorized, updated_at, created_at)
363
+ VALUES ('__task-loop__', 'telegram', '__task-loop__', 'direct', 0, unixepoch(), unixepoch())`)}catch{}}function bS($){let w=G0(),E=$??w.db.path;if(E!==":memory:")qS(SS(E),{recursive:!0});let X=new PS(E);return X.exec("PRAGMA journal_mode=WAL;"),X.exec("PRAGMA foreign_keys=ON;"),X.exec("PRAGMA synchronous=NORMAL;"),kS(X),pN(X,{schema:vW})}function f(){if(!xW)xW=bS();return xW}function W$($){return($??f()).$client}var xW=null;var J$=T(()=>{R$();K7();Q$()});async function Nw($){let w=f(),E=await w.query.jobs.findFirst({where:V(I0.id,$.jobId)});if(!E)throw Error(`Job not found: ${$.jobId}`);let X=$.runId??r(),G=new Date;if($.runId)await w.update(e0).set({status:"running",started_at:G}).where(V(e0.id,X));else await w.insert(e0).values({id:X,job_id:E.id,status:"running",trigger_by:$.triggerBy??"manual",started_at:G,created_at:G});await w.update(I0).set({last_run_at:G,run_count:E.run_count+1,updated_at:G}).where(V(I0.id,E.id)),yW.info(`Starting job: ${E.name} [${X}]`);let A={...process.env,ORC_JOB_RUN_ID:X,...E.env_vars??{},...$.envOverrides??{}},N=(E.timeout_secs??300)*1000;try{let D=Bun.spawn({cmd:["sh","-c",E.command],cwd:E.working_dir??process.cwd(),env:A,stdout:"pipe",stderr:"pipe"}),O=[],W=[],J=[],Y=setTimeout(()=>D.kill(),N),H=async(R,B)=>{let I=new TextDecoder,C="";for await(let v of R){C+=I.decode(v,{stream:!0});let k=C.split(`
364
+ `);C=k.pop()??"";for(let n of k){if(B==="stdout")O.push(n);else W.push(n);J.push({run_id:X,ts:new Date,stream:B,line:n})}}};await Promise.all([H(D.stdout,"stdout"),H(D.stderr,"stderr"),D.exited]),clearTimeout(Y);let L=D.exitCode??-1,F=new Date,j=L===0;if(J.length>0)await w.insert(hE).values(J);await w.update(e0).set({status:j?"success":"failed",exit_code:L,ended_at:F,stdout:O.join(`
364
365
  `).slice(0,65536),stderr:W.join(`
365
- `).slice(0,16384)}).where(V(E$.id,X));let M=Math.round((F.getTime()-G.getTime())/1000);return await w.insert(C1).values({id:i(),agent:"runner",summary:`Job "${E.name}" ${j?"succeeded":"failed"} in ${M}s (exit ${L})`,job_run_id:X,created_at:F}),v8.info(`Job ${E.name} [${X}] ${j?"succeeded":"failed"} (exit ${L})`),X}catch(D){let N=D instanceof Error?D.message:String(D);throw await w.update(E$).set({status:"failed",ended_at:new Date,error_msg:N}).where(V(E$.id,X)),v8.error(`Job ${E.name} [${X}] crashed: ${N}`),D}}var v8;var nw=R(()=>{X1();p$();y$();d$();i$();v8=Z0("runner:executor")});function pJ($,w){zY.set($,w)}function TY($,w){let E=zY.get($);if(!E)throw Error(`No adapter registered for: ${$}`);return E(w)}var zY;var oJ=R(()=>{zY=new Map});async function GX($,w){if(typeof $==="number")return;let E=$.getReader(),X=new TextDecoder,G="";try{while(!0){let{done:J,value:A}=await E.read();if(J)break;G+=X.decode(A,{stream:!0});let D=G.split(`
366
- `);G=D.pop()??"";for(let N of D)if(N.trim())w(N)}if(G.trim())w(G)}finally{E.releaseLock()}}function JX($,w){if(!$||typeof $==="number")return;$.write(w)}function tJ($){if(!$||typeof $==="number")return;$.end()}function AX($,w){f8.set($,w)}function iJ($){let w=f8.get($);if(!w)throw Error(`No agent backend registered for: ${$}`);return w()}function BY(){return[...f8.keys()]}var f8;var dJ=R(()=>{f8=new Map});var QY={};Ww(QY,{startCodexSession:()=>x8,CodexSession:()=>lJ});function K2(){let $=new Set(["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_ORG_ID","HOME","USER","PATH","SHELL","TERM","LANG","SSH_AUTH_SOCK","SSH_AGENT_PID","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC"]),w={};for(let[E,X]of Object.entries(process.env))if(X!==void 0&&($.has(E)||E.startsWith("OPENAI_")))w[E]=X;return w}class lJ{id=i();proc=null;eventQueue=[];resolveNext=null;done=!1;state={hasReceivedResult:!1,lastAssistantText:""};runtimeSessionId;permissionResolvers=new Map;stderrLines=[];cwd;constructor($){this.cwd=$.cwd,this.runtimeSessionId=$.runtimeSessionId}async start($,w){let E=["codex","exec","--output-format","stream-json"];if($.runtimeSessionId)E.push("--session",$.runtimeSessionId);if($.model)E.push("--model",$.model);if(E.push(w),this.proc=Bun.spawn({cmd:E,cwd:this.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:K2()}),this.proc.stdout)GX(this.proc.stdout,(X)=>{try{this.handleLine(JSON.parse(X))}catch{}}).then(()=>{if(!this.state.hasReceivedResult)this.done=!0,this.resolveNext?.(),this.resolveNext=null});if(this.proc.stderr)GX(this.proc.stderr,(X)=>{if(this.stderrLines.push(X),this.stderrLines.length>100)this.stderrLines.shift()});this.watchExit()}handleLine($){let w=String($.type??"");if(w==="assistant_message"||w==="message"){let E=$.content,X=typeof E==="string"?E:Array.isArray(E)?E.map((G)=>String(G.text??"")).join(""):"";if(X)this.state.lastAssistantText=X,this.push({type:"text",data:X});return}if(w==="tool_call"||w==="function_call"){let E=String($.id??i());this.push({type:"tool_use",data:{id:E,name:String($.name??""),input:JSON.stringify($.arguments??$.input??{})}});return}if(w==="tool_result"||w==="function_result"){this.push({type:"tool_result",data:{toolUseId:String($.tool_call_id??$.id??""),content:String($.output??$.content??""),isError:Boolean($.is_error??!1)}});return}if(w==="approval_request"||w==="permission_request"){let E=String($.id??i()),X=String($.tool??$.name??""),G=JSON.stringify($.input??$.command??{}),J=new Promise((A)=>{this.permissionResolvers.set(E,A)});this.push({type:"permission_request",data:{requestId:E,tool:X,command:G}}),J.then((A)=>{if(A!=="denied"){let D=JSON.stringify({type:"approval_response",id:E,approved:!0});JX(this.proc?.stdin,new TextEncoder().encode(`${D}
366
+ `).slice(0,16384)}).where(V(e0.id,X));let M=Math.round((F.getTime()-G.getTime())/1000);return await w.insert(_w).values({id:r(),agent:"runner",summary:`Job "${E.name}" ${j?"succeeded":"failed"} in ${M}s (exit ${L})`,job_run_id:X,created_at:F}),yW.info(`Job ${E.name} [${X}] ${j?"succeeded":"failed"} (exit ${L})`),X}catch(D){let O=D instanceof Error?D.message:String(D);throw await w.update(e0).set({status:"failed",ended_at:new Date,error_msg:O}).where(V(e0.id,X)),yW.error(`Job ${E.name} [${X}] crashed: ${O}`),D}}var yW;var cE=T(()=>{B$();z$();J$();Q$();f$();yW=B0("runner:executor")});function dN($,w){P7.set($,w)}function q7($,w){let E=P7.get($);if(!E)throw Error(`No adapter registered for: ${$}`);return E(w)}var P7;var lN=T(()=>{P7=new Map});async function NX($,w){if(typeof $==="number")return;let E=$.getReader(),X=new TextDecoder,G="";try{while(!0){let{done:A,value:N}=await E.read();if(A)break;G+=X.decode(N,{stream:!0});let D=G.split(`
367
+ `);G=D.pop()??"";for(let O of D)if(O.trim())w(O)}if(G.trim())w(G)}finally{E.releaseLock()}}function DX($,w){if(!$||typeof $==="number")return;$.write(w)}function sN($){if(!$||typeof $==="number")return;$.end()}function L1($,w){gW.set($,w)}function OX($){let w=gW.get($);if(!w)throw Error(`No agent backend registered for: ${$}`);return w()}function uW(){return[...gW.keys()]}var gW;var aN=T(()=>{gW=new Map});function ZS(){let $=new Set(["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_ORG_ID","HOME","USER","PATH","SHELL","TERM","LANG","SSH_AUTH_SOCK","SSH_AGENT_PID","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC"]),w={};for(let[E,X]of Object.entries(process.env))if(X!==void 0&&($.has(E)||E.startsWith("OPENAI_")))w[E]=X;return w}class eN{id=r();proc=null;eventQueue=[];resolveNext=null;done=!1;state={hasReceivedResult:!1,lastAssistantText:""};runtimeSessionId;permissionResolvers=new Map;stderrLines=[];cwd;constructor($){this.cwd=$.cwd,this.runtimeSessionId=$.runtimeSessionId}async start($,w){let E=["codex","exec","--output-format","stream-json"];if($.runtimeSessionId)E.push("--session",$.runtimeSessionId);if($.model)E.push("--model",$.model);if(E.push(w),this.proc=Bun.spawn({cmd:E,cwd:this.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:ZS()}),this.proc.stdout)NX(this.proc.stdout,(X)=>{try{this.handleLine(JSON.parse(X))}catch{}}).then(()=>{if(!this.state.hasReceivedResult)this.done=!0,this.resolveNext?.(),this.resolveNext=null});if(this.proc.stderr)NX(this.proc.stderr,(X)=>{if(this.stderrLines.push(X),this.stderrLines.length>100)this.stderrLines.shift()});this.watchExit()}handleLine($){let w=String($.type??"");if(w==="assistant_message"||w==="message"){let E=$.content,X=typeof E==="string"?E:Array.isArray(E)?E.map((G)=>String(G.text??"")).join(""):"";if(X)this.state.lastAssistantText=X,this.push({type:"text",data:X});return}if(w==="tool_call"||w==="function_call"){let E=String($.id??r());this.push({type:"tool_use",data:{id:E,name:String($.name??""),input:JSON.stringify($.arguments??$.input??{})}});return}if(w==="tool_result"||w==="function_result"){this.push({type:"tool_result",data:{toolUseId:String($.tool_call_id??$.id??""),content:String($.output??$.content??""),isError:Boolean($.is_error??!1)}});return}if(w==="approval_request"||w==="permission_request"){let E=String($.id??r()),X=String($.tool??$.name??""),G=JSON.stringify($.input??$.command??{}),A=new Promise((N)=>{this.permissionResolvers.set(E,N)});this.push({type:"permission_request",data:{requestId:E,tool:X,command:G}}),A.then((N)=>{if(N!=="denied"){let D=JSON.stringify({type:"approval_response",id:E,approved:!0});DX(this.proc?.stdin,new TextEncoder().encode(`${D}
367
368
  `))}});return}if(w==="done"||w==="completed"||w==="session_end"){if(this.state.hasReceivedResult=!0,$.session_id)this.runtimeSessionId=String($.session_id);this.push({type:"result",data:{runtimeSessionId:this.runtimeSessionId,usage:$.usage}}),this.done=!0,this.resolveNext?.(),this.resolveNext=null}}async watchExit(){if(!this.proc)return;let $=await this.proc.exited;if(this.state.hasReceivedResult||this.done)return;if($!==0){let w=this.stderrLines.join(`
368
- `).trim();this.push({type:"error",data:w||`codex exited with code ${$}`})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}async send($){let w=JSON.stringify({type:"user_message",content:$});JX(this.proc?.stdin,new TextEncoder().encode(`${w}
369
- `))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){return this.proc?.exitCode===null}async close(){if(!this.proc)return;tJ(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),I2);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function V2(){return{name:"codex",async preflight(){if(!Bun.which("codex"))return{ok:!1,error:"codex CLI not found on PATH"};return{ok:!0}},async startSession($){throw Error("Codex sessions require an initial prompt \u2014 use startCodexSession() directly")},async resumeSession($,w){return new lJ({...w,runtimeSessionId:$})},async stop(){}}}async function x8($,w){let E=new lJ($);return await E.start($,w),E}var Je,I2=8000;var sJ=R(()=>{X1();p$();dJ();Je=Z0("agent-runtime:codex");AX("codex",V2)});function S2(){let $=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HOME","USER","PATH","SHELL","TERM","LANG","LC_ALL","SSH_AUTH_SOCK","SSH_AGENT_PID","XDG_RUNTIME_DIR","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC"]),w={};for(let[E,X]of Object.entries(process.env))if(X!==void 0&&($.has(E)||E.startsWith("ANTHROPIC_")))w[E]=X;return w}function y8(){return Bun.which("claude")??null}function k2($){return/auth|api.key|invalid.key|401|unauthorized/i.test($)}function IY($){if(!$)return"";if(typeof $==="string")return $;return $.map((w)=>w.text??w.thinking??"").join("")}class g8{id=i();proc=null;eventQueue=[];resolveNext=null;done=!1;state={hasReceivedResult:!1,hasStreamedText:!1,lastAssistantText:""};permissionResolvers=new Map;stderrRing=[];cwd;runtimeSessionId;claudePath;constructor($,w){this.cwd=$.cwd,this.runtimeSessionId=$.runtimeSessionId,this.claudePath=w}spawn($=[]){let w=[this.claudePath,"--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--no-color",...$];if(this.proc=Bun.spawn({cmd:w,cwd:this.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:S2()}),this.proc.stdout)GX(this.proc.stdout,(E)=>{try{this.handleStdoutLine(JSON.parse(E))}catch{}}).then(()=>this.handleEof());if(this.proc.stderr)GX(this.proc.stderr,(E)=>{if(this.stderrRing.push(E),this.stderrRing.length>q2)this.stderrRing.shift()});this.watchExit()}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}handleEof(){if(!this.state.hasReceivedResult)this.done=!0,this.resolveNext?.(),this.resolveNext=null}async start($){let w=$.runtimeSessionId?["--resume",$.runtimeSessionId]:[];this.spawn(w)}handleStdoutLine($){if($.type==="assistant"&&$.message?.content){for(let w of $.message.content){if(w.type==="text"&&w.text)this.state.hasStreamedText=!0,this.state.lastAssistantText=w.text,this.push({type:"text",data:w.text});if(w.type==="thinking"&&w.thinking)this.push({type:"thinking",data:w.thinking})}return}if($.type==="tool_use"){let w=$.id??i();this.push({type:"tool_use",data:{id:w,name:$.name??"",input:JSON.stringify($.input??{})}});return}if($.type==="tool_result"){this.push({type:"tool_result",data:{toolUseId:$.tool_use_id??$.tool_id??"",content:IY($.content),isError:$.is_error??!1}});return}if($.type==="control_request"||$.type==="permission_request"){let w=$.id??i(),E=$.name??IY($.content),X=typeof $.input==="object"&&$.input!==null?JSON.stringify($.input):String($.input??""),G=new Promise((J)=>{this.permissionResolvers.set(w,J)});this.push({type:"permission_request",data:{requestId:w,tool:E,command:X}}),G.then((J)=>this.sendControlResponse(w,J));return}if($.type==="result"||$.subtype==="end_turn"){if(this.state.hasReceivedResult=!0,$.session_id)this.runtimeSessionId=$.session_id;this.push({type:"result",data:{runtimeSessionId:this.runtimeSessionId,usage:$.usage}}),this.done=!0,this.resolveNext?.(),this.resolveNext=null;return}}async watchExit(){if(!this.proc)return;let $=await this.proc.exited;if(this.state.hasReceivedResult||this.done)return;let w=this.stderrRing.join(`
370
- `);if(k2(w))this.push({type:"error",data:"Authentication failed \u2014 check ANTHROPIC_API_KEY"});else if($!==0){let E=w.trim()||`claude exited with code ${$}`;this.push({type:"error",data:E})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}sendControlResponse($,w){let X={type:"control_response",id:$,result:w==="approved"||w==="session"?"approve":"deny"};JX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(X)}
371
- `))}async send($){let w={type:"user",message:{role:"user",content:$}};JX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(w)}
372
- `))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){if(!this.proc)return!1;return this.proc.exitCode===null}async close(){if(!this.proc)return;tJ(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),P2);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function b2(){return{name:"claude",async preflight(){let $=y8();if(!$)return{ok:!1,error:"claude CLI not found on PATH"};try{let w=Bun.spawn({cmd:[$,"--version"],stdout:"pipe",stderr:"pipe"}),E=await new Response(w.stdout).text();if(await w.exited,w.exitCode!==0)return{ok:!1,error:"claude --version failed"};let X=/(\d+)\./.exec(E);if((X?Number(X[1]):0)<2)return{ok:!1,error:`claude CLI too old (${E.trim()}), need >= 2.x`};return{ok:!0}}catch(w){return{ok:!1,error:String(w)}}},async startSession($){let w=y8();if(!w)throw Error("claude CLI not found on PATH");let E=new g8($,w);return await E.start($),E},async resumeSession($,w){let E=y8();if(!E)throw Error("claude CLI not found on PATH");let X=new g8({...w,runtimeSessionId:$},E);return await X.start({...w,runtimeSessionId:$}),X},async stop(){}}}var Oe,P2=8000,q2=200;var KY=R(()=>{X1();p$();dJ();Oe=Z0("agent-runtime:claude");AX("claude",b2)});var VY={};Ww(VY,{startCodexSession:()=>x8,registerBackend:()=>AX,listRegisteredBackends:()=>BY,createBackend:()=>iJ});var aJ=R(()=>{sJ();dJ();KY();sJ()});async function PY($){let w=x(),E=`${$.platform}:${$.chatId}`,X=await w.query.bridge_chats.findFirst({where:V(X$.id,E)});if(X)return await w.update(X$).set({username:$.username??X.username,display_name:$.displayName??X.display_name,authorized:$.authorized,thread_id:$.threadId??X.thread_id,updated_at:new Date}).where(V(X$.id,E)),await w.query.bridge_chats.findFirst({where:V(X$.id,E)})??X;return await w.insert(X$).values({id:E,platform:$.platform,chat_id:$.chatId,username:$.username,display_name:$.displayName,authorized:$.authorized,mode:$.mode,thread_id:$.threadId,updated_at:new Date,created_at:new Date}),await w.query.bridge_chats.findFirst({where:V(X$.id,E)})}async function u8($,w){await x().update(X$).set({mode:w,updated_at:new Date}).where(V(X$.id,$))}async function qY($,w){await x().update(X$).set({working_dir:w,updated_at:new Date}).where(V(X$.id,$))}async function DX($){await x().insert(Z8).values({id:i(),chat_id:$.chatKey,direction:$.direction,role:$.role,text:$.text,platform_msg_id:$.platformMessageId,gateway_session_id:$.gatewaySessionId,thread_id:$.threadId,metadata:$.metadata,created_at:new Date})}async function h8($){let w=x(),E=i(),X=new Date;return await w.insert(x$).values({id:E,chat_id:$.chatKey,backend:$.backend,cwd:$.cwd,mode:$.mode,title:$.title,status:"idle",last_activity_at:X,created_at:X,updated_at:X}),await w.update(X$).set({session_id:E,updated_at:X}).where(V(X$.id,$.chatKey)),await w.query.gateway_sessions.findFirst({where:V(x$.id,E)})}async function jw($){let w=x(),E=await w.query.bridge_chats.findFirst({where:V(X$.id,$)});if(E?.session_id){let X=await w.query.gateway_sessions.findFirst({where:V(x$.id,E.session_id)});if(X)return X}return w.query.gateway_sessions.findFirst({where:V(x$.chat_id,$),orderBy:[x0(x$.updated_at)]})}async function NX($){return x().query.gateway_sessions.findMany({where:V(x$.chat_id,$),orderBy:[x0(x$.updated_at)],limit:20})}async function CG($,w){await x().update(X$).set({session_id:w,updated_at:new Date}).where(V(X$.id,$))}async function a1($,w){await x().update(x$).set({...w,updated_at:new Date}).where(V(x$.id,$))}async function SY($){let w=x(),E=i();return await w.insert(XX).values({id:E,chat_id:$.chatKey,gateway_session_id:$.gatewaySessionId,tool:$.tool,command:$.command,message:$.message,scope:$.scope??"once",expires_at:$.expiresAt,created_at:new Date}),await w.query.bridge_permissions.findFirst({where:V(XX.id,E)})}async function c8($){let w=x();if($.length===26)return w.query.bridge_permissions.findFirst({where:V(XX.id,$)});return(await w.query.bridge_permissions.findMany({limit:20,orderBy:[x0(XX.created_at)]})).find((X)=>X.id.endsWith($))}async function _G($){let w=x();if($.length===26)return w.query.tasks.findFirst({where:V(r.id,$)});return(await w.query.tasks.findMany({limit:100,orderBy:[x0(r.updated_at)]})).find((X)=>X.id.endsWith($)||X.id===$)}async function kY($,w){let E=x();if(!await E.query.tasks.findFirst({where:V(r.id,$)}))return null;let G=new Date;if(await E.update(r).set({status:"done",updated_at:G}).where(V(r.id,$)),w)await E.insert(G$).values({id:i(),resource_type:"task",resource_id:$,content:w,author:"human",created_at:G});return await E.query.tasks.findFirst({where:V(r.id,$)})??null}async function bY($,w){let E=x();if(!await E.query.tasks.findFirst({where:V(r.id,$)}))return null;let G=new Date;if(await E.update(r).set({status:"changes_requested",updated_at:G}).where(V(r.id,$)),w)await E.insert(G$).values({id:i(),resource_type:"task",resource_id:$,content:w,author:"human",created_at:G});return await E.query.tasks.findFirst({where:V(r.id,$)})??null}async function n8($=8){return(await x().query.tasks.findMany({limit:$,orderBy:[x0(r.updated_at)]})).filter((X)=>!["done","cancelled"].includes(X.status))}async function ZY($,w=5){let X=await x().query.memories.findMany({limit:w*3,orderBy:[x0(H1.created_at)]}),G=$.toLowerCase().split(/\s+/).filter(Boolean);return X.filter((J)=>G.every((A)=>J.content.toLowerCase().includes(A)||J.title?.toLowerCase().includes(A))).slice(0,w)}async function eJ($){return x().query.jobs.findFirst({where:V(I0.name,$)})}async function m8($=10){return x().query.jobs.findMany({limit:$,orderBy:[x0(I0.updated_at)]})}async function CY(){return x().query.bridge_chats.findMany({where:S0(V(X$.authorized,!0),PJ(X$.platform,["telegram","slack"])),orderBy:[x0(X$.updated_at)]})}async function _Y($,w){await x().update(x$).set({task_id:w,updated_at:new Date}).where(V(x$.id,$))}var vG=R(()=>{X1();y$();d$();i$()});async function vY($,w,E,X){let G=xG.get($.session.id);if(!G||!G.alive())G=await C2($,w),xG.set($.session.id,G);else if($.session.backend==="codex")await G.send(w);else await G.send(w);return await _2($,G,E,X)}async function C2($,w){let E=$.session.backend,X=$.session.runtime_session_id??void 0;if(E==="codex"){let{startCodexSession:A}=await Promise.resolve().then(() => (sJ(),QY));return await A({cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X},w)}let G=iJ(E);if(X)try{return await G.resumeSession(X,{cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X})}catch(A){fG.warn(`Failed to resume ${E} session, starting fresh`,{err:A})}let J=await G.startSession({cwd:$.session.cwd,model:$.session.model??void 0});return await J.send(w),J}async function _2($,w,E,X){let G="",J,A=v2($.session.id,w);try{for await(let D of w.events()){if(A.reset(),D.type==="text"){if(G+=D.data,X&&E)await X.update($.session.id,G);continue}if(D.type==="thinking")continue;if(D.type==="tool_use"){let N=`\uD83D\uDD27 ${D.data.name}`;if(X&&E)await X.update($.session.id,`${G}
373
- ${N}`);continue}if(D.type==="permission_request"){let{requestId:N,tool:W,command:O}=D.data;if($.session.auto_approve){w.respondPermission(N,"approved");continue}if(A.pause(),X)X.freeze($.session.id);await SY({chatKey:$.chatKey,gatewaySessionId:$.session.id,tool:W,command:O,scope:"once",expiresAt:new Date(Date.now()+300000)});let Y=[[{label:"\u2705 Allow",value:`perm:approve:${N}`},{label:"\u274C Deny",value:`perm:deny:${N}`},{label:"\uD83D\uDD13 Allow session",value:`perm:session:${N}`}]],H=`\uD83D\uDD11 <b>Permission request</b>
369
+ `).trim();this.push({type:"error",data:w||`codex exited with code ${$}`})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}async send($){if(!this.proc){await this.start({cwd:this.cwd,runtimeSessionId:this.runtimeSessionId},$);return}let w=JSON.stringify({type:"user_message",content:$});DX(this.proc?.stdin,new TextEncoder().encode(`${w}
370
+ `))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){return this.proc?.exitCode===null}async close(){if(!this.proc)return;sN(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),_S);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function CS(){return{name:"codex",async preflight(){if(!Bun.which("codex"))return{ok:!1,error:"codex CLI not found on PATH"};return{ok:!0}},async startSession($){return new eN($)},async resumeSession($,w){return new eN({...w,runtimeSessionId:$})},async stop(){}}}async function xG($,w){let E=new eN($);return await E.start($,w),E}var Re,_S=8000;var nW=T(()=>{B$();z$();aN();Re=B0("agent-runtime:codex");L1("codex",CS)});function xS(){let $=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HOME","USER","PATH","SHELL","TERM","LANG","LC_ALL","SSH_AUTH_SOCK","SSH_AGENT_PID","XDG_RUNTIME_DIR","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC"]),w={};for(let[E,X]of Object.entries(process.env))if(X!==void 0&&($.has(E)||E.startsWith("ANTHROPIC_")))w[E]=X;return w}function hW(){let $=Bun.which("claude");if(!$)return null;return $.replaceAll("\\","/")}function yS($){return/auth|api.key|invalid.key|401|unauthorized/i.test($)}function S7($){if(!$)return"";if(typeof $==="string")return $;return $.map((w)=>w.text??w.thinking??"").join("")}class cW{id=r();proc=null;eventQueue=[];resolveNext=null;done=!1;state={hasReceivedResult:!1,hasStreamedText:!1,lastAssistantText:""};permissionResolvers=new Map;stderrRing=[];cwd;runtimeSessionId;claudePath;autoApprove;constructor($,w){this.cwd=$.cwd,this.runtimeSessionId=$.runtimeSessionId,this.claudePath=w,this.autoApprove=$.autoApprove??!1}spawn($=[],w){let E=this.autoApprove?[this.claudePath,"-p",w??"","--output-format","stream-json","--verbose","--dangerously-skip-permissions",...$]:[this.claudePath,"--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--no-color",...$];if(this.proc=Bun.spawn({cmd:E,cwd:this.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:xS()}),this.proc.stdout)NX(this.proc.stdout,(X)=>{try{this.handleStdoutLine(JSON.parse(X))}catch{}}).then(()=>this.handleEof());if(this.proc.stderr)NX(this.proc.stderr,(X)=>{if(this.stderrRing.push(X),this.stderrRing.length>vS)this.stderrRing.shift()});this.watchExit()}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}handleEof(){if(!this.state.hasReceivedResult)this.done=!0,this.resolveNext?.(),this.resolveNext=null}async start($){if(this.autoApprove)return;let w=$.runtimeSessionId?["--resume",$.runtimeSessionId]:[];this.spawn(w)}handleStdoutLine($){if($.type==="assistant"&&$.message?.content){for(let w of $.message.content){if(w.type==="text"&&w.text)this.state.hasStreamedText=!0,this.state.lastAssistantText=w.text,this.push({type:"text",data:w.text});if(w.type==="thinking"&&w.thinking)this.push({type:"thinking",data:w.thinking})}return}if($.type==="tool_use"){let w=$.id??r();this.push({type:"tool_use",data:{id:w,name:$.name??"",input:JSON.stringify($.input??{})}});return}if($.type==="tool_result"){this.push({type:"tool_result",data:{toolUseId:$.tool_use_id??$.tool_id??"",content:S7($.content),isError:$.is_error??!1}});return}if($.type==="control_request"||$.type==="permission_request"){let w=$.id??r(),E=$.name??S7($.content),X=typeof $.input==="object"&&$.input!==null?JSON.stringify($.input):String($.input??""),G=new Promise((A)=>{this.permissionResolvers.set(w,A)});this.push({type:"permission_request",data:{requestId:w,tool:E,command:X}}),G.then((A)=>this.sendControlResponse(w,A));return}if($.type==="result"||$.subtype==="end_turn"){if(this.state.hasReceivedResult=!0,$.session_id)this.runtimeSessionId=$.session_id;this.push({type:"result",data:{runtimeSessionId:this.runtimeSessionId,usage:$.usage}}),this.done=!0,this.resolveNext?.(),this.resolveNext=null;return}}async watchExit(){if(!this.proc)return;let $=await this.proc.exited;if(this.state.hasReceivedResult||this.done)return;let w=this.stderrRing.join(`
371
+ `);if(yS(w))this.push({type:"error",data:"Authentication failed \u2014 check ANTHROPIC_API_KEY"});else if($!==0){let E=w.trim()||`claude exited with code ${$}`;this.push({type:"error",data:E})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}sendControlResponse($,w){let X={type:"control_response",id:$,result:w==="approved"||w==="session"?"approve":"deny"};DX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(X)}
372
+ `))}async send($){if(this.autoApprove){if(this.proc)await this.close().catch(()=>{});this.spawn([],$);return}let w={type:"user",message:{role:"user",content:$}};DX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(w)}
373
+ `))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){if(!this.proc)return!1;return this.proc.exitCode===null}async close(){if(!this.proc)return;sN(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),fS);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function gS(){return{name:"claude",async preflight(){let $=hW();if(!$)return{ok:!1,error:"claude CLI not found on PATH"};try{let w=Bun.spawn({cmd:[$,"--version"],stdout:"pipe",stderr:"pipe"}),E=await new Response(w.stdout).text();if(await w.exited,w.exitCode!==0)return{ok:!1,error:"claude --version failed"};let X=/(\d+)\./.exec(E);if((X?Number(X[1]):0)<2)return{ok:!1,error:`claude CLI too old (${E.trim()}), need >= 2.x`};return{ok:!0}}catch(w){return{ok:!1,error:String(w)}}},async startSession($){let w=hW();if(!w)throw Error("claude CLI not found on PATH");let E=new cW($,w);return await E.start($),E},async resumeSession($,w){let E=hW();if(!E)throw Error("claude CLI not found on PATH");let X=new cW({...w,runtimeSessionId:$},E);return await X.start({...w,runtimeSessionId:$}),X},async stop(){}}}var Ve,fS=8000,vS=200;var k7=T(()=>{B$();z$();aN();Ve=B0("agent-runtime:claude");L1("claude",gS)});var WX=T(()=>{nW();aN();k7();nW()});var b7={};OE(b7,{startCodexSession:()=>xG,registerBackend:()=>L1,listRegisteredBackends:()=>uW,createBackend:()=>OX});var $D=T(()=>{WX();WX()});async function _7($){let w=f(),E=`${$.platform}:${$.chatId}`,X=await w.query.bridge_chats.findFirst({where:V(G$.id,E)});if(X)return await w.update(G$).set({username:$.username??X.username,display_name:$.displayName??X.display_name,authorized:$.authorized,thread_id:$.threadId??X.thread_id,updated_at:new Date}).where(V(G$.id,E)),await w.query.bridge_chats.findFirst({where:V(G$.id,E)})??X;return await w.insert(G$).values({id:E,platform:$.platform,chat_id:$.chatId,username:$.username,display_name:$.displayName,authorized:$.authorized,mode:$.mode,thread_id:$.threadId,updated_at:new Date,created_at:new Date}),await w.query.bridge_chats.findFirst({where:V(G$.id,E)})}async function rW($,w){await f().update(G$).set({mode:w,updated_at:new Date}).where(V(G$.id,$))}async function Z7($,w){await f().update(G$).set({working_dir:w,updated_at:new Date}).where(V(G$.id,$))}async function JX($){await f().insert(fW).values({id:r(),chat_id:$.chatKey,direction:$.direction,role:$.role,text:$.text,platform_msg_id:$.platformMessageId,gateway_session_id:$.gatewaySessionId,thread_id:$.threadId,metadata:$.metadata,created_at:new Date})}async function tW($){let w=f(),E=r(),X=new Date;return await w.insert(v$).values({id:E,chat_id:$.chatKey,backend:$.backend,cwd:$.cwd,mode:$.mode,title:$.title,status:"idle",last_activity_at:X,created_at:X,updated_at:X}),await w.update(G$).set({session_id:E,updated_at:X}).where(V(G$.id,$.chatKey)),await w.query.gateway_sessions.findFirst({where:V(v$.id,E)})}async function FE($){let w=f(),E=await w.query.bridge_chats.findFirst({where:V(G$.id,$)});if(E?.session_id){let X=await w.query.gateway_sessions.findFirst({where:V(v$.id,E.session_id)});if(X)return X}return w.query.gateway_sessions.findFirst({where:V(v$.chat_id,$),orderBy:[r0(v$.updated_at)]})}async function UX($){return f().query.gateway_sessions.findMany({where:V(v$.chat_id,$),orderBy:[r0(v$.updated_at)],limit:20})}async function yG($,w){await f().update(G$).set({session_id:w,updated_at:new Date}).where(V(G$.id,$))}async function sw($,w){await f().update(v$).set({...w,updated_at:new Date}).where(V(v$.id,$))}async function C7($){let w=f(),E=r();return await w.insert(AX).values({id:E,chat_id:$.chatKey,gateway_session_id:$.gatewaySessionId,tool:$.tool,command:$.command,message:$.message,scope:$.scope??"once",expires_at:$.expiresAt,created_at:new Date}),await w.query.bridge_permissions.findFirst({where:V(AX.id,E)})}async function oW($){let w=f();if($.length===26)return w.query.bridge_permissions.findFirst({where:V(AX.id,$)});return(await w.query.bridge_permissions.findMany({limit:20,orderBy:[r0(AX.created_at)]})).find((X)=>X.id.endsWith($))}async function gG($){let w=f();if($.length===26)return w.query.tasks.findFirst({where:V(t.id,$)});return(await w.query.tasks.findMany({limit:100,orderBy:[r0(t.updated_at)]})).find((X)=>X.id.endsWith($)||X.id===$)}async function f7($,w){let E=f();if(!await E.query.tasks.findFirst({where:V(t.id,$)}))return null;let G=new Date;if(await E.update(t).set({status:"done",updated_at:G}).where(V(t.id,$)),w)await E.insert(F$).values({id:r(),resource_type:"task",resource_id:$,content:w,author:"human",created_at:G});return await E.query.tasks.findFirst({where:V(t.id,$)})??null}async function v7($,w){let E=f();if(!await E.query.tasks.findFirst({where:V(t.id,$)}))return null;let G=new Date;if(await E.update(t).set({status:"changes_requested",updated_at:G}).where(V(t.id,$)),w)await E.insert(F$).values({id:r(),resource_type:"task",resource_id:$,content:w,author:"human",created_at:G});return await E.query.tasks.findFirst({where:V(t.id,$)})??null}async function mW($=8){return(await f().query.tasks.findMany({limit:$,orderBy:[r0(t.updated_at)]})).filter((X)=>!["done","cancelled"].includes(X.status))}async function x7($,w=5){let X=await f().query.memories.findMany({limit:w*3,orderBy:[r0(Hw.created_at)]}),G=$.toLowerCase().split(/\s+/).filter(Boolean);return X.filter((A)=>G.every((N)=>A.content.toLowerCase().includes(N)||A.title?.toLowerCase().includes(N))).slice(0,w)}async function wD($){return f().query.jobs.findFirst({where:V(I0.name,$)})}async function iW($=10){return f().query.jobs.findMany({limit:$,orderBy:[r0(I0.updated_at)]})}async function y7(){return f().query.bridge_chats.findMany({where:_0(V(G$.authorized,!0),bN(G$.platform,["telegram","slack"])),orderBy:[r0(G$.updated_at)]})}async function g7($,w){await f().update(v$).set({task_id:w,updated_at:new Date}).where(V(v$.id,$))}var uG=T(()=>{B$();J$();Q$();f$()});var u7={};OE(u7,{startCodexSession:()=>xG});var n7=T(()=>{WX();WX()});async function h7($,w,E,X){let G=hG.get($.session.id);if(!G||!G.alive())G=await nS($,w),hG.set($.session.id,G);else if($.session.backend==="codex")await G.send(w);else await G.send(w);return await hS($,G,E,X)}async function nS($,w){let E=$.session.backend,X=$.session.runtime_session_id??void 0;if(E==="codex"){let{startCodexSession:N}=await Promise.resolve().then(() => (n7(),u7));return await N({cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X},w)}let G=OX(E);if(X)try{return await G.resumeSession(X,{cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X})}catch(N){nG.warn(`Failed to resume ${E} session, starting fresh`,{err:N})}let A=await G.startSession({cwd:$.session.cwd,model:$.session.model??void 0});return await A.send(w),A}async function hS($,w,E,X){let G="",A,N=cS($.session.id,w);try{for await(let D of w.events()){if(N.reset(),D.type==="text"){if(G+=D.data,X&&E)await X.update($.session.id,G);continue}if(D.type==="thinking")continue;if(D.type==="tool_use"){let O=`\uD83D\uDD27 ${D.data.name}`;if(X&&E)await X.update($.session.id,`${G}
374
+ ${O}`);continue}if(D.type==="permission_request"){let{requestId:O,tool:W,command:J}=D.data;if($.session.auto_approve){w.respondPermission(O,"approved");continue}if(N.pause(),X)X.freeze($.session.id);await C7({chatKey:$.chatKey,gatewaySessionId:$.session.id,tool:W,command:J,scope:"once",expiresAt:new Date(Date.now()+300000)});let Y=[[{label:"\u2705 Allow",value:`perm:approve:${O}`},{label:"\u274C Deny",value:`perm:deny:${O}`},{label:"\uD83D\uDD13 Allow session",value:`perm:session:${O}`}]],H=`\uD83D\uDD11 <b>Permission request</b>
374
375
  <b>Tool:</b> ${W}
375
- <b>Command:</b> <code>${O.slice(0,200)}</code>`;if("sendWithButtons"in $.adapter)await $.adapter.sendWithButtons($.chatId,H,Y,{threadId:$.threadId,parseMode:"html"});else await $.adapter.send($.chatId,H,{threadId:$.threadId,parseMode:"html"});let L=await $.permissionManager.waitFor(N);if(w.respondPermission(N,L?"approved":"denied"),X)X.unfreeze($.session.id);A.resume();continue}if(D.type==="result"){J=D.data.runtimeSessionId;break}if(D.type==="error")throw Error(D.data)}}finally{A.clear()}return{output:G.trim()||"(no output)",runtimeSessionId:J}}function v2($,w){let E=!1,X=null;function G(){if(X)clearTimeout(X);if(E)return;X=setTimeout(async()=>{fG.warn("Idle timeout \u2014 closing agent session",{sessionId:$}),await w.close().catch(()=>{}),xG.delete($),await a1($,{status:"error",last_error:"Idle timeout",last_activity_at:new Date})},Z2)}return G(),{reset(){G()},pause(){if(E=!0,X)clearTimeout(X),X=null},resume(){E=!1,G()},clear(){if(X)clearTimeout(X),X=null}}}async function fY($){let w=xG.get($);if(w)xG.delete($),await w.close().catch(()=>{})}async function xY(){let{listRegisteredBackends:$,createBackend:w}=await Promise.resolve().then(() => (aJ(),VY));for(let E of $())try{let G=await w(E).preflight();if(!G.ok)fG.warn(`Agent backend preflight failed: ${E}`,{error:G.error});else fG.info(`Agent backend ready: ${E}`)}catch(X){fG.warn(`Agent backend preflight error: ${E}`,{err:X})}}var fG,Z2=600000,xG;var yY=R(()=>{p$();aJ();vG();fG=Z0("gateway:runner"),xG=new Map});class r8{windows=new Map;allow($){let w=Date.now(),E=w-60000,X=this.windows.get($)??[];if(X=X.filter((G)=>G>E),X.length>=20)return this.windows.set($,X),!1;return X.push(w),this.windows.set($,X),!0}clear($){this.windows.delete($)}}function p8($){return $.replace(f2,(w)=>`${"*".repeat(w.length-4)}${w.slice(-4)}`)}var f2;var gY=R(()=>{f2=/\b(sk-[A-Za-z0-9\-_]{20,}|xox[bpoa]-[A-Za-z0-9-]+|ghp_[A-Za-z0-9]{36}|AIza[A-Za-z0-9\-_]{35}|[0-9]{8,10}:[A-Za-z0-9\-_]{35})\b/g});function nY($){if($.endsWith("codex"))return"codex";if($.endsWith("cursor"))return"cursor";return"claude"}function uY($){if($==="running")return"\u26A1";if($==="error")return"\u274C";if($==="stopped")return"\u26D4";return"\uD83D\uDCA4"}function hY($){if($==="critical")return"\uD83D\uDD34";if($==="high")return"\uD83D\uDFE0";if($==="normal")return"\uD83D\uDFE1";return"\u26AA"}function cY($){if($==="done")return"\u2705";if($==="review")return"\uD83D\uDC40";if($==="doing")return"\uD83D\uDD28";if($==="blocked")return"\uD83D\uDEA7";if($==="changes_requested")return"\uD83D\uDD01";if($==="cancelled")return"\u274C";return"\uD83D\uDCCB"}function x2($){let w=["<b>ORC Gateway Commands</b>","","<b>Navigation</b>","/help \u2014 this message","/status \u2014 system overview","/mode [direct|agent:claude|agent:codex|agent:cursor|multi|job:&lt;name&gt;] \u2014 switch mode","/cwd &lt;path&gt; \u2014 set working directory","","<b>Tasks</b>","/tasks \u2014 list active tasks","/task &lt;id&gt; \u2014 task details","/approve &lt;id&gt; [note] \u2014 approve task or permission","/reject &lt;id&gt; [note] \u2014 reject task or deny permission","/assign &lt;task-id&gt; &lt;agent&gt; \u2014 assign task to agent session","","<b>Jobs</b>","/jobs \u2014 list jobs","/run &lt;name&gt; \u2014 trigger a job","","<b>Memory</b>","/mem &lt;query&gt; \u2014 search memories","","<b>Agents</b>","/agent claude|codex|cursor \u2014 switch active agent","/sessions \u2014 list all agent sessions","/session new|list|switch &lt;id&gt;|stop \u2014 session lifecycle"];if($.startsWith("agent:")||$==="multi")w.push("","<i>Current mode: agent \u2014 send any text to the active agent</i>");return w.join(`
376
- `)}async function mY($){let w=$.rawText.trim();if(!w.startsWith("/"))return null;let E=w.split(/\s+/),X=E[0]??"",G=E.slice(1).join(" ").trim();if(X==="/start"||X==="/help")return{html:x2($.currentMode??"direct")};if(X==="/status"){let J=await n8(5),A=await NX($.chatKey),D=await m8(5),N=await jw($.chatKey),W=["<b>ORC Status</b>","",`Mode: <code>${$.currentMode??"direct"}</code>`,`Working dir: <code>${$.currentWorkingDir??"(unset)"}</code>`,"",`<b>Tasks</b>: ${J.length} active`,`<b>Jobs</b>: ${D.length} defined`,`<b>Sessions</b>: ${A.length} total`];if(N)W.push(`<b>Active session</b>: ${N.backend} ${uY(N.status)} <code>${N.id.slice(-6)}</code>`);return{html:W.join(`
377
- `)}}if(X==="/mode"){if(!G)return{text:"Usage: /mode <direct|agent:claude|agent:codex|agent:cursor|multi|job:name>"};let J=G;return await u8($.chatKey,J),{text:`Mode updated to ${J}`,mode:J}}if(X==="/cwd"){if(!G)return{text:"Usage: /cwd <absolute-path>"};await qY($.chatKey,G);let J=await jw($.chatKey);if(J)await a1(J.id,{cwd:G});return{text:`Working directory set to ${G}`}}if(X==="/agent"){if(G!=="claude"&&G!=="codex"&&G!=="cursor")return{text:"Usage: /agent <claude|codex|cursor>"};let J=`agent:${G}`;return await u8($.chatKey,J),{text:`Agent mode set to ${J}`,mode:J}}if(X==="/tasks"){let J=await n8();if(J.length===0)return{text:"No active tasks."};let A=["<b>Active Tasks</b>",""];for(let D of J){let N=D.claimed_by?` [${D.claimed_by}]`:"";A.push(`${cY(D.status)} ${hY(D.priority)} <code>${D.id.slice(-6)}</code> ${D.title}${N}`)}return{html:A.join(`
378
- `)}}if(X==="/task"){if(!G)return{text:"Usage: /task <id>"};let J=await _G(G);if(!J)return{text:`Task not found: ${G}`};let A=[`<b>${J.title}</b>`,`ID: <code>${J.id}</code>`,`Status: ${cY(J.status)} ${J.status}`,`Priority: ${hY(J.priority)} ${J.priority}`];if(J.claimed_by)A.push(`Agent: ${J.claimed_by}`);if(J.body)A.push("",J.body.slice(0,500));let D=J.status==="review"?[[{label:"\u2705 Approve",value:`task:approve:${J.id}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${J.id}`}]]:void 0;return{html:A.join(`
379
- `),buttons:D}}if(X==="/approve"){if(!G)return{text:"Usage: /approve <task-or-permission-id> [note]"};let[J,...A]=G.split(/\s+/);if(!J)return{text:"Usage: /approve <task-or-permission-id> [note]"};let D=A.join(" ").trim(),N=await c8(J);if(N)return{text:`Permission ${N.id.slice(-6)} queued for approval \u2014 use the button or wait for agent context.`};let W=await _G(J);if(!W)return{text:`No task or permission found for ${J}`};return await kY(W.id,D||"Approved from gateway"),{text:`\u2705 Approved task [${W.id.slice(-6)}] ${W.title}`}}if(X==="/reject"){if(!G)return{text:"Usage: /reject <task-or-permission-id> [note]"};let[J,...A]=G.split(/\s+/);if(!J)return{text:"Usage: /reject <task-or-permission-id> [note]"};let D=A.join(" ").trim(),N=await c8(J);if(N)return{text:`Permission ${N.id.slice(-6)} denial queued \u2014 use the button or wait for agent context.`};let W=await _G(J);if(!W)return{text:`No task or permission found for ${J}`};return await bY(W.id,D||"Changes requested from gateway"),{text:`\uD83D\uDD01 Changes requested for [${W.id.slice(-6)}] ${W.title}`}}if(X==="/assign"){let[J,A]=G.split(/\s+/);if(!J||!A)return{text:"Usage: /assign <task-id> <agent>"};if(A!=="claude"&&A!=="codex"&&A!=="cursor")return{text:"Agent must be: claude, codex, or cursor"};let D=await _G(J);if(!D)return{text:`Task not found: ${J}`};let W=(await NX($.chatKey)).find((O)=>O.backend===A&&O.status!=="stopped");if(!W)return{text:`No active ${A} session found. Start one with /agent ${A} then send a message.`};return await _Y(W.id,D.id),{text:`Assigned [${D.id.slice(-6)}] ${D.title} \u2192 ${A} session [${W.id.slice(-6)}]`}}if(X==="/jobs"){let J=await m8();if(J.length===0)return{text:"No jobs defined."};let A=["<b>Jobs</b>",""];for(let D of J){let N=D.last_run_at?"ran":"never";A.push(`\u2022 <code>${D.name}</code> (${D.trigger_type}) \u2014 ${N} \xD7 ${D.run_count}`)}return{html:A.join(`
380
- `)}}if(X==="/run"){if(!G)return{text:"Usage: /run <job-name>"};let J=await eJ(G);if(!J)return{text:`Job not found: ${G}`};let A=await A1({jobId:J.id,triggerBy:"bridge-msg"});return{text:`Triggered ${J.name} \u2192 run ${A.slice(-6)}`}}if(X==="/mem"){if(!G)return{text:"Usage: /mem <query>"};let J=await ZY(G);if(J.length===0)return{text:"No matching memories."};let A=["<b>Memories</b>",""];for(let D of J){let N=D.title??D.content.slice(0,40);A.push(`\u2022 [${D.id.slice(-6)}] <b>${N}</b>`),A.push(` ${D.content.slice(0,120)}${D.content.length>120?"\u2026":""}`)}return{html:A.join(`
381
- `)}}if(X==="/sessions"){let J=await NX($.chatKey);if(J.length===0)return{text:"No agent sessions yet."};let A=await jw($.chatKey),D=["<b>Agent Sessions</b>",""];for(let N of J){let W=N.id===A?.id?"\u25B6 ":" ",O=N.task_id?` task:${N.task_id.slice(-6)}`:"";if(D.push(`${W}${uY(N.status)} <code>${N.id.slice(-6)}</code> ${N.backend}${O}`),N.cwd)D.push(` cwd: <code>${N.cwd}</code>`)}return{html:D.join(`
382
- `)}}if(X==="/session"){let[J,...A]=E.slice(1);if(!J)return{text:"Usage: /session <new|list|switch <id>|stop>"};if(J==="new"){let D=nY($.currentMode??"agent:claude"),N=await h8({chatKey:$.chatKey,backend:D,cwd:$.currentWorkingDir??void 0,mode:$.currentMode??`agent:${D}`,title:`Session ${i().slice(-6)}`});return await CG($.chatKey,N.id),{text:`Created and activated ${D} session [${N.id.slice(-6)}]`}}if(J==="list"){let D=await NX($.chatKey);if(D.length===0)return{text:"No gateway sessions yet."};let N=await jw($.chatKey);return{text:D.map((O,Y)=>{return`${O.id===N?.id?"*":" "}${Y+1}. [${O.id.slice(-6)}] ${O.backend} ${O.status} cwd=${O.cwd??"(unset)"}`}).join(`
383
- `)}}if(J==="switch"){let D=A.join(" ").trim();if(!D)return{text:"Usage: /session switch <id-or-index>"};let N=await NX($.chatKey),W=/^\d+$/.test(D)?N[Number(D)-1]:N.find((O)=>O.id===D||O.id.endsWith(D));if(!W)return{text:`Session not found: ${D}`};return await CG($.chatKey,W.id),{text:`Active session: [${W.id.slice(-6)}] ${W.backend}`}}if(J==="stop"){let D=await jw($.chatKey);if(D)await a1(D.id,{status:"stopped"});return await CG($.chatKey,null),{text:"Cleared active gateway session."}}return{text:"Usage: /session <new|list|switch <id>|stop>"}}return{text:`Unknown command: ${X}
384
-
385
- Type /help for available commands.`}}async function rY($){let w=await jw($.chatKey),E=nY($.mode);if(w&&w.backend===E&&w.status!=="stopped")return w;let X=await h8({chatKey:$.chatKey,backend:E,cwd:$.cwd??void 0,mode:$.mode,title:`Session ${i().slice(-6)}`});return await CG($.chatKey,X.id),X}var pY=R(()=>{X1();nw();vG()});class o8{pending=new Map;waitFor($){return new Promise((w)=>{let E=setTimeout(()=>{if(this.pending.delete($))w(!1)},300000);this.pending.set($,{resolve:w,timer:E})})}resolve($,w){let E=this.pending.get($);if(!E)return!1;return clearTimeout(E.timer),this.pending.delete($),E.resolve(w),!0}denyAll(){for(let[$,w]of this.pending)clearTimeout(w.timer),w.resolve(!1),this.pending.delete($)}hasPending($){return this.pending.has($)}}class $A{states=new Map;adapter;constructor($){this.adapter=$}static supports($){return"updateMessage"in $&&typeof $.updateMessage==="function"}async init($,w,E,X){this.states.set($,{chatId:w,msgId:E,lastText:X,lastEditAt:0,frozen:!1,degraded:!1,pendingText:null,pendingTimer:null})}async update($,w){let E=this.states.get($);if(!E||E.degraded)return;let X=w.length>3000?`${w.slice(0,3000)}
386
- \u2026`:w;if(E.frozen){E.pendingText=X;return}let G=Date.now(),J=Math.abs(X.length-E.lastText.length),A=G-E.lastEditAt;if(A<1500||J<30){if(E.pendingText=X,!E.pendingTimer){let D=Math.max(1500-A,100);E.pendingTimer=setTimeout(()=>this.flushPending($),D)}return}await this.doEdit(E,X)}freeze($){let w=this.states.get($);if(w)w.frozen=!0}unfreeze($){let w=this.states.get($);if(!w)return;if(w.frozen=!1,w.pendingText)this.flushPending($)}async finalize($,w){let E=this.states.get($);if(!E)return;if(E.pendingTimer)clearTimeout(E.pendingTimer),E.pendingTimer=null;let X=w.length>3000?`${w.slice(0,3000)}
387
- \u2026`:w;if(!E.degraded&&X!==E.lastText)await this.doEdit(E,X);this.states.delete($)}cleanup($){let w=this.states.get($);if(w?.pendingTimer)clearTimeout(w.pendingTimer);this.states.delete($)}async flushPending($){let w=this.states.get($);if(!w||!w.pendingText||w.frozen)return;w.pendingTimer=null;let E=w.pendingText;w.pendingText=null,await this.doEdit(w,E)}async doEdit($,w){try{await this.adapter.updateMessage($.chatId,$.msgId,w),$.lastText=w,$.lastEditAt=Date.now()}catch{$.degraded=!0}}}class t8{locked=new Set;tryAcquire($){if(this.locked.has($))return!1;return this.locked.add($),!0}release($){this.locked.delete($)}isLocked($){return this.locked.has($)}}function g2($){let w=O0(),E=w.gateway.slack.bot_token,X=w.gateway.slack.app_token;if(!E||!X)throw Error("Slack bot_token and app_token are required.");let G=null,J=null,A=!1,D=new Map;function N(M){let z=w.gateway.slack.authorized_users.map(String);return z.length>0&&z.includes(M)}function W(M){let z=Date.now();if(D.has(M))return!0;D.set(M,z);for(let[B,Q]of D)if(z-Q>y2)D.delete(B);return!1}function O(M){if(!M)return!1;return parseFloat(M)*1000<$}async function Y(){let M=await fetch("https://slack.com/api/apps.connections.open",{method:"POST",headers:{Authorization:`Bearer ${X}`}}),z=await M.json();if(!M.ok||!z.ok||!z.url)throw Error(z.error??`Slack socket connect failed (${M.status})`);return new WebSocket(z.url)}async function H(M){if(!G||!M||G.readyState!==WebSocket.OPEN)return;G.send(JSON.stringify({envelope_id:M}))}async function L(M){let z=JSON.parse(M.data);if(await H(z.envelope_id),!J)return;if(z.type==="interactive"){let C=z.payload??{},n=C.actions?.[0]?.value,T0=C.user?.id,f0=C.channel?.id;if(!n||!T0||!f0||!N(T0))return;await J({platform:"slack",chatId:f0,userId:T0,username:C.user?.username,displayName:C.user?.name,text:n,threadId:C.message?.ts});return}let Q=(z.payload??{}).event;if(!Q?.type||!Q.user||!Q.channel)return;if(!N(Q.user))return;if(Q.type!=="app_mention"&&!(Q.type==="message"&&Q.channel_type==="im"))return;if(Q.ts&&W(Q.ts))return;if(O(Q.ts))return;let k=[];for(let C of Q.files??[]){if(!C.url_private_download||!C.mimetype?.startsWith("audio/"))continue;try{let n=await fetch(C.url_private_download,{headers:{Authorization:`Bearer ${E}`}});k.push({kind:"audio",data:new Uint8Array(await n.arrayBuffer()),mimeType:C.mimetype,format:C.mimetype.split("/").at(1)??"mp3"})}catch{}}let v=(Q.text??"").replace(/^<@[^>]+>\s*/,"").trim();await J({platform:"slack",chatId:Q.channel,userId:Q.user,text:v,threadId:Q.thread_ts??Q.ts,platformMessageId:Q.ts,attachments:k.length>0?k:void 0})}async function F(M,z){let B=await fetch(`https://slack.com/api/${M}`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(z)}),Q=await B.json();if(!B.ok||Q.ok!==!0)throw Error(String(Q.error??`Slack request failed (${B.status})`));return Q}function j(M,z){if(!z?.length)return;return[{type:"section",text:{type:"mrkdwn",text:M}},{type:"actions",elements:z.flat().map((B)=>({type:"button",text:{type:"plain_text",text:B.label},value:B.value,action_id:B.value}))}]}return{platform:"slack",async start(M){J=M,A=!0;async function z(){G=await Y(),G.addEventListener("message",(B)=>{L(B)}),G.addEventListener("close",async()=>{if(!A)return;wA.warn("Slack socket closed; reconnecting in 5s"),await new Promise((B)=>setTimeout(B,5000));try{await z()}catch(B){wA.error("Slack reconnect failed",{err:B})}}),G.addEventListener("error",(B)=>{wA.warn("Slack socket error",{err:B})}),wA.info("Slack gateway adapter connected")}await z()},async stop(){A=!1,G?.close()},async send(M,z,B){let Q=j(z,B?.buttons),k=await F("chat.postMessage",{channel:M,text:z,thread_ts:B?.threadId,...Q?{blocks:Q}:{}});return`${String(k.channel??M)}:${String(k.ts??"")}`},async updateMessage(M,z,B,Q){let[k,v]=z.split(":");if(!k||!v)return;let C=j(B,Q?.buttons);await F("chat.update",{channel:k,ts:v,text:B,...C?{blocks:C}:{}})},async sendWithButtons(M,z,B,Q){let k=j(z,B),v=await F("chat.postMessage",{channel:M,text:z,thread_ts:Q?.threadId,...k?{blocks:k}:{}});return`${String(v.channel??M)}:${String(v.ts??"")}`}}}var wA,y2=60000;var oY=R(()=>{C$();p$();oJ();wA=Z0("gateway:slack");pJ("slack",($)=>g2($))});import{mkdtempSync as u2,readFileSync as h2,rmSync as tY,writeFileSync as c2}from"fs";import{tmpdir as n2}from"os";import{join as i8}from"path";function m2(){return Bun.which("ffmpeg")??null}function dY($){let w=$.toLowerCase();if(w==="oga"||w==="opus")return"ogg";if(w==="mpeg"||w==="mpga")return"mp3";return w}function iY($){let w=$.toLowerCase();if(w==="wav")return"audio/wav";if(w==="ogg"||w==="opus")return"audio/ogg";if(w==="mp4"||w==="m4a")return"audio/mp4";return"audio/mpeg"}function lY($,w,E){let X=m2();if(!X)throw Error("ffmpeg is required for voice support.");let G=u2(i8(n2(),"orc-gateway-")),J=i8(G,`input.${dY(w)}`),A=i8(G,`output.${E}`);c2(J,$);let D=["-y","-i",J];if(E==="mp3")D.push("-ac","1","-ar","16000");if(E==="ogg")D.push("-c:a","libopus");D.push(A);let N=Bun.spawnSync({cmd:[X,...D],stdout:"ignore",stderr:"pipe"});if(N.exitCode!==0){let O=new TextDecoder().decode(N.stderr);throw tY(G,{recursive:!0,force:!0}),Error(O||"ffmpeg conversion failed")}let W=h2(A);return tY(G,{recursive:!0,force:!0}),new Uint8Array(W)}function r2($){return!["mp3","wav","webm","m4a","mp4"].includes($.toLowerCase())}async function sY($){let w=O0();if(!w.speech.enabled)throw Error("Speech support is not enabled.");let{audio:E,format:X}=$;if(r2(X))E=lY(E,X,"mp3"),X="mp3";if(w.speech.provider==="qwen"){let W=w.speech.qwen.api_key;if(!W)throw Error("Qwen speech API key is not configured.");let O=w.speech.qwen.base_url??"https://dashscope.aliyuncs.com/compatible-mode/v1",Y={model:w.speech.qwen.model??"qwen3-asr-flash",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:`data:${iY(X)};base64,${Buffer.from(E).toString("base64")}`}}]}]},H=await fetch(`${O.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify(Y)}),L=await H.json();if(!H.ok)throw Error(L.error?.message??`Speech request failed (${H.status})`);return L.choices?.[0]?.message?.content?.trim()??""}let G=w.speech.provider==="groq"?w.speech.groq:w.speech.openai;if(!G.api_key)throw Error("Speech API key is not configured.");let J=G.base_url??(w.speech.provider==="groq"?"https://api.groq.com/openai/v1":"https://api.openai.com/v1"),A=new FormData;if(A.append("model",G.model??(w.speech.provider==="groq"?"whisper-large-v3-turbo":"whisper-1")),A.append("response_format","text"),w.speech.language)A.append("language",w.speech.language);A.append("file",new File([E],`audio.${dY(X)}`,{type:iY(X)}));let D=await fetch(`${J.replace(/\/$/,"")}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${G.api_key}`},body:A}),N=await D.text();if(!D.ok)throw Error(N||`Speech request failed (${D.status})`);return N.trim()}async function aY($){let w=O0();if(!w.tts.enabled)throw Error("TTS is not enabled.");if(w.tts.max_text_len>0&&$.length>w.tts.max_text_len)throw Error("Reply is too long for TTS.");if(w.tts.provider==="qwen"){let A=w.tts.qwen.api_key;if(!A)throw Error("Qwen TTS API key is not configured.");let D=await fetch(w.tts.qwen.base_url??"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",{method:"POST",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.qwen.model??"qwen3-tts-flash",input:{text:$,voice:w.tts.voice||"Cherry"}})}),N=await D.json();if(!D.ok||N.code)throw Error(N.message??`TTS request failed (${D.status})`);if(!N.output?.audio?.url)throw Error("Qwen TTS did not return audio.");let W=await fetch(N.output.audio.url),O=new Uint8Array(await W.arrayBuffer());return{audio:lY(O,"wav","ogg"),format:"ogg"}}let E=w.tts.openai.api_key??w.speech.openai.api_key;if(!E)throw Error("OpenAI TTS API key is not configured.");let X=w.tts.openai.base_url??"https://api.openai.com/v1",G=await fetch(`${X.replace(/\/$/,"")}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.openai.model??"tts-1",input:$,voice:w.tts.voice||"alloy"})});if(!G.ok)throw Error(await G.text());return{audio:new Uint8Array(await G.arrayBuffer()),format:"mp3"}}var eY=R(()=>{C$()});var GA=Z((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});YH.matchFilter=p2;YH.parse=WH;YH.preprocess=OH;var $H=new Map;function p2($){var w;let E=Array.isArray($)?$:[$],X=E.join(","),G=(w=$H.get(X))!==null&&w!==void 0?w:(()=>{let J=WH(E),A=o2(J);return $H.set(X,A),A})();return(J)=>G(J)}function WH($){return Array.isArray($)?$.map((w)=>w.split(":")):[$.split(":")]}function o2($){let w=$.flatMap((G)=>t2(G,OH(G))),E=d2(w),X=l2(E);return(G)=>!!X(G.update,G)}function OH($){let w=XA,E=[$].flatMap((X)=>{let[G,J,A]=X;if(!(G in NH))return[X];if(!G&&!J&&!A)return[X];let N=NH[G].map((W)=>[W,J,A]);if(J===void 0)return N;if(J in l8&&(J||A))return N;return N.filter(([W])=>{var O;return!!((O=w[W])===null||O===void 0?void 0:O[J])})}).flatMap((X)=>{let[G,J,A]=X;if(!(J in l8))return[X];if(!J&&!A)return[X];let N=l8[J].map((W)=>[G,W,A]);if(A===void 0)return N;return N.filter(([,W])=>{var O,Y;return!!((Y=(O=w[G])===null||O===void 0?void 0:O[W])===null||Y===void 0?void 0:Y[A])})});if(E.length===0)throw Error(`Shortcuts in '${$.join(":")}' do not expand to any valid filter query`);return E}function t2($,w){if(w.length===0)throw Error("Empty filter query given");let E=w.map(i2).filter((X)=>X!==!0);if(E.length===0)return w;else if(E.length===1)throw Error(E[0]);else throw Error(`Invalid filter query '${$.join(":")}'. There are ${E.length} errors after expanding the contained shortcuts: ${E.join("; ")}`)}function i2($){let[w,E,X,...G]=$;if(w===void 0)return"Empty filter query given";if(!(w in XA)){let D=Object.keys(XA);return`Invalid L1 filter '${w}' given in '${$.join(":")}'. Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}if(E===void 0)return!0;let J=XA[w];if(!(E in J)){let D=Object.keys(J);return`Invalid L2 filter '${E}' given in '${$.join(":")}'. Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}if(X===void 0)return!0;let A=J[E];if(!(X in A)){let D=Object.keys(A);return`Invalid L3 filter '${X}' given in '${$.join(":")}'. ${D.length===0?`No further filtering is possible after '${w}:${E}'.`:`Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}`}if(G.length===0)return!0;return`Cannot filter further than three levels, ':${G.join(":")}' is invalid!`}function d2($){var w,E;let X={};for(let[G,J,A]of $){let D=(w=X[G])!==null&&w!==void 0?w:X[G]={};if(J!==void 0){let N=(E=D[J])!==null&&E!==void 0?E:D[J]=new Set;if(A!==void 0)N.add(A)}}return X}function d8($,w){return(E,X)=>$(E,X)||w(E,X)}function wH($,w){return(E,X)=>{let G=$(E,X);return G&&w(G,X)}}function EH($){return(w,E)=>$(w,E)!=null}function l2($){let w=Object.entries($).map(([E,X])=>{let G=(A)=>A[E],J=Object.entries(X).map(([A,D])=>{let N=(O)=>O[A],W=Array.from(D).map((O)=>{return O==="me"?(H,L)=>{let F=L.me.id;return XH(H,(j)=>j.id===F)}:(H)=>XH(H,(L)=>L[O]||L.type===O)});return W.length===0?EH(N):wH(N,W.reduce(d8))});return J.length===0?EH(G):wH(G,J.reduce(d8))});if(w.length===0)throw Error("Cannot create filter function for empty query");return w.reduce(d8)}function XH($,w){let E=(X)=>X!=null&&w(X);return Array.isArray($)?$.some(E):E($)}var GH={mention:{},hashtag:{},cashtag:{},bot_command:{},url:{},email:{},phone_number:{},bold:{},italic:{},underline:{},strikethrough:{},spoiler:{},blockquote:{},expandable_blockquote:{},code:{},pre:{},text_link:{},text_mention:{},custom_emoji:{}},s8={me:{},is_bot:{},is_premium:{},added_to_attachment_menu:{}},s2={user:{},hidden_user:{},chat:{},channel:{}},a2={is_video:{},is_animated:{},premium_animation:{}},a8={emoji:{},custom_emoji:{},paid:{}},JH={can_be_upgraded:{},is_upgrade_separate:{},is_private:{}},UH={forward_origin:s2,is_topic_message:{},is_automatic_forward:{},business_connection_id:{},text:{},animation:{},audio:{},document:{},paid_media:{},photo:{},sticker:a2,story:{},video:{},video_note:{},voice:{},contact:{},dice:{},game:{},poll:{},venue:{},location:{},entities:GH,caption_entities:GH,caption:{},link_preview_options:{url:{},prefer_small_media:{},prefer_large_media:{},show_above_text:{}},effect_id:{},paid_star_count:{},has_media_spoiler:{},new_chat_title:{},new_chat_photo:{},delete_chat_photo:{},message_auto_delete_timer_changed:{},pinned_message:{},invoice:{},proximity_alert_triggered:{},chat_background_set:{},giveaway_created:{},giveaway:{only_new_members:{},has_public_winners:{}},giveaway_winners:{only_new_members:{},was_refunded:{}},giveaway_completed:{},gift:JH,gift_upgrade_sent:JH,unique_gift:{transfer_star_count:{}},paid_message_price_changed:{},video_chat_scheduled:{},video_chat_started:{},video_chat_ended:{},video_chat_participants_invited:{},web_app_data:{}},EA={...UH,direct_messages_topic:{},chat_owner_left:{new_owner:{}},chat_owner_changd:{},new_chat_members:s8,left_chat_member:s8,group_chat_created:{},supergroup_chat_created:{},migrate_to_chat_id:{},migrate_from_chat_id:{},successful_payment:{},refunded_payment:{},users_shared:{},chat_shared:{},connected_website:{},write_access_allowed:{},passport_data:{},boost_added:{},forum_topic_created:{is_name_implicit:{}},forum_topic_edited:{name:{},icon_custom_emoji_id:{}},forum_topic_closed:{},forum_topic_reopened:{},general_forum_topic_hidden:{},general_forum_topic_unhidden:{},checklist:{others_can_add_tasks:{},others_can_mark_tasks_as_done:{}},checklist_tasks_done:{},checklist_tasks_added:{},suggested_post_info:{},suggested_post_approved:{},suggested_post_approval_failed:{},suggested_post_declined:{},suggested_post_paid:{},suggested_post_refunded:{},sender_boost_count:{}},AH={...UH,channel_chat_created:{},direct_message_price_changed:{},is_paid_post:{}},e2={can_reply:{},is_enabled:{}},$S={old_reaction:a8,new_reaction:a8},wS={reactions:a8},ES={data:{},game_short_name:{}},DH={from:s8},XA={message:EA,edited_message:EA,channel_post:AH,edited_channel_post:AH,business_connection:e2,business_message:EA,edited_business_message:EA,deleted_business_messages:{},inline_query:{},chosen_inline_result:{},callback_query:ES,shipping_query:{},pre_checkout_query:{},poll:{},poll_answer:{},my_chat_member:DH,chat_member:DH,chat_join_request:{},message_reaction:$S,message_reaction_count:wS,chat_boost:{},removed_chat_boost:{},purchased_paid_media:{}},NH={"":["message","channel_post"],msg:["message","channel_post"],edit:["edited_message","edited_channel_post"]},l8={"":["entities","caption_entities"],media:["photo","video"],file:["photo","animation","audio","document","video","video_note","voice","sticker"]}});var AA=Z((HH)=>{Object.defineProperty(HH,"__esModule",{value:!0});HH.Context=void 0;var AS=GA(),e1={filterQuery($){let w=(0,AS.matchFilter)($);return(E)=>w(E)},text($){let w=e1.filterQuery([":text",":caption"]),E=HE($);return(X)=>{var G,J;if(!w(X))return!1;let A=(G=X.message)!==null&&G!==void 0?G:X.channelPost,D=(J=A.text)!==null&&J!==void 0?J:A.caption;return LE(X,D,E)}},command($){let w=e1.filterQuery(":entities:bot_command"),E=new Set,X=new Set;return JA($).forEach((G)=>{if(G.startsWith("/"))throw Error(`Do not include '/' when registering command handlers (use '${G.substring(1)}' not '${G}')`);(G.includes("@")?E:X).add(G)}),(G)=>{var J,A;if(!w(G))return!1;let D=(J=G.message)!==null&&J!==void 0?J:G.channelPost,N=(A=D.text)!==null&&A!==void 0?A:D.caption;return D.entities.some((W)=>{if(W.type!=="bot_command")return!1;if(W.offset!==0)return!1;let O=N.substring(1,W.length);if(X.has(O)||E.has(O))return G.match=N.substring(O.length+1).trimStart(),!0;let Y=O.indexOf("@");if(Y===-1)return!1;let H=O.substring(Y+1).toLowerCase(),L=G.me.username.toLowerCase();if(H!==L)return!1;let F=O.substring(0,Y);if(X.has(F))return G.match=N.substring(O.length+1).trimStart(),!0;return!1})}},reaction($){let w=e1.filterQuery("message_reaction"),E=typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((A)=>typeof A==="string"?{type:"emoji",emoji:A}:A),X=new Set(E.filter((A)=>A.type==="emoji").map((A)=>A.emoji)),G=new Set(E.filter((A)=>A.type==="custom_emoji").map((A)=>A.custom_emoji_id)),J=E.some((A)=>A.type==="paid");return(A)=>{if(!w(A))return!1;let{old_reaction:D,new_reaction:N}=A.messageReaction;for(let W of N){let O=!1;if(W.type==="emoji")for(let Y of D){if(Y.type!=="emoji")continue;if(Y.emoji===W.emoji){O=!0;break}}else if(W.type==="custom_emoji")for(let Y of D){if(Y.type!=="custom_emoji")continue;if(Y.custom_emoji_id===W.custom_emoji_id){O=!0;break}}else if(W.type==="paid")for(let Y of D){if(Y.type!=="paid")continue;O=!0;break}if(O)continue;if(W.type==="emoji"){if(X.has(W.emoji))return!0}else if(W.type==="custom_emoji"){if(G.has(W.custom_emoji_id))return!0}else if(W.type==="paid"){if(J)return!0}else return!0}return!1}},chatType($){let w=new Set(JA($));return(E)=>{var X;return((X=E.chat)===null||X===void 0?void 0:X.type)!==void 0&&w.has(E.chat.type)}},callbackQuery($){let w=e1.filterQuery("callback_query:data"),E=HE($);return(X)=>w(X)&&LE(X,X.callbackQuery.data,E)},gameQuery($){let w=e1.filterQuery("callback_query:game_short_name"),E=HE($);return(X)=>w(X)&&LE(X,X.callbackQuery.game_short_name,E)},inlineQuery($){let w=e1.filterQuery("inline_query"),E=HE($);return(X)=>w(X)&&LE(X,X.inlineQuery.query,E)},chosenInlineResult($){let w=e1.filterQuery("chosen_inline_result"),E=HE($);return(X)=>w(X)&&LE(X,X.chosenInlineResult.result_id,E)},preCheckoutQuery($){let w=e1.filterQuery("pre_checkout_query"),E=HE($);return(X)=>w(X)&&LE(X,X.preCheckoutQuery.invoice_payload,E)},shippingQuery($){let w=e1.filterQuery("shipping_query"),E=HE($);return(X)=>w(X)&&LE(X,X.shippingQuery.invoice_payload,E)}};class l${constructor($,w,E){this.update=$,this.api=w,this.me=E}get message(){return this.update.message}get editedMessage(){return this.update.edited_message}get channelPost(){return this.update.channel_post}get editedChannelPost(){return this.update.edited_channel_post}get businessConnection(){return this.update.business_connection}get businessMessage(){return this.update.business_message}get editedBusinessMessage(){return this.update.edited_business_message}get deletedBusinessMessages(){return this.update.deleted_business_messages}get messageReaction(){return this.update.message_reaction}get messageReactionCount(){return this.update.message_reaction_count}get inlineQuery(){return this.update.inline_query}get chosenInlineResult(){return this.update.chosen_inline_result}get callbackQuery(){return this.update.callback_query}get shippingQuery(){return this.update.shipping_query}get preCheckoutQuery(){return this.update.pre_checkout_query}get poll(){return this.update.poll}get pollAnswer(){return this.update.poll_answer}get myChatMember(){return this.update.my_chat_member}get chatMember(){return this.update.chat_member}get chatJoinRequest(){return this.update.chat_join_request}get chatBoost(){return this.update.chat_boost}get removedChatBoost(){return this.update.removed_chat_boost}get purchasedPaidMedia(){return this.update.purchased_paid_media}get msg(){var $,w,E,X,G,J,A;return(J=(G=(X=(E=(w=($=this.message)!==null&&$!==void 0?$:this.editedMessage)!==null&&w!==void 0?w:this.channelPost)!==null&&E!==void 0?E:this.editedChannelPost)!==null&&X!==void 0?X:this.businessMessage)!==null&&G!==void 0?G:this.editedBusinessMessage)!==null&&J!==void 0?J:(A=this.callbackQuery)===null||A===void 0?void 0:A.message}get chat(){var $,w,E,X,G,J,A,D,N;return(N=(D=(A=(J=(G=(X=(E=(w=($=this.msg)!==null&&$!==void 0?$:this.deletedBusinessMessages)!==null&&w!==void 0?w:this.messageReaction)!==null&&E!==void 0?E:this.messageReactionCount)!==null&&X!==void 0?X:this.myChatMember)!==null&&G!==void 0?G:this.chatMember)!==null&&J!==void 0?J:this.chatJoinRequest)!==null&&A!==void 0?A:this.chatBoost)!==null&&D!==void 0?D:this.removedChatBoost)===null||N===void 0?void 0:N.chat}get senderChat(){var $;return($=this.msg)===null||$===void 0?void 0:$.sender_chat}get from(){var $,w,E,X,G,J,A,D,N,W,O,Y,H,L,F,j,M;return(A=(J=(w=($=this.businessConnection)!==null&&$!==void 0?$:this.messageReaction)!==null&&w!==void 0?w:(G=(X=(E=this.chatBoost)===null||E===void 0?void 0:E.boost)!==null&&X!==void 0?X:this.removedChatBoost)===null||G===void 0?void 0:G.source)===null||J===void 0?void 0:J.user)!==null&&A!==void 0?A:(M=(j=(F=(L=(H=(Y=(O=(W=(N=(D=this.callbackQuery)!==null&&D!==void 0?D:this.msg)!==null&&N!==void 0?N:this.inlineQuery)!==null&&W!==void 0?W:this.chosenInlineResult)!==null&&O!==void 0?O:this.shippingQuery)!==null&&Y!==void 0?Y:this.preCheckoutQuery)!==null&&H!==void 0?H:this.myChatMember)!==null&&L!==void 0?L:this.chatMember)!==null&&F!==void 0?F:this.chatJoinRequest)!==null&&j!==void 0?j:this.purchasedPaidMedia)===null||M===void 0?void 0:M.from}get msgId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.message_id)!==null&&w!==void 0?w:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReactionCount)===null||G===void 0?void 0:G.message_id}get chatId(){var $,w,E;return(w=($=this.chat)===null||$===void 0?void 0:$.id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.user_chat_id}get inlineMessageId(){var $,w,E;return(w=($=this.callbackQuery)===null||$===void 0?void 0:$.inline_message_id)!==null&&w!==void 0?w:(E=this.chosenInlineResult)===null||E===void 0?void 0:E.inline_message_id}get businessConnectionId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.business_connection_id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.id)!==null&&X!==void 0?X:(G=this.deletedBusinessMessages)===null||G===void 0?void 0:G.business_connection_id}entities($){var w,E;let X=this.msg;if(X===void 0)return[];let G=(w=X.text)!==null&&w!==void 0?w:X.caption;if(G===void 0)return[];let J=(E=X.entities)!==null&&E!==void 0?E:X.caption_entities;if(J===void 0)return[];if($!==void 0){let A=new Set(JA($));J=J.filter((D)=>A.has(D.type))}return J.map((A)=>({...A,text:G.substring(A.offset,A.offset+A.length)}))}reactions(){let $=[],w=[],E=[],X=[],G=[],J=[],A=[],D=[],N=!1,W=!1,O=this.messageReaction;if(O!==void 0){let{old_reaction:Y,new_reaction:H}=O;for(let L of H)if(L.type==="emoji")$.push(L.emoji);else if(L.type==="custom_emoji")G.push(L.custom_emoji_id);else if(L.type==="paid")N=W=!0;for(let L of Y)if(L.type==="emoji")X.push(L.emoji);else if(L.type==="custom_emoji")D.push(L.custom_emoji_id);else if(L.type==="paid")W=!1;w.push(...$),J.push(...G);for(let L=0;L<X.length;L++){let F=w.length;if(F===0)break;let j=X[L];for(let M=0;M<F;M++)if(j===w[M]){E.push(j),X.splice(L,1),w.splice(M,1),L--;break}}for(let L=0;L<D.length;L++){let F=J.length;if(F===0)break;let j=D[L];for(let M=0;M<F;M++)if(j===J[M]){A.push(j),D.splice(L,1),J.splice(M,1),L--;break}}}return{emoji:$,emojiAdded:w,emojiKept:E,emojiRemoved:X,customEmoji:G,customEmojiAdded:J,customEmojiKept:A,customEmojiRemoved:D,paid:N,paidAdded:W}}has($){return l$.has.filterQuery($)(this)}hasText($){return l$.has.text($)(this)}hasCommand($){return l$.has.command($)(this)}hasReaction($){return l$.has.reaction($)(this)}hasChatType($){return l$.has.chatType($)(this)}hasCallbackQuery($){return l$.has.callbackQuery($)(this)}hasGameQuery($){return l$.has.gameQuery($)(this)}hasInlineQuery($){return l$.has.inlineQuery($)(this)}hasChosenInlineResult($){return l$.has.chosenInlineResult($)(this)}hasPreCheckoutQuery($){return l$.has.preCheckoutQuery($)(this)}hasShippingQuery($){return l$.has.shippingQuery($)(this)}reply($,w,E){var X;let G=this.msg;return this.api.sendMessage(I(this.chatId,"sendMessage"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDraft($,w,E){let X=this.msg;return this.api.sendMessageDraft(I(this.chatId,"sendMessageDraft"),this.update.update_id,$,{...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X===null||X===void 0?void 0:X.message_thread_id}:{},...w},E)}forwardMessage($,w,E){var X;let G=this.msg;return this.api.forwardMessage($,I(this.chatId,"forwardMessage"),I(this.msgId,"forwardMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}forwardMessages($,w,E,X){var G;let J=this.msg;return this.api.forwardMessages($,I(this.chatId,"forwardMessages"),w,{direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}copyMessage($,w,E){var X;let G=this.msg;return this.api.copyMessage($,I(this.chatId,"copyMessage"),I(this.msgId,"copyMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}copyMessages($,w,E,X){var G;let J=this.msg;return this.api.copyMessages($,I(this.chatId,"copyMessages"),w,{direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPhoto($,w,E){var X;let G=this.msg;return this.api.sendPhoto(I(this.chatId,"sendPhoto"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAudio($,w,E){var X;let G=this.msg;return this.api.sendAudio(I(this.chatId,"sendAudio"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDocument($,w,E){var X;let G=this.msg;return this.api.sendDocument(I(this.chatId,"sendDocument"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideo($,w,E){var X;let G=this.msg;return this.api.sendVideo(I(this.chatId,"sendVideo"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAnimation($,w,E){var X;let G=this.msg;return this.api.sendAnimation(I(this.chatId,"sendAnimation"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVoice($,w,E){var X;let G=this.msg;return this.api.sendVoice(I(this.chatId,"sendVoice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideoNote($,w,E){var X;let G=this.msg;return this.api.sendVideoNote(I(this.chatId,"sendVideoNote"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithMediaGroup($,w,E){var X;let G=this.msg;return this.api.sendMediaGroup(I(this.chatId,"sendMediaGroup"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithLocation($,w,E,X){var G;let J=this.msg;return this.api.sendLocation(I(this.chatId,"sendLocation"),$,w,{business_connection_id:this.businessConnectionId,...(J===null||J===void 0?void 0:J.is_topic_message)?{message_thread_id:J.message_thread_id}:{},direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}editMessageLiveLocation($,w,E,X){let G=this.inlineMessageId;return G!==void 0?this.api.editMessageLiveLocationInline(G,$,w,{business_connection_id:this.businessConnectionId,...E},X):this.api.editMessageLiveLocation(I(this.chatId,"editMessageLiveLocation"),I(this.msgId,"editMessageLiveLocation"),$,w,{business_connection_id:this.businessConnectionId,...E},X)}stopMessageLiveLocation($,w){let E=this.inlineMessageId;return E!==void 0?this.api.stopMessageLiveLocationInline(E,{business_connection_id:this.businessConnectionId,...$},w):this.api.stopMessageLiveLocation(I(this.chatId,"stopMessageLiveLocation"),I(this.msgId,"stopMessageLiveLocation"),{business_connection_id:this.businessConnectionId,...$},w)}sendPaidMedia($,w,E,X){var G,J;let A=this.msg;return this.api.sendPaidMedia(I(this.chatId,"sendPaidMedia"),$,w,{business_connection_id:this.businessConnectionId,...(A===null||A===void 0?void 0:A.is_topic_message)?{message_thread_id:A.message_thread_id}:{},direct_messages_topic_id:(J=(G=this.msg)===null||G===void 0?void 0:G.direct_messages_topic)===null||J===void 0?void 0:J.topic_id,...E},X)}replyWithVenue($,w,E,X,G,J){var A;let D=this.msg;return this.api.sendVenue(I(this.chatId,"sendVenue"),$,w,E,X,{business_connection_id:this.businessConnectionId,...(D===null||D===void 0?void 0:D.is_topic_message)?{message_thread_id:D.message_thread_id}:{},direct_messages_topic_id:(A=D===null||D===void 0?void 0:D.direct_messages_topic)===null||A===void 0?void 0:A.topic_id,...G},J)}replyWithContact($,w,E,X){var G;let J=this.msg;return this.api.sendContact(I(this.chatId,"sendContact"),$,w,{business_connection_id:this.businessConnectionId,...(J===null||J===void 0?void 0:J.is_topic_message)?{message_thread_id:J.message_thread_id}:{},direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPoll($,w,E,X){let G=this.msg;return this.api.sendPoll(I(this.chatId,"sendPoll"),$,w,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},...E},X)}replyWithChecklist($,w,E){return this.api.sendChecklist(I(this.businessConnectionId,"sendChecklist"),I(this.chatId,"sendChecklist"),$,w,E)}editMessageChecklist($,w,E){var X,G,J,A;let D=I(this.msg,"editMessageChecklist"),N=(A=(G=(X=D.checklist_tasks_done)===null||X===void 0?void 0:X.checklist_message)!==null&&G!==void 0?G:(J=D.checklist_tasks_added)===null||J===void 0?void 0:J.checklist_message)!==null&&A!==void 0?A:D;return this.api.editMessageChecklist(I(this.businessConnectionId,"editMessageChecklist"),I(N.chat.id,"editMessageChecklist"),I(N.message_id,"editMessageChecklist"),$,w,E)}replyWithDice($,w,E){var X;let G=this.msg;return this.api.sendDice(I(this.chatId,"sendDice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithChatAction($,w,E){let X=this.msg;return this.api.sendChatAction(I(this.chatId,"sendChatAction"),$,{business_connection_id:this.businessConnectionId,message_thread_id:X===null||X===void 0?void 0:X.message_thread_id,...w},E)}react($,w,E){return this.api.setMessageReaction(I(this.chatId,"setMessageReaction"),I(this.msgId,"setMessageReaction"),typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((X)=>typeof X==="string"?{type:"emoji",emoji:X}:X),w,E)}getUserProfilePhotos($,w){return this.api.getUserProfilePhotos(I(this.from,"getUserProfilePhotos").id,$,w)}getUserProfileAudios($,w){return this.api.getUserProfileAudios(I(this.from,"getUserProfileAudios").id,$,w)}setUserEmojiStatus($,w){return this.api.setUserEmojiStatus(I(this.from,"setUserEmojiStatus").id,$,w)}getUserChatBoosts($,w){return this.api.getUserChatBoosts($!==null&&$!==void 0?$:I(this.chatId,"getUserChatBoosts"),I(this.from,"getUserChatBoosts").id,w)}getUserGifts($,w){return this.api.getUserGifts(I(this.from,"getUserGifts").id,$,w)}getChatGifts($,w){return this.api.getChatGifts(I(this.chatId,"getChatGifts"),$,w)}getBusinessConnection($){return this.api.getBusinessConnection(I(this.businessConnectionId,"getBusinessConnection"),$)}getFile($){var w,E,X,G,J,A;let D=I(this.msg,"getFile"),N=D.photo!==void 0?D.photo[D.photo.length-1]:(A=(J=(G=(X=(E=(w=D.animation)!==null&&w!==void 0?w:D.audio)!==null&&E!==void 0?E:D.document)!==null&&X!==void 0?X:D.video)!==null&&G!==void 0?G:D.video_note)!==null&&J!==void 0?J:D.voice)!==null&&A!==void 0?A:D.sticker;return this.api.getFile(I(N,"getFile").file_id,$)}kickAuthor(...$){return this.banAuthor(...$)}banAuthor($,w){return this.api.banChatMember(I(this.chatId,"banAuthor"),I(this.from,"banAuthor").id,$,w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E){return this.api.banChatMember(I(this.chatId,"banChatMember"),$,w,E)}unbanChatMember($,w,E){return this.api.unbanChatMember(I(this.chatId,"unbanChatMember"),$,w,E)}restrictAuthor($,w,E){return this.api.restrictChatMember(I(this.chatId,"restrictAuthor"),I(this.from,"restrictAuthor").id,$,w,E)}restrictChatMember($,w,E,X){return this.api.restrictChatMember(I(this.chatId,"restrictChatMember"),$,w,E,X)}promoteAuthor($,w){return this.api.promoteChatMember(I(this.chatId,"promoteAuthor"),I(this.from,"promoteAuthor").id,$,w)}promoteChatMember($,w,E){return this.api.promoteChatMember(I(this.chatId,"promoteChatMember"),$,w,E)}setChatAdministratorAuthorCustomTitle($,w){return this.api.setChatAdministratorCustomTitle(I(this.chatId,"setChatAdministratorAuthorCustomTitle"),I(this.from,"setChatAdministratorAuthorCustomTitle").id,$,w)}setChatAdministratorCustomTitle($,w,E){return this.api.setChatAdministratorCustomTitle(I(this.chatId,"setChatAdministratorCustomTitle"),$,w,E)}setAuthorTag($,w){return this.api.setChatMemberTag(I(this.chatId,"setChatMemberTag"),I(this.from,"setChatMemberTag").id,$,w)}setChatMemberTag($,w,E){return this.api.setChatMemberTag(I(this.chatId,"setChatMemberTag"),$,w,E)}banChatSenderChat($,w){return this.api.banChatSenderChat(I(this.chatId,"banChatSenderChat"),$,w)}unbanChatSenderChat($,w){return this.api.unbanChatSenderChat(I(this.chatId,"unbanChatSenderChat"),$,w)}setChatPermissions($,w,E){return this.api.setChatPermissions(I(this.chatId,"setChatPermissions"),$,w,E)}exportChatInviteLink($){return this.api.exportChatInviteLink(I(this.chatId,"exportChatInviteLink"),$)}createChatInviteLink($,w){return this.api.createChatInviteLink(I(this.chatId,"createChatInviteLink"),$,w)}editChatInviteLink($,w,E){return this.api.editChatInviteLink(I(this.chatId,"editChatInviteLink"),$,w,E)}createChatSubscriptionInviteLink($,w,E,X){return this.api.createChatSubscriptionInviteLink(I(this.chatId,"createChatSubscriptionInviteLink"),$,w,E,X)}editChatSubscriptionInviteLink($,w,E){return this.api.editChatSubscriptionInviteLink(I(this.chatId,"editChatSubscriptionInviteLink"),$,w,E)}revokeChatInviteLink($,w){return this.api.revokeChatInviteLink(I(this.chatId,"editChatInviteLink"),$,w)}approveChatJoinRequest($,w){return this.api.approveChatJoinRequest(I(this.chatId,"approveChatJoinRequest"),$,w)}declineChatJoinRequest($,w){return this.api.declineChatJoinRequest(I(this.chatId,"declineChatJoinRequest"),$,w)}approveSuggestedPost($,w){return this.api.approveSuggestedPost(I(this.chatId,"approveSuggestedPost"),I(this.msgId,"approveSuggestedPost"),$,w)}declineSuggestedPost($,w){return this.api.declineSuggestedPost(I(this.chatId,"declineSuggestedPost"),I(this.msgId,"declineSuggestedPost"),$,w)}setChatPhoto($,w){return this.api.setChatPhoto(I(this.chatId,"setChatPhoto"),$,w)}deleteChatPhoto($){return this.api.deleteChatPhoto(I(this.chatId,"deleteChatPhoto"),$)}setChatTitle($,w){return this.api.setChatTitle(I(this.chatId,"setChatTitle"),$,w)}setChatDescription($,w){return this.api.setChatDescription(I(this.chatId,"setChatDescription"),$,w)}pinChatMessage($,w,E){return this.api.pinChatMessage(I(this.chatId,"pinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinChatMessage($,w,E){return this.api.unpinChatMessage(I(this.chatId,"unpinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinAllChatMessages($){return this.api.unpinAllChatMessages(I(this.chatId,"unpinAllChatMessages"),$)}leaveChat($){return this.api.leaveChat(I(this.chatId,"leaveChat"),$)}getChat($){return this.api.getChat(I(this.chatId,"getChat"),$)}getChatAdministrators($){return this.api.getChatAdministrators(I(this.chatId,"getChatAdministrators"),$)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($){return this.api.getChatMemberCount(I(this.chatId,"getChatMemberCount"),$)}getAuthor($){return this.api.getChatMember(I(this.chatId,"getAuthor"),I(this.from,"getAuthor").id,$)}getChatMember($,w){return this.api.getChatMember(I(this.chatId,"getChatMember"),$,w)}setChatStickerSet($,w){return this.api.setChatStickerSet(I(this.chatId,"setChatStickerSet"),$,w)}deleteChatStickerSet($){return this.api.deleteChatStickerSet(I(this.chatId,"deleteChatStickerSet"),$)}createForumTopic($,w,E){return this.api.createForumTopic(I(this.chatId,"createForumTopic"),$,w,E)}editForumTopic($,w){let E=I(this.msg,"editForumTopic"),X=I(E.message_thread_id,"editForumTopic");return this.api.editForumTopic(E.chat.id,X,$,w)}closeForumTopic($){let w=I(this.msg,"closeForumTopic"),E=I(w.message_thread_id,"closeForumTopic");return this.api.closeForumTopic(w.chat.id,E,$)}reopenForumTopic($){let w=I(this.msg,"reopenForumTopic"),E=I(w.message_thread_id,"reopenForumTopic");return this.api.reopenForumTopic(w.chat.id,E,$)}deleteForumTopic($){let w=I(this.msg,"deleteForumTopic"),E=I(w.message_thread_id,"deleteForumTopic");return this.api.deleteForumTopic(w.chat.id,E,$)}unpinAllForumTopicMessages($){let w=I(this.msg,"unpinAllForumTopicMessages"),E=I(w.message_thread_id,"unpinAllForumTopicMessages");return this.api.unpinAllForumTopicMessages(w.chat.id,E,$)}editGeneralForumTopic($,w){return this.api.editGeneralForumTopic(I(this.chatId,"editGeneralForumTopic"),$,w)}closeGeneralForumTopic($){return this.api.closeGeneralForumTopic(I(this.chatId,"closeGeneralForumTopic"),$)}reopenGeneralForumTopic($){return this.api.reopenGeneralForumTopic(I(this.chatId,"reopenGeneralForumTopic"),$)}hideGeneralForumTopic($){return this.api.hideGeneralForumTopic(I(this.chatId,"hideGeneralForumTopic"),$)}unhideGeneralForumTopic($){return this.api.unhideGeneralForumTopic(I(this.chatId,"unhideGeneralForumTopic"),$)}unpinAllGeneralForumTopicMessages($){return this.api.unpinAllGeneralForumTopicMessages(I(this.chatId,"unpinAllGeneralForumTopicMessages"),$)}answerCallbackQuery($,w){return this.api.answerCallbackQuery(I(this.callbackQuery,"answerCallbackQuery").id,typeof $==="string"?{text:$}:$,w)}setChatMenuButton($,w){return this.api.setChatMenuButton($,w)}getChatMenuButton($,w){return this.api.getChatMenuButton($,w)}setMyDefaultAdministratorRights($,w){return this.api.setMyDefaultAdministratorRights($,w)}getMyDefaultAdministratorRights($,w){return this.api.getMyDefaultAdministratorRights($,w)}editMessageText($,w,E){var X,G,J,A,D;let N=this.inlineMessageId;return N!==void 0?this.api.editMessageTextInline(N,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageText(I(this.chatId,"editMessageText"),I((A=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&A!==void 0?A:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageText"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageCaption($,w){var E,X,G,J,A;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageCaptionInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageCaption(I(this.chatId,"editMessageCaption"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"editMessageCaption"),{business_connection_id:this.businessConnectionId,...$},w)}editMessageMedia($,w,E){var X,G,J,A,D;let N=this.inlineMessageId;return N!==void 0?this.api.editMessageMediaInline(N,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageMedia(I(this.chatId,"editMessageMedia"),I((A=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&A!==void 0?A:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageMedia"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageReplyMarkup($,w){var E,X,G,J,A;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageReplyMarkupInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageReplyMarkup(I(this.chatId,"editMessageReplyMarkup"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"editMessageReplyMarkup"),{business_connection_id:this.businessConnectionId,...$},w)}stopPoll($,w){var E,X,G,J,A;return this.api.stopPoll(I(this.chatId,"stopPoll"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"stopPoll"),{business_connection_id:this.businessConnectionId,...$},w)}deleteMessage($){var w,E,X,G,J;return this.api.deleteMessage(I(this.chatId,"deleteMessage"),I((G=(E=(w=this.msg)===null||w===void 0?void 0:w.message_id)!==null&&E!==void 0?E:(X=this.messageReaction)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReactionCount)===null||J===void 0?void 0:J.message_id,"deleteMessage"),$)}deleteMessages($,w){return this.api.deleteMessages(I(this.chatId,"deleteMessages"),$,w)}deleteBusinessMessages($,w){return this.api.deleteBusinessMessages(I(this.businessConnectionId,"deleteBusinessMessages"),$,w)}setBusinessAccountName($,w,E){return this.api.setBusinessAccountName(I(this.businessConnectionId,"setBusinessAccountName"),$,w,E)}setBusinessAccountUsername($,w){return this.api.setBusinessAccountUsername(I(this.businessConnectionId,"setBusinessAccountUsername"),$,w)}setBusinessAccountBio($,w){return this.api.setBusinessAccountBio(I(this.businessConnectionId,"setBusinessAccountBio"),$,w)}setBusinessAccountProfilePhoto($,w,E){return this.api.setBusinessAccountProfilePhoto(I(this.businessConnectionId,"setBusinessAccountProfilePhoto"),$,w,E)}removeBusinessAccountProfilePhoto($,w){return this.api.removeBusinessAccountProfilePhoto(I(this.businessConnectionId,"removeBusinessAccountProfilePhoto"),$,w)}setBusinessAccountGiftSettings($,w,E){return this.api.setBusinessAccountGiftSettings(I(this.businessConnectionId,"setBusinessAccountGiftSettings"),$,w,E)}getBusinessAccountStarBalance($){return this.api.getBusinessAccountStarBalance(I(this.businessConnectionId,"getBusinessAccountStarBalance"),$)}transferBusinessAccountStars($,w){return this.api.transferBusinessAccountStars(I(this.businessConnectionId,"transferBusinessAccountStars"),$,w)}getBusinessAccountGifts($,w){return this.api.getBusinessAccountGifts(I(this.businessConnectionId,"getBusinessAccountGifts"),$,w)}convertGiftToStars($,w){return this.api.convertGiftToStars(I(this.businessConnectionId,"convertGiftToStars"),$,w)}upgradeGift($,w,E){return this.api.upgradeGift(I(this.businessConnectionId,"upgradeGift"),$,w,E)}transferGift($,w,E,X){return this.api.transferGift(I(this.businessConnectionId,"transferGift"),$,w,E,X)}postStory($,w,E,X){return this.api.postStory(I(this.businessConnectionId,"postStory"),$,w,E,X)}repostStory($,w,E){var X;let G=I((X=this.msg)===null||X===void 0?void 0:X.story,"repostStory");return this.api.repostStory(I(this.businessConnectionId,"repostStory"),G.chat.id,G.id,$,w,E)}editStory($,w,E,X){return this.api.editStory(I(this.businessConnectionId,"editStory"),$,w,E,X)}deleteStory($,w){return this.api.deleteStory(I(this.businessConnectionId,"deleteStory"),$,w)}replyWithSticker($,w,E){var X;let G=this.msg;return this.api.sendSticker(I(this.chatId,"sendSticker"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}getCustomEmojiStickers($){var w,E;return this.api.getCustomEmojiStickers(((E=(w=this.msg)===null||w===void 0?void 0:w.entities)!==null&&E!==void 0?E:[]).filter((X)=>X.type==="custom_emoji").map((X)=>X.custom_emoji_id),$)}replyWithGift($,w,E){return this.api.sendGift(I(this.from,"sendGift").id,$,w,E)}giftPremiumSubscription($,w,E,X){return this.api.giftPremiumSubscription(I(this.from,"giftPremiumSubscription").id,$,w,E,X)}replyWithGiftToChannel($,w,E){return this.api.sendGiftToChannel(I(this.chat,"sendGift").id,$,w,E)}answerInlineQuery($,w,E){return this.api.answerInlineQuery(I(this.inlineQuery,"answerInlineQuery").id,$,w,E)}savePreparedInlineMessage($,w,E){return this.api.savePreparedInlineMessage(I(this.from,"savePreparedInlineMessage").id,$,w,E)}replyWithInvoice($,w,E,X,G,J,A){var D;let N=this.msg;return this.api.sendInvoice(I(this.chatId,"sendInvoice"),$,w,E,X,G,{...(N===null||N===void 0?void 0:N.is_topic_message)?{message_thread_id:N.message_thread_id}:{},direct_messages_topic_id:(D=N===null||N===void 0?void 0:N.direct_messages_topic)===null||D===void 0?void 0:D.topic_id,...J},A)}answerShippingQuery($,w,E){return this.api.answerShippingQuery(I(this.shippingQuery,"answerShippingQuery").id,$,w,E)}answerPreCheckoutQuery($,w,E){return this.api.answerPreCheckoutQuery(I(this.preCheckoutQuery,"answerPreCheckoutQuery").id,$,typeof w==="string"?{error_message:w}:w,E)}refundStarPayment($){var w;return this.api.refundStarPayment(I(this.from,"refundStarPayment").id,I((w=this.msg)===null||w===void 0?void 0:w.successful_payment,"refundStarPayment").telegram_payment_charge_id,$)}editUserStarSubscription($,w,E){return this.api.editUserStarSubscription(I(this.from,"editUserStarSubscription").id,$,w,E)}verifyUser($,w){return this.api.verifyUser(I(this.from,"verifyUser").id,$,w)}verifyChat($,w){return this.api.verifyChat(I(this.chatId,"verifyChat"),$,w)}removeUserVerification($){return this.api.removeUserVerification(I(this.from,"removeUserVerification").id,$)}removeChatVerification($){return this.api.removeChatVerification(I(this.chatId,"removeChatVerification"),$)}readBusinessMessage($){return this.api.readBusinessMessage(I(this.businessConnectionId,"readBusinessMessage"),I(this.chatId,"readBusinessMessage"),I(this.msgId,"readBusinessMessage"),$)}setPassportDataErrors($,w){return this.api.setPassportDataErrors(I(this.from,"setPassportDataErrors").id,$,w)}replyWithGame($,w,E){let X=this.msg;return this.api.sendGame(I(this.chatId,"sendGame"),$,{business_connection_id:this.businessConnectionId,...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X.message_thread_id}:{},...w},E)}}HH.Context=l$;l$.has=e1;function I($,w){if($===void 0)throw Error(`Missing information for API call to ${w}`);return $}function HE($){return JA($).map((w)=>typeof w==="string"?(E)=>E===w?w:null:(E)=>E.match(w))}function LE($,w,E){for(let X of E){let G=X(w);if(G)return $.match=G,!0}return!1}function JA($){return Array.isArray($)?$:[$]}});var wN=Z((MH)=>{Object.defineProperty(MH,"__esModule",{value:!0});MH.Composer=MH.BotError=void 0;MH.run=jH;var _1=AA();class $N extends Error{constructor($,w){super(DS($));if(this.error=$,this.ctx=w,this.name="BotError",$ instanceof Error)this.stack=$.stack}}MH.BotError=$N;function DS($){let w;if($ instanceof Error)w=`${$.name} in middleware: ${$.message}`;else{let E=typeof $;switch(w=`Non-error value of type ${E} thrown in middleware`,E){case"bigint":case"boolean":case"number":case"symbol":w+=`: ${$}`;break;case"string":w+=`: ${String($).substring(0,50)}`;break;default:w+="!";break}}return w}function yG($){return typeof $==="function"?$:(w,E)=>$.middleware()(w,E)}function FH($,w){return async(E,X)=>{let G=!1;await $(E,async()=>{if(G)throw Error("`next` already called before!");else G=!0;await w(E,X)})}}function e8($,w){return w()}var NS=()=>Promise.resolve();async function jH($,w){await $(w,NS)}class FE{constructor(...$){this.handler=$.length===0?e8:$.map(yG).reduce(FH)}middleware(){return this.handler}use(...$){let w=new FE(...$);return this.handler=FH(this.handler,yG(w)),w}on($,...w){return this.filter(_1.Context.has.filterQuery($),...w)}hears($,...w){return this.filter(_1.Context.has.text($),...w)}command($,...w){return this.filter(_1.Context.has.command($),...w)}reaction($,...w){return this.filter(_1.Context.has.reaction($),...w)}chatType($,...w){return this.filter(_1.Context.has.chatType($),...w)}callbackQuery($,...w){return this.filter(_1.Context.has.callbackQuery($),...w)}gameQuery($,...w){return this.filter(_1.Context.has.gameQuery($),...w)}inlineQuery($,...w){return this.filter(_1.Context.has.inlineQuery($),...w)}chosenInlineResult($,...w){return this.filter(_1.Context.has.chosenInlineResult($),...w)}preCheckoutQuery($,...w){return this.filter(_1.Context.has.preCheckoutQuery($),...w)}shippingQuery($,...w){return this.filter(_1.Context.has.shippingQuery($),...w)}filter($,...w){let E=new FE(...w);return this.branch($,E,e8),E}drop($,...w){return this.filter(async(E)=>!await $(E),...w)}fork(...$){let w=new FE(...$),E=yG(w);return this.use((X,G)=>Promise.all([G(),jH(E,X)])),w}lazy($){return this.use(async(w,E)=>{let X=await $(w),G=Array.isArray(X)?X:[X];await yG(new FE(...G))(w,E)})}route($,w,E=e8){return this.lazy(async(X)=>{var G;let J=await $(X);return(G=J===void 0||!w[J]?E:w[J])!==null&&G!==void 0?G:[]})}branch($,w,E){return this.lazy(async(X)=>await $(X)?w:E)}errorBoundary($,...w){let E=new FE(...w),X=yG(E);return this.use(async(G,J)=>{let A=!1,D=()=>(A=!0,Promise.resolve());try{await X(G,D)}catch(N){A=!1,await $(new $N(N,G),D)}if(A)await J()}),E}}MH.Composer=FE});var TH=Z((pe,zH)=>{var WX=1000,OX=WX*60,UX=OX*60,jE=UX*24,US=jE*7,YS=jE*365.25;zH.exports=function($,w){w=w||{};var E=typeof $;if(E==="string"&&$.length>0)return HS($);else if(E==="number"&&isFinite($))return w.long?FS($):LS($);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify($))};function HS($){if($=String($),$.length>100)return;var w=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec($);if(!w)return;var E=parseFloat(w[1]),X=(w[2]||"ms").toLowerCase();switch(X){case"years":case"year":case"yrs":case"yr":case"y":return E*YS;case"weeks":case"week":case"w":return E*US;case"days":case"day":case"d":return E*jE;case"hours":case"hour":case"hrs":case"hr":case"h":return E*UX;case"minutes":case"minute":case"mins":case"min":case"m":return E*OX;case"seconds":case"second":case"secs":case"sec":case"s":return E*WX;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return E;default:return}}function LS($){var w=Math.abs($);if(w>=jE)return Math.round($/jE)+"d";if(w>=UX)return Math.round($/UX)+"h";if(w>=OX)return Math.round($/OX)+"m";if(w>=WX)return Math.round($/WX)+"s";return $+"ms"}function FS($){var w=Math.abs($);if(w>=jE)return DA($,w,jE,"day");if(w>=UX)return DA($,w,UX,"hour");if(w>=OX)return DA($,w,OX,"minute");if(w>=WX)return DA($,w,WX,"second");return $+" ms"}function DA($,w,E,X){var G=w>=E*1.5;return Math.round($/E)+" "+X+(G?"s":"")}});var EN=Z((oe,BH)=>{function jS($){E.debug=E,E.default=E,E.coerce=N,E.disable=A,E.enable=G,E.enabled=D,E.humanize=TH(),E.destroy=W,Object.keys($).forEach((O)=>{E[O]=$[O]}),E.names=[],E.skips=[],E.formatters={};function w(O){let Y=0;for(let H=0;H<O.length;H++)Y=(Y<<5)-Y+O.charCodeAt(H),Y|=0;return E.colors[Math.abs(Y)%E.colors.length]}E.selectColor=w;function E(O){let Y,H=null,L,F;function j(...M){if(!j.enabled)return;let z=j,B=Number(new Date),Q=B-(Y||B);if(z.diff=Q,z.prev=Y,z.curr=B,Y=B,M[0]=E.coerce(M[0]),typeof M[0]!=="string")M.unshift("%O");let k=0;M[0]=M[0].replace(/%([a-zA-Z%])/g,(C,n)=>{if(C==="%%")return"%";k++;let T0=E.formatters[n];if(typeof T0==="function"){let f0=M[k];C=T0.call(z,f0),M.splice(k,1),k--}return C}),E.formatArgs.call(z,M),(z.log||E.log).apply(z,M)}if(j.namespace=O,j.useColors=E.useColors(),j.color=E.selectColor(O),j.extend=X,j.destroy=E.destroy,Object.defineProperty(j,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(H!==null)return H;if(L!==E.namespaces)L=E.namespaces,F=E.enabled(O);return F},set:(M)=>{H=M}}),typeof E.init==="function")E.init(j);return j}function X(O,Y){let H=E(this.namespace+(typeof Y>"u"?":":Y)+O);return H.log=this.log,H}function G(O){E.save(O),E.namespaces=O,E.names=[],E.skips=[];let Y=(typeof O==="string"?O:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let H of Y)if(H[0]==="-")E.skips.push(H.slice(1));else E.names.push(H)}function J(O,Y){let H=0,L=0,F=-1,j=0;while(H<O.length)if(L<Y.length&&(Y[L]===O[H]||Y[L]==="*"))if(Y[L]==="*")F=L,j=H,L++;else H++,L++;else if(F!==-1)L=F+1,j++,H=j;else return!1;while(L<Y.length&&Y[L]==="*")L++;return L===Y.length}function A(){let O=[...E.names,...E.skips.map((Y)=>"-"+Y)].join(",");return E.enable(""),O}function D(O){for(let Y of E.skips)if(J(O,Y))return!1;for(let Y of E.names)if(J(O,Y))return!0;return!1}function N(O){if(O instanceof Error)return O.stack||O.message;return O}function W(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return E.enable(E.load()),E}BH.exports=jS});var IH=Z((QH,NA)=>{QH.formatArgs=RS;QH.save=zS;QH.load=TS;QH.useColors=MS;QH.storage=BS();QH.destroy=(()=>{let $=!1;return()=>{if(!$)$=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();QH.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function MS(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let $;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&($=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt($[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function RS($){if($[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+$[0]+(this.useColors?"%c ":" ")+"+"+NA.exports.humanize(this.diff),!this.useColors)return;let w="color: "+this.color;$.splice(1,0,w,"color: inherit");let E=0,X=0;$[0].replace(/%[a-zA-Z%]/g,(G)=>{if(G==="%%")return;if(E++,G==="%c")X=E}),$.splice(X,0,w)}QH.log=console.debug||console.log||(()=>{});function zS($){try{if($)QH.storage.setItem("debug",$);else QH.storage.removeItem("debug")}catch(w){}}function TS(){let $;try{$=QH.storage.getItem("debug")||QH.storage.getItem("DEBUG")}catch(w){}if(!$&&typeof process<"u"&&"env"in process)$=process.env.DEBUG;return $}function BS(){try{return localStorage}catch($){}}NA.exports=EN()(QH);var{formatters:QS}=NA.exports;QS.j=function($){try{return JSON.stringify($)}catch(w){return"[UnexpectedJSONParseError]: "+w.message}}});var VH={};Ww(VH,{default:()=>fS,createSupportsColor:()=>XN});import GN from"process";import bS from"os";import KH from"tty";function L1($,w=globalThis.Deno?globalThis.Deno.args:GN.argv){let E=$.startsWith("-")?"":$.length===1?"-":"--",X=w.indexOf(E+$),G=w.indexOf("--");return X!==-1&&(G===-1||X<G)}function ZS(){if(!("FORCE_COLOR"in m0))return;if(m0.FORCE_COLOR==="true")return 1;if(m0.FORCE_COLOR==="false")return 0;if(m0.FORCE_COLOR.length===0)return 1;let $=Math.min(Number.parseInt(m0.FORCE_COLOR,10),3);if(![0,1,2,3].includes($))return;return $}function CS($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function _S($,{streamIsTTY:w,sniffFlags:E=!0}={}){let X=ZS();if(X!==void 0)WA=X;let G=E?WA:X;if(G===0)return 0;if(E){if(L1("color=16m")||L1("color=full")||L1("color=truecolor"))return 3;if(L1("color=256"))return 2}if("TF_BUILD"in m0&&"AGENT_NAME"in m0)return 1;if($&&!w&&G===void 0)return 0;let J=G||0;if(m0.TERM==="dumb")return J;if(GN.platform==="win32"){let A=bS.release().split(".");if(Number(A[0])>=10&&Number(A[2])>=10586)return Number(A[2])>=14931?3:2;return 1}if("CI"in m0){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((A)=>(A in m0)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((A)=>(A in m0))||m0.CI_NAME==="codeship")return 1;return J}if("TEAMCITY_VERSION"in m0)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(m0.TEAMCITY_VERSION)?1:0;if(m0.COLORTERM==="truecolor")return 3;if(m0.TERM==="xterm-kitty")return 3;if(m0.TERM==="xterm-ghostty")return 3;if(m0.TERM==="wezterm")return 3;if("TERM_PROGRAM"in m0){let A=Number.parseInt((m0.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(m0.TERM_PROGRAM){case"iTerm.app":return A>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(m0.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(m0.TERM))return 1;if("COLORTERM"in m0)return 1;return J}function XN($,w={}){let E=_S($,{streamIsTTY:$&&$.isTTY,...w});return CS(E)}var m0,WA,vS,fS;var PH=R(()=>{({env:m0}=GN);if(L1("no-color")||L1("no-colors")||L1("color=false")||L1("color=never"))WA=0;else if(L1("color")||L1("colors")||L1("color=true")||L1("color=always"))WA=1;vS={stdout:XN({isTTY:KH.isatty(1)}),stderr:XN({isTTY:KH.isatty(2)})},fS=vS});var bH=Z((SH,UA)=>{var xS=V$("tty"),OA=V$("util");SH.init=mS;SH.log=hS;SH.formatArgs=gS;SH.save=cS;SH.load=nS;SH.useColors=yS;SH.destroy=OA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");SH.colors=[6,2,3,4,5,1];try{let $=(PH(),CO(VH));if($&&($.stderr||$).level>=2)SH.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch($){}SH.inspectOpts=Object.keys(process.env).filter(($)=>{return/^debug_/i.test($)}).reduce(($,w)=>{let E=w.substring(6).toLowerCase().replace(/_([a-z])/g,(G,J)=>{return J.toUpperCase()}),X=process.env[w];if(/^(yes|on|true|enabled)$/i.test(X))X=!0;else if(/^(no|off|false|disabled)$/i.test(X))X=!1;else if(X==="null")X=null;else X=Number(X);return $[E]=X,$},{});function yS(){return"colors"in SH.inspectOpts?Boolean(SH.inspectOpts.colors):xS.isatty(process.stderr.fd)}function gS($){let{namespace:w,useColors:E}=this;if(E){let X=this.color,G="\x1B[3"+(X<8?X:"8;5;"+X),J=` ${G};1m${w} \x1B[0m`;$[0]=J+$[0].split(`
376
+ <b>Command:</b> <code>${J.slice(0,200)}</code>`;if("sendWithButtons"in $.adapter)await $.adapter.sendWithButtons($.chatId,H,Y,{threadId:$.threadId,parseMode:"html"});else await $.adapter.send($.chatId,H,{threadId:$.threadId,parseMode:"html"});let L=await $.permissionManager.waitFor(O);if(w.respondPermission(O,L?"approved":"denied"),X)X.unfreeze($.session.id);N.resume();continue}if(D.type==="result"){A=D.data.runtimeSessionId;break}if(D.type==="error")throw Error(D.data)}}finally{N.clear()}return{output:G.trim()||"(no output)",runtimeSessionId:A}}function cS($,w){let E=!1,X=null;function G(){if(X)clearTimeout(X);if(E)return;X=setTimeout(async()=>{nG.warn("Idle timeout \u2014 closing agent session",{sessionId:$}),await w.close().catch(()=>{}),hG.delete($),await sw($,{status:"error",last_error:"Idle timeout",last_activity_at:new Date})},uS)}return G(),{reset(){G()},pause(){if(E=!0,X)clearTimeout(X),X=null},resume(){E=!1,G()},clear(){if(X)clearTimeout(X),X=null}}}async function c7($){let w=hG.get($);if(w)hG.delete($),await w.close().catch(()=>{})}async function r7(){let{listRegisteredBackends:$,createBackend:w}=await Promise.resolve().then(() => ($D(),b7));for(let E of $())try{let G=await w(E).preflight();if(!G.ok)nG.warn(`Agent backend preflight failed: ${E}`,{error:G.error});else nG.info(`Agent backend ready: ${E}`)}catch(X){nG.warn(`Agent backend preflight error: ${E}`,{err:X})}}var nG,uS=600000,hG;var t7=T(()=>{z$();$D();uG();nG=B0("gateway:runner"),hG=new Map});class pW{windows=new Map;allow($){let w=Date.now(),E=w-60000,X=this.windows.get($)??[];if(X=X.filter((G)=>G>E),X.length>=20)return this.windows.set($,X),!1;return X.push(w),this.windows.set($,X),!0}clear($){this.windows.delete($)}}function dW($){return $.replace(rS,(w)=>`${"*".repeat(w.length-4)}${w.slice(-4)}`)}var rS;var o7=T(()=>{rS=/\b(sk-[A-Za-z0-9\-_]{20,}|xox[bpoa]-[A-Za-z0-9-]+|ghp_[A-Za-z0-9]{36}|AIza[A-Za-z0-9\-_]{35}|[0-9]{8,10}:[A-Za-z0-9\-_]{35})\b/g});function d7($){if($.endsWith("codex"))return"codex";if($.endsWith("cursor"))return"cursor";return"claude"}function m7($){if($==="running")return"\u26A1";if($==="error")return"\u274C";if($==="stopped")return"\u26D4";return"\uD83D\uDCA4"}function i7($){if($==="critical")return"\uD83D\uDD34";if($==="high")return"\uD83D\uDFE0";if($==="normal")return"\uD83D\uDFE1";return"\u26AA"}function p7($){if($==="done")return"\u2705";if($==="review")return"\uD83D\uDC40";if($==="doing")return"\uD83D\uDD28";if($==="blocked")return"\uD83D\uDEA7";if($==="changes_requested")return"\uD83D\uDD01";if($==="cancelled")return"\u274C";return"\uD83D\uDCCB"}function tS($){let w=["<b>ORC Gateway Commands</b>","","<b>Navigation</b>","/help \u2014 this message","/status \u2014 system overview","/mode [direct|agent:claude|agent:codex|agent:cursor|multi|job:&lt;name&gt;] \u2014 switch mode","/cwd &lt;path&gt; \u2014 set working directory","","<b>Tasks</b>","/tasks \u2014 list active tasks","/task &lt;id&gt; \u2014 task details","/approve &lt;id&gt; [note] \u2014 approve task or permission","/reject &lt;id&gt; [note] \u2014 reject task or deny permission","/assign &lt;task-id&gt; &lt;agent&gt; \u2014 assign task to agent session","","<b>Jobs</b>","/jobs \u2014 list jobs","/run &lt;name&gt; \u2014 trigger a job","","<b>Memory</b>","/mem &lt;query&gt; \u2014 search memories","","<b>Agents</b>","/agent claude|codex|cursor \u2014 switch active agent","/sessions \u2014 list all agent sessions","/session new|list|switch &lt;id&gt;|stop \u2014 session lifecycle"];if($.startsWith("agent:")||$==="multi")w.push("","<i>Current mode: agent \u2014 send any text to the active agent</i>");return w.join(`
377
+ `)}async function l7($){let w=$.rawText.trim();if(!w.startsWith("/"))return null;let E=w.split(/\s+/),X=E[0]??"",G=E.slice(1).join(" ").trim();if(X==="/start"||X==="/help")return{html:tS($.currentMode??"direct")};if(X==="/status"){let A=await mW(5),N=await UX($.chatKey),D=await iW(5),O=await FE($.chatKey),W=["<b>ORC Status</b>","",`Mode: <code>${$.currentMode??"direct"}</code>`,`Working dir: <code>${$.currentWorkingDir??"(unset)"}</code>`,"",`<b>Tasks</b>: ${A.length} active`,`<b>Jobs</b>: ${D.length} defined`,`<b>Sessions</b>: ${N.length} total`];if(O)W.push(`<b>Active session</b>: ${O.backend} ${m7(O.status)} <code>${O.id.slice(-6)}</code>`);return{html:W.join(`
378
+ `)}}if(X==="/mode"){if(!G)return{text:"Usage: /mode <direct|agent:claude|agent:codex|agent:cursor|multi|job:name>"};let A=G;return await rW($.chatKey,A),{text:`Mode updated to ${A}`,mode:A}}if(X==="/cwd"){if(!G)return{text:"Usage: /cwd <absolute-path>"};await Z7($.chatKey,G);let A=await FE($.chatKey);if(A)await sw(A.id,{cwd:G});return{text:`Working directory set to ${G}`}}if(X==="/agent"){if(G!=="claude"&&G!=="codex"&&G!=="cursor")return{text:"Usage: /agent <claude|codex|cursor>"};let A=`agent:${G}`;return await rW($.chatKey,A),{text:`Agent mode set to ${A}`,mode:A}}if(X==="/tasks"){let A=await mW();if(A.length===0)return{text:"No active tasks."};let N=["<b>Active Tasks</b>",""];for(let D of A){let O=D.claimed_by?` [${D.claimed_by}]`:"";N.push(`${p7(D.status)} ${i7(D.priority)} <code>${D.id.slice(-6)}</code> ${D.title}${O}`)}return{html:N.join(`
379
+ `)}}if(X==="/task"){if(!G)return{text:"Usage: /task <id>"};let A=await gG(G);if(!A)return{text:`Task not found: ${G}`};let N=[`<b>${A.title}</b>`,`ID: <code>${A.id}</code>`,`Status: ${p7(A.status)} ${A.status}`,`Priority: ${i7(A.priority)} ${A.priority}`];if(A.claimed_by)N.push(`Agent: ${A.claimed_by}`);if(A.body)N.push("",A.body.slice(0,500));let D=A.status==="review"?[[{label:"\u2705 Approve",value:`task:approve:${A.id}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${A.id}`}]]:void 0;return{html:N.join(`
380
+ `),buttons:D}}if(X==="/approve"){if(!G)return{text:"Usage: /approve <task-or-permission-id> [note]"};let[A,...N]=G.split(/\s+/);if(!A)return{text:"Usage: /approve <task-or-permission-id> [note]"};let D=N.join(" ").trim(),O=await oW(A);if(O)return{text:`Permission ${O.id.slice(-6)} queued for approval \u2014 use the button or wait for agent context.`};let W=await gG(A);if(!W)return{text:`No task or permission found for ${A}`};return await f7(W.id,D||"Approved from gateway"),{text:`\u2705 Approved task [${W.id.slice(-6)}] ${W.title}`}}if(X==="/reject"){if(!G)return{text:"Usage: /reject <task-or-permission-id> [note]"};let[A,...N]=G.split(/\s+/);if(!A)return{text:"Usage: /reject <task-or-permission-id> [note]"};let D=N.join(" ").trim(),O=await oW(A);if(O)return{text:`Permission ${O.id.slice(-6)} denial queued \u2014 use the button or wait for agent context.`};let W=await gG(A);if(!W)return{text:`No task or permission found for ${A}`};return await v7(W.id,D||"Changes requested from gateway"),{text:`\uD83D\uDD01 Changes requested for [${W.id.slice(-6)}] ${W.title}`}}if(X==="/assign"){let[A,N]=G.split(/\s+/);if(!A||!N)return{text:"Usage: /assign <task-id> <agent>"};if(N!=="claude"&&N!=="codex"&&N!=="cursor")return{text:"Agent must be: claude, codex, or cursor"};let D=await gG(A);if(!D)return{text:`Task not found: ${A}`};let W=(await UX($.chatKey)).find((J)=>J.backend===N&&J.status!=="stopped");if(!W)return{text:`No active ${N} session found. Start one with /agent ${N} then send a message.`};return await g7(W.id,D.id),{text:`Assigned [${D.id.slice(-6)}] ${D.title} \u2192 ${N} session [${W.id.slice(-6)}]`}}if(X==="/jobs"){let A=await iW();if(A.length===0)return{text:"No jobs defined."};let N=["<b>Jobs</b>",""];for(let D of A){let O=D.last_run_at?"ran":"never";N.push(`\u2022 <code>${D.name}</code> (${D.trigger_type}) \u2014 ${O} \xD7 ${D.run_count}`)}return{html:N.join(`
381
+ `)}}if(X==="/run"){if(!G)return{text:"Usage: /run <job-name>"};let A=await wD(G);if(!A)return{text:`Job not found: ${G}`};let N=await Nw({jobId:A.id,triggerBy:"bridge-msg"});return{text:`Triggered ${A.name} \u2192 run ${N.slice(-6)}`}}if(X==="/mem"){if(!G)return{text:"Usage: /mem <query>"};let A=await x7(G);if(A.length===0)return{text:"No matching memories."};let N=["<b>Memories</b>",""];for(let D of A){let O=D.title??D.content.slice(0,40);N.push(`\u2022 [${D.id.slice(-6)}] <b>${O}</b>`),N.push(` ${D.content.slice(0,120)}${D.content.length>120?"\u2026":""}`)}return{html:N.join(`
382
+ `)}}if(X==="/sessions"){let A=await UX($.chatKey);if(A.length===0)return{text:"No agent sessions yet."};let N=await FE($.chatKey),D=["<b>Agent Sessions</b>",""];for(let O of A){let W=O.id===N?.id?"\u25B6 ":" ",J=O.task_id?` task:${O.task_id.slice(-6)}`:"";if(D.push(`${W}${m7(O.status)} <code>${O.id.slice(-6)}</code> ${O.backend}${J}`),O.cwd)D.push(` cwd: <code>${O.cwd}</code>`)}return{html:D.join(`
383
+ `)}}if(X==="/session"){let[A,...N]=E.slice(1);if(!A)return{text:"Usage: /session <new|list|switch <id>|stop>"};if(A==="new"){let D=d7($.currentMode??"agent:claude"),O=await tW({chatKey:$.chatKey,backend:D,cwd:$.currentWorkingDir??void 0,mode:$.currentMode??`agent:${D}`,title:`Session ${r().slice(-6)}`});return await yG($.chatKey,O.id),{text:`Created and activated ${D} session [${O.id.slice(-6)}]`}}if(A==="list"){let D=await UX($.chatKey);if(D.length===0)return{text:"No gateway sessions yet."};let O=await FE($.chatKey);return{text:D.map((J,Y)=>{return`${J.id===O?.id?"*":" "}${Y+1}. [${J.id.slice(-6)}] ${J.backend} ${J.status} cwd=${J.cwd??"(unset)"}`}).join(`
384
+ `)}}if(A==="switch"){let D=N.join(" ").trim();if(!D)return{text:"Usage: /session switch <id-or-index>"};let O=await UX($.chatKey),W=/^\d+$/.test(D)?O[Number(D)-1]:O.find((J)=>J.id===D||J.id.endsWith(D));if(!W)return{text:`Session not found: ${D}`};return await yG($.chatKey,W.id),{text:`Active session: [${W.id.slice(-6)}] ${W.backend}`}}if(A==="stop"){let D=await FE($.chatKey);if(D)await sw(D.id,{status:"stopped"});return await yG($.chatKey,null),{text:"Cleared active gateway session."}}return{text:"Usage: /session <new|list|switch <id>|stop>"}}return{text:`Unknown command: ${X}
385
+
386
+ Type /help for available commands.`}}async function s7($){let w=await FE($.chatKey),E=d7($.mode);if(w&&w.backend===E&&w.status!=="stopped")return w;let X=await tW({chatKey:$.chatKey,backend:E,cwd:$.cwd??void 0,mode:$.mode,title:`Session ${r().slice(-6)}`});return await yG($.chatKey,X.id),X}var a7=T(()=>{B$();cE();uG()});class lW{pending=new Map;waitFor($){return new Promise((w)=>{let E=setTimeout(()=>{if(this.pending.delete($))w(!1)},300000);this.pending.set($,{resolve:w,timer:E})})}resolve($,w){let E=this.pending.get($);if(!E)return!1;return clearTimeout(E.timer),this.pending.delete($),E.resolve(w),!0}denyAll(){for(let[$,w]of this.pending)clearTimeout(w.timer),w.resolve(!1),this.pending.delete($)}hasPending($){return this.pending.has($)}}class ED{states=new Map;adapter;constructor($){this.adapter=$}static supports($){return"updateMessage"in $&&typeof $.updateMessage==="function"}async init($,w,E,X){this.states.set($,{chatId:w,msgId:E,lastText:X,lastEditAt:0,frozen:!1,degraded:!1,pendingText:null,pendingTimer:null})}async update($,w){let E=this.states.get($);if(!E||E.degraded)return;let X=w.length>3000?`${w.slice(0,3000)}
387
+ \u2026`:w;if(E.frozen){E.pendingText=X;return}let G=Date.now(),A=Math.abs(X.length-E.lastText.length),N=G-E.lastEditAt;if(N<1500||A<30){if(E.pendingText=X,!E.pendingTimer){let D=Math.max(1500-N,100);E.pendingTimer=setTimeout(()=>this.flushPending($),D)}return}await this.doEdit(E,X)}freeze($){let w=this.states.get($);if(w)w.frozen=!0}unfreeze($){let w=this.states.get($);if(!w)return;if(w.frozen=!1,w.pendingText)this.flushPending($)}async finalize($,w){let E=this.states.get($);if(!E)return;if(E.pendingTimer)clearTimeout(E.pendingTimer),E.pendingTimer=null;let X=w.length>3000?`${w.slice(0,3000)}
388
+ \u2026`:w;if(!E.degraded&&X!==E.lastText)await this.doEdit(E,X);this.states.delete($)}cleanup($){let w=this.states.get($);if(w?.pendingTimer)clearTimeout(w.pendingTimer);this.states.delete($)}async flushPending($){let w=this.states.get($);if(!w||!w.pendingText||w.frozen)return;w.pendingTimer=null;let E=w.pendingText;w.pendingText=null,await this.doEdit(w,E)}async doEdit($,w){try{await this.adapter.updateMessage($.chatId,$.msgId,w),$.lastText=w,$.lastEditAt=Date.now()}catch{$.degraded=!0}}}class sW{locked=new Set;tryAcquire($){if(this.locked.has($))return!1;return this.locked.add($),!0}release($){this.locked.delete($)}isLocked($){return this.locked.has($)}}function mS($){let w=G0(),E=w.gateway.slack.bot_token,X=w.gateway.slack.app_token;if(!E||!X)throw Error("Slack bot_token and app_token are required.");let G=null,A=null,N=!1,D=new Map;function O(M){let R=w.gateway.slack.authorized_users.map(String);return R.length>0&&R.includes(M)}function W(M){let R=Date.now();if(D.has(M))return!0;D.set(M,R);for(let[B,I]of D)if(R-I>oS)D.delete(B);return!1}function J(M){if(!M)return!1;return parseFloat(M)*1000<$}async function Y(){let M=await fetch("https://slack.com/api/apps.connections.open",{method:"POST",headers:{Authorization:`Bearer ${X}`}}),R=await M.json();if(!M.ok||!R.ok||!R.url)throw Error(R.error??`Slack socket connect failed (${M.status})`);return new WebSocket(R.url)}async function H(M){if(!G||!M||G.readyState!==WebSocket.OPEN)return;G.send(JSON.stringify({envelope_id:M}))}async function L(M){let R=JSON.parse(M.data);if(await H(R.envelope_id),!A)return;if(R.type==="interactive"){let k=R.payload??{},n=k.actions?.[0]?.value,H0=k.user?.id,b0=k.channel?.id;if(!n||!H0||!b0||!O(H0))return;await A({platform:"slack",chatId:b0,userId:H0,username:k.user?.username,displayName:k.user?.name,text:n,threadId:k.message?.ts});return}let I=(R.payload??{}).event;if(!I?.type||!I.user||!I.channel)return;if(!O(I.user))return;if(I.type!=="app_mention"&&!(I.type==="message"&&I.channel_type==="im"))return;if(I.ts&&W(I.ts))return;if(J(I.ts))return;let C=[];for(let k of I.files??[]){if(!k.url_private_download||!k.mimetype?.startsWith("audio/"))continue;try{let n=await fetch(k.url_private_download,{headers:{Authorization:`Bearer ${E}`}});C.push({kind:"audio",data:new Uint8Array(await n.arrayBuffer()),mimeType:k.mimetype,format:k.mimetype.split("/").at(1)??"mp3"})}catch{}}let v=(I.text??"").replace(/^<@[^>]+>\s*/,"").trim();await A({platform:"slack",chatId:I.channel,userId:I.user,text:v,threadId:I.thread_ts??I.ts,platformMessageId:I.ts,attachments:C.length>0?C:void 0})}async function F(M,R){let B=await fetch(`https://slack.com/api/${M}`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(R)}),I=await B.json();if(!B.ok||I.ok!==!0)throw Error(String(I.error??`Slack request failed (${B.status})`));return I}function j(M,R){if(!R?.length)return;return[{type:"section",text:{type:"mrkdwn",text:M}},{type:"actions",elements:R.flat().map((B)=>({type:"button",text:{type:"plain_text",text:B.label},value:B.value,action_id:B.value}))}]}return{platform:"slack",async start(M){A=M,N=!0;async function R(){G=await Y(),G.addEventListener("message",(B)=>{L(B)}),G.addEventListener("close",async()=>{if(!N)return;XD.warn("Slack socket closed; reconnecting in 5s"),await new Promise((B)=>setTimeout(B,5000));try{await R()}catch(B){XD.error("Slack reconnect failed",{err:B})}}),G.addEventListener("error",(B)=>{XD.warn("Slack socket error",{err:B})}),XD.info("Slack gateway adapter connected")}await R()},async stop(){N=!1,G?.close()},async send(M,R,B){let I=j(R,B?.buttons),C=await F("chat.postMessage",{channel:M,text:R,thread_ts:B?.threadId,...I?{blocks:I}:{}});return`${String(C.channel??M)}:${String(C.ts??"")}`},async updateMessage(M,R,B,I){let[C,v]=R.split(":");if(!C||!v)return;let k=j(B,I?.buttons);await F("chat.update",{channel:C,ts:v,text:B,...k?{blocks:k}:{}})},async sendWithButtons(M,R,B,I){let C=j(R,B),v=await F("chat.postMessage",{channel:M,text:R,thread_ts:I?.threadId,...C?{blocks:C}:{}});return`${String(v.channel??M)}:${String(v.ts??"")}`}}}var XD,oS=60000;var e7=T(()=>{R$();z$();lN();XD=B0("gateway:slack");dN("slack",($)=>mS($))});import{mkdtempSync as iS,readFileSync as pS,rmSync as $H,writeFileSync as dS}from"fs";import{tmpdir as lS}from"os";import{join as aW}from"path";function sS(){return Bun.which("ffmpeg")??null}function EH($){let w=$.toLowerCase();if(w==="oga"||w==="opus")return"ogg";if(w==="mpeg"||w==="mpga")return"mp3";return w}function wH($){let w=$.toLowerCase();if(w==="wav")return"audio/wav";if(w==="ogg"||w==="opus")return"audio/ogg";if(w==="mp4"||w==="m4a")return"audio/mp4";return"audio/mpeg"}function XH($,w,E){let X=sS();if(!X)throw Error("ffmpeg is required for voice support.");let G=iS(aW(lS(),"orc-gateway-")),A=aW(G,`input.${EH(w)}`),N=aW(G,`output.${E}`);dS(A,$);let D=["-y","-i",A];if(E==="mp3")D.push("-ac","1","-ar","16000");if(E==="ogg")D.push("-c:a","libopus");D.push(N);let O=Bun.spawnSync({cmd:[X,...D],stdout:"ignore",stderr:"pipe"});if(O.exitCode!==0){let J=new TextDecoder().decode(O.stderr);throw $H(G,{recursive:!0,force:!0}),Error(J||"ffmpeg conversion failed")}let W=pS(N);return $H(G,{recursive:!0,force:!0}),new Uint8Array(W)}function aS($){return!["mp3","wav","webm","m4a","mp4"].includes($.toLowerCase())}async function GH($){let w=G0();if(!w.speech.enabled)throw Error("Speech support is not enabled.");let{audio:E,format:X}=$;if(aS(X))E=XH(E,X,"mp3"),X="mp3";if(w.speech.provider==="qwen"){let W=w.speech.qwen.api_key;if(!W)throw Error("Qwen speech API key is not configured.");let J=w.speech.qwen.base_url??"https://dashscope.aliyuncs.com/compatible-mode/v1",Y={model:w.speech.qwen.model??"qwen3-asr-flash",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:`data:${wH(X)};base64,${Buffer.from(E).toString("base64")}`}}]}]},H=await fetch(`${J.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify(Y)}),L=await H.json();if(!H.ok)throw Error(L.error?.message??`Speech request failed (${H.status})`);return L.choices?.[0]?.message?.content?.trim()??""}let G=w.speech.provider==="groq"?w.speech.groq:w.speech.openai;if(!G.api_key)throw Error("Speech API key is not configured.");let A=G.base_url??(w.speech.provider==="groq"?"https://api.groq.com/openai/v1":"https://api.openai.com/v1"),N=new FormData;if(N.append("model",G.model??(w.speech.provider==="groq"?"whisper-large-v3-turbo":"whisper-1")),N.append("response_format","text"),w.speech.language)N.append("language",w.speech.language);N.append("file",new File([E],`audio.${EH(X)}`,{type:wH(X)}));let D=await fetch(`${A.replace(/\/$/,"")}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${G.api_key}`},body:N}),O=await D.text();if(!D.ok)throw Error(O||`Speech request failed (${D.status})`);return O.trim()}async function AH($){let w=G0();if(!w.tts.enabled)throw Error("TTS is not enabled.");if(w.tts.max_text_len>0&&$.length>w.tts.max_text_len)throw Error("Reply is too long for TTS.");if(w.tts.provider==="qwen"){let N=w.tts.qwen.api_key;if(!N)throw Error("Qwen TTS API key is not configured.");let D=await fetch(w.tts.qwen.base_url??"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",{method:"POST",headers:{Authorization:`Bearer ${N}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.qwen.model??"qwen3-tts-flash",input:{text:$,voice:w.tts.voice||"Cherry"}})}),O=await D.json();if(!D.ok||O.code)throw Error(O.message??`TTS request failed (${D.status})`);if(!O.output?.audio?.url)throw Error("Qwen TTS did not return audio.");let W=await fetch(O.output.audio.url),J=new Uint8Array(await W.arrayBuffer());return{audio:XH(J,"wav","ogg"),format:"ogg"}}let E=w.tts.openai.api_key??w.speech.openai.api_key;if(!E)throw Error("OpenAI TTS API key is not configured.");let X=w.tts.openai.base_url??"https://api.openai.com/v1",G=await fetch(`${X.replace(/\/$/,"")}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.openai.model??"tts-1",input:$,voice:w.tts.voice||"alloy"})});if(!G.ok)throw Error(await G.text());return{audio:new Uint8Array(await G.arrayBuffer()),format:"mp3"}}var NH=T(()=>{R$()});var ND=_((RH)=>{Object.defineProperty(RH,"__esModule",{value:!0});RH.matchFilter=eS;RH.parse=jH;RH.preprocess=MH;var DH=new Map;function eS($){var w;let E=Array.isArray($)?$:[$],X=E.join(","),G=(w=DH.get(X))!==null&&w!==void 0?w:(()=>{let A=jH(E),N=$2(A);return DH.set(X,N),N})();return(A)=>G(A)}function jH($){return Array.isArray($)?$.map((w)=>w.split(":")):[$.split(":")]}function $2($){let w=$.flatMap((G)=>w2(G,MH(G))),E=X2(w),X=G2(E);return(G)=>!!X(G.update,G)}function MH($){let w=AD,E=[$].flatMap((X)=>{let[G,A,N]=X;if(!(G in FH))return[X];if(!G&&!A&&!N)return[X];let O=FH[G].map((W)=>[W,A,N]);if(A===void 0)return O;if(A in $J&&(A||N))return O;return O.filter(([W])=>{var J;return!!((J=w[W])===null||J===void 0?void 0:J[A])})}).flatMap((X)=>{let[G,A,N]=X;if(!(A in $J))return[X];if(!A&&!N)return[X];let O=$J[A].map((W)=>[G,W,N]);if(N===void 0)return O;return O.filter(([,W])=>{var J,Y;return!!((Y=(J=w[G])===null||J===void 0?void 0:J[W])===null||Y===void 0?void 0:Y[N])})});if(E.length===0)throw Error(`Shortcuts in '${$.join(":")}' do not expand to any valid filter query`);return E}function w2($,w){if(w.length===0)throw Error("Empty filter query given");let E=w.map(E2).filter((X)=>X!==!0);if(E.length===0)return w;else if(E.length===1)throw Error(E[0]);else throw Error(`Invalid filter query '${$.join(":")}'. There are ${E.length} errors after expanding the contained shortcuts: ${E.join("; ")}`)}function E2($){let[w,E,X,...G]=$;if(w===void 0)return"Empty filter query given";if(!(w in AD)){let D=Object.keys(AD);return`Invalid L1 filter '${w}' given in '${$.join(":")}'. Permitted values are: ${D.map((O)=>`'${O}'`).join(", ")}.`}if(E===void 0)return!0;let A=AD[w];if(!(E in A)){let D=Object.keys(A);return`Invalid L2 filter '${E}' given in '${$.join(":")}'. Permitted values are: ${D.map((O)=>`'${O}'`).join(", ")}.`}if(X===void 0)return!0;let N=A[E];if(!(X in N)){let D=Object.keys(N);return`Invalid L3 filter '${X}' given in '${$.join(":")}'. ${D.length===0?`No further filtering is possible after '${w}:${E}'.`:`Permitted values are: ${D.map((O)=>`'${O}'`).join(", ")}.`}`}if(G.length===0)return!0;return`Cannot filter further than three levels, ':${G.join(":")}' is invalid!`}function X2($){var w,E;let X={};for(let[G,A,N]of $){let D=(w=X[G])!==null&&w!==void 0?w:X[G]={};if(A!==void 0){let O=(E=D[A])!==null&&E!==void 0?E:D[A]=new Set;if(N!==void 0)O.add(N)}}return X}function eW($,w){return(E,X)=>$(E,X)||w(E,X)}function OH($,w){return(E,X)=>{let G=$(E,X);return G&&w(G,X)}}function WH($){return(w,E)=>$(w,E)!=null}function G2($){let w=Object.entries($).map(([E,X])=>{let G=(N)=>N[E],A=Object.entries(X).map(([N,D])=>{let O=(J)=>J[N],W=Array.from(D).map((J)=>{return J==="me"?(H,L)=>{let F=L.me.id;return JH(H,(j)=>j.id===F)}:(H)=>JH(H,(L)=>L[J]||L.type===J)});return W.length===0?WH(O):OH(O,W.reduce(eW))});return A.length===0?WH(G):OH(G,A.reduce(eW))});if(w.length===0)throw Error("Cannot create filter function for empty query");return w.reduce(eW)}function JH($,w){let E=(X)=>X!=null&&w(X);return Array.isArray($)?$.some(E):E($)}var UH={mention:{},hashtag:{},cashtag:{},bot_command:{},url:{},email:{},phone_number:{},bold:{},italic:{},underline:{},strikethrough:{},spoiler:{},blockquote:{},expandable_blockquote:{},code:{},pre:{},text_link:{},text_mention:{},custom_emoji:{}},wJ={me:{},is_bot:{},is_premium:{},added_to_attachment_menu:{}},A2={user:{},hidden_user:{},chat:{},channel:{}},N2={is_video:{},is_animated:{},premium_animation:{}},EJ={emoji:{},custom_emoji:{},paid:{}},YH={can_be_upgraded:{},is_upgrade_separate:{},is_private:{}},TH={forward_origin:A2,is_topic_message:{},is_automatic_forward:{},business_connection_id:{},text:{},animation:{},audio:{},document:{},paid_media:{},photo:{},sticker:N2,story:{},video:{},video_note:{},voice:{},contact:{},dice:{},game:{},poll:{},venue:{},location:{},entities:UH,caption_entities:UH,caption:{},link_preview_options:{url:{},prefer_small_media:{},prefer_large_media:{},show_above_text:{}},effect_id:{},paid_star_count:{},has_media_spoiler:{},new_chat_title:{},new_chat_photo:{},delete_chat_photo:{},message_auto_delete_timer_changed:{},pinned_message:{},invoice:{},proximity_alert_triggered:{},chat_background_set:{},giveaway_created:{},giveaway:{only_new_members:{},has_public_winners:{}},giveaway_winners:{only_new_members:{},was_refunded:{}},giveaway_completed:{},gift:YH,gift_upgrade_sent:YH,unique_gift:{transfer_star_count:{}},paid_message_price_changed:{},video_chat_scheduled:{},video_chat_started:{},video_chat_ended:{},video_chat_participants_invited:{},web_app_data:{}},GD={...TH,direct_messages_topic:{},chat_owner_left:{new_owner:{}},chat_owner_changd:{},new_chat_members:wJ,left_chat_member:wJ,group_chat_created:{},supergroup_chat_created:{},migrate_to_chat_id:{},migrate_from_chat_id:{},successful_payment:{},refunded_payment:{},users_shared:{},chat_shared:{},connected_website:{},write_access_allowed:{},passport_data:{},boost_added:{},forum_topic_created:{is_name_implicit:{}},forum_topic_edited:{name:{},icon_custom_emoji_id:{}},forum_topic_closed:{},forum_topic_reopened:{},general_forum_topic_hidden:{},general_forum_topic_unhidden:{},checklist:{others_can_add_tasks:{},others_can_mark_tasks_as_done:{}},checklist_tasks_done:{},checklist_tasks_added:{},suggested_post_info:{},suggested_post_approved:{},suggested_post_approval_failed:{},suggested_post_declined:{},suggested_post_paid:{},suggested_post_refunded:{},sender_boost_count:{}},HH={...TH,channel_chat_created:{},direct_message_price_changed:{},is_paid_post:{}},D2={can_reply:{},is_enabled:{}},O2={old_reaction:EJ,new_reaction:EJ},W2={reactions:EJ},J2={data:{},game_short_name:{}},LH={from:wJ},AD={message:GD,edited_message:GD,channel_post:HH,edited_channel_post:HH,business_connection:D2,business_message:GD,edited_business_message:GD,deleted_business_messages:{},inline_query:{},chosen_inline_result:{},callback_query:J2,shipping_query:{},pre_checkout_query:{},poll:{},poll_answer:{},my_chat_member:LH,chat_member:LH,chat_join_request:{},message_reaction:O2,message_reaction_count:W2,chat_boost:{},removed_chat_boost:{},purchased_paid_media:{}},FH={"":["message","channel_post"],msg:["message","channel_post"],edit:["edited_message","edited_channel_post"]},$J={"":["entities","caption_entities"],media:["photo","video"],file:["photo","animation","audio","document","video","video_note","voice","sticker"]}});var OD=_((zH)=>{Object.defineProperty(zH,"__esModule",{value:!0});zH.Context=void 0;var L2=ND(),aw={filterQuery($){let w=(0,L2.matchFilter)($);return(E)=>w(E)},text($){let w=aw.filterQuery([":text",":caption"]),E=F1($);return(X)=>{var G,A;if(!w(X))return!1;let N=(G=X.message)!==null&&G!==void 0?G:X.channelPost,D=(A=N.text)!==null&&A!==void 0?A:N.caption;return j1(X,D,E)}},command($){let w=aw.filterQuery(":entities:bot_command"),E=new Set,X=new Set;return DD($).forEach((G)=>{if(G.startsWith("/"))throw Error(`Do not include '/' when registering command handlers (use '${G.substring(1)}' not '${G}')`);(G.includes("@")?E:X).add(G)}),(G)=>{var A,N;if(!w(G))return!1;let D=(A=G.message)!==null&&A!==void 0?A:G.channelPost,O=(N=D.text)!==null&&N!==void 0?N:D.caption;return D.entities.some((W)=>{if(W.type!=="bot_command")return!1;if(W.offset!==0)return!1;let J=O.substring(1,W.length);if(X.has(J)||E.has(J))return G.match=O.substring(J.length+1).trimStart(),!0;let Y=J.indexOf("@");if(Y===-1)return!1;let H=J.substring(Y+1).toLowerCase(),L=G.me.username.toLowerCase();if(H!==L)return!1;let F=J.substring(0,Y);if(X.has(F))return G.match=O.substring(J.length+1).trimStart(),!0;return!1})}},reaction($){let w=aw.filterQuery("message_reaction"),E=typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((N)=>typeof N==="string"?{type:"emoji",emoji:N}:N),X=new Set(E.filter((N)=>N.type==="emoji").map((N)=>N.emoji)),G=new Set(E.filter((N)=>N.type==="custom_emoji").map((N)=>N.custom_emoji_id)),A=E.some((N)=>N.type==="paid");return(N)=>{if(!w(N))return!1;let{old_reaction:D,new_reaction:O}=N.messageReaction;for(let W of O){let J=!1;if(W.type==="emoji")for(let Y of D){if(Y.type!=="emoji")continue;if(Y.emoji===W.emoji){J=!0;break}}else if(W.type==="custom_emoji")for(let Y of D){if(Y.type!=="custom_emoji")continue;if(Y.custom_emoji_id===W.custom_emoji_id){J=!0;break}}else if(W.type==="paid")for(let Y of D){if(Y.type!=="paid")continue;J=!0;break}if(J)continue;if(W.type==="emoji"){if(X.has(W.emoji))return!0}else if(W.type==="custom_emoji"){if(G.has(W.custom_emoji_id))return!0}else if(W.type==="paid"){if(A)return!0}else return!0}return!1}},chatType($){let w=new Set(DD($));return(E)=>{var X;return((X=E.chat)===null||X===void 0?void 0:X.type)!==void 0&&w.has(E.chat.type)}},callbackQuery($){let w=aw.filterQuery("callback_query:data"),E=F1($);return(X)=>w(X)&&j1(X,X.callbackQuery.data,E)},gameQuery($){let w=aw.filterQuery("callback_query:game_short_name"),E=F1($);return(X)=>w(X)&&j1(X,X.callbackQuery.game_short_name,E)},inlineQuery($){let w=aw.filterQuery("inline_query"),E=F1($);return(X)=>w(X)&&j1(X,X.inlineQuery.query,E)},chosenInlineResult($){let w=aw.filterQuery("chosen_inline_result"),E=F1($);return(X)=>w(X)&&j1(X,X.chosenInlineResult.result_id,E)},preCheckoutQuery($){let w=aw.filterQuery("pre_checkout_query"),E=F1($);return(X)=>w(X)&&j1(X,X.preCheckoutQuery.invoice_payload,E)},shippingQuery($){let w=aw.filterQuery("shipping_query"),E=F1($);return(X)=>w(X)&&j1(X,X.shippingQuery.invoice_payload,E)}};class s${constructor($,w,E){this.update=$,this.api=w,this.me=E}get message(){return this.update.message}get editedMessage(){return this.update.edited_message}get channelPost(){return this.update.channel_post}get editedChannelPost(){return this.update.edited_channel_post}get businessConnection(){return this.update.business_connection}get businessMessage(){return this.update.business_message}get editedBusinessMessage(){return this.update.edited_business_message}get deletedBusinessMessages(){return this.update.deleted_business_messages}get messageReaction(){return this.update.message_reaction}get messageReactionCount(){return this.update.message_reaction_count}get inlineQuery(){return this.update.inline_query}get chosenInlineResult(){return this.update.chosen_inline_result}get callbackQuery(){return this.update.callback_query}get shippingQuery(){return this.update.shipping_query}get preCheckoutQuery(){return this.update.pre_checkout_query}get poll(){return this.update.poll}get pollAnswer(){return this.update.poll_answer}get myChatMember(){return this.update.my_chat_member}get chatMember(){return this.update.chat_member}get chatJoinRequest(){return this.update.chat_join_request}get chatBoost(){return this.update.chat_boost}get removedChatBoost(){return this.update.removed_chat_boost}get purchasedPaidMedia(){return this.update.purchased_paid_media}get msg(){var $,w,E,X,G,A,N;return(A=(G=(X=(E=(w=($=this.message)!==null&&$!==void 0?$:this.editedMessage)!==null&&w!==void 0?w:this.channelPost)!==null&&E!==void 0?E:this.editedChannelPost)!==null&&X!==void 0?X:this.businessMessage)!==null&&G!==void 0?G:this.editedBusinessMessage)!==null&&A!==void 0?A:(N=this.callbackQuery)===null||N===void 0?void 0:N.message}get chat(){var $,w,E,X,G,A,N,D,O;return(O=(D=(N=(A=(G=(X=(E=(w=($=this.msg)!==null&&$!==void 0?$:this.deletedBusinessMessages)!==null&&w!==void 0?w:this.messageReaction)!==null&&E!==void 0?E:this.messageReactionCount)!==null&&X!==void 0?X:this.myChatMember)!==null&&G!==void 0?G:this.chatMember)!==null&&A!==void 0?A:this.chatJoinRequest)!==null&&N!==void 0?N:this.chatBoost)!==null&&D!==void 0?D:this.removedChatBoost)===null||O===void 0?void 0:O.chat}get senderChat(){var $;return($=this.msg)===null||$===void 0?void 0:$.sender_chat}get from(){var $,w,E,X,G,A,N,D,O,W,J,Y,H,L,F,j,M;return(N=(A=(w=($=this.businessConnection)!==null&&$!==void 0?$:this.messageReaction)!==null&&w!==void 0?w:(G=(X=(E=this.chatBoost)===null||E===void 0?void 0:E.boost)!==null&&X!==void 0?X:this.removedChatBoost)===null||G===void 0?void 0:G.source)===null||A===void 0?void 0:A.user)!==null&&N!==void 0?N:(M=(j=(F=(L=(H=(Y=(J=(W=(O=(D=this.callbackQuery)!==null&&D!==void 0?D:this.msg)!==null&&O!==void 0?O:this.inlineQuery)!==null&&W!==void 0?W:this.chosenInlineResult)!==null&&J!==void 0?J:this.shippingQuery)!==null&&Y!==void 0?Y:this.preCheckoutQuery)!==null&&H!==void 0?H:this.myChatMember)!==null&&L!==void 0?L:this.chatMember)!==null&&F!==void 0?F:this.chatJoinRequest)!==null&&j!==void 0?j:this.purchasedPaidMedia)===null||M===void 0?void 0:M.from}get msgId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.message_id)!==null&&w!==void 0?w:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReactionCount)===null||G===void 0?void 0:G.message_id}get chatId(){var $,w,E;return(w=($=this.chat)===null||$===void 0?void 0:$.id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.user_chat_id}get inlineMessageId(){var $,w,E;return(w=($=this.callbackQuery)===null||$===void 0?void 0:$.inline_message_id)!==null&&w!==void 0?w:(E=this.chosenInlineResult)===null||E===void 0?void 0:E.inline_message_id}get businessConnectionId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.business_connection_id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.id)!==null&&X!==void 0?X:(G=this.deletedBusinessMessages)===null||G===void 0?void 0:G.business_connection_id}entities($){var w,E;let X=this.msg;if(X===void 0)return[];let G=(w=X.text)!==null&&w!==void 0?w:X.caption;if(G===void 0)return[];let A=(E=X.entities)!==null&&E!==void 0?E:X.caption_entities;if(A===void 0)return[];if($!==void 0){let N=new Set(DD($));A=A.filter((D)=>N.has(D.type))}return A.map((N)=>({...N,text:G.substring(N.offset,N.offset+N.length)}))}reactions(){let $=[],w=[],E=[],X=[],G=[],A=[],N=[],D=[],O=!1,W=!1,J=this.messageReaction;if(J!==void 0){let{old_reaction:Y,new_reaction:H}=J;for(let L of H)if(L.type==="emoji")$.push(L.emoji);else if(L.type==="custom_emoji")G.push(L.custom_emoji_id);else if(L.type==="paid")O=W=!0;for(let L of Y)if(L.type==="emoji")X.push(L.emoji);else if(L.type==="custom_emoji")D.push(L.custom_emoji_id);else if(L.type==="paid")W=!1;w.push(...$),A.push(...G);for(let L=0;L<X.length;L++){let F=w.length;if(F===0)break;let j=X[L];for(let M=0;M<F;M++)if(j===w[M]){E.push(j),X.splice(L,1),w.splice(M,1),L--;break}}for(let L=0;L<D.length;L++){let F=A.length;if(F===0)break;let j=D[L];for(let M=0;M<F;M++)if(j===A[M]){N.push(j),D.splice(L,1),A.splice(M,1),L--;break}}}return{emoji:$,emojiAdded:w,emojiKept:E,emojiRemoved:X,customEmoji:G,customEmojiAdded:A,customEmojiKept:N,customEmojiRemoved:D,paid:O,paidAdded:W}}has($){return s$.has.filterQuery($)(this)}hasText($){return s$.has.text($)(this)}hasCommand($){return s$.has.command($)(this)}hasReaction($){return s$.has.reaction($)(this)}hasChatType($){return s$.has.chatType($)(this)}hasCallbackQuery($){return s$.has.callbackQuery($)(this)}hasGameQuery($){return s$.has.gameQuery($)(this)}hasInlineQuery($){return s$.has.inlineQuery($)(this)}hasChosenInlineResult($){return s$.has.chosenInlineResult($)(this)}hasPreCheckoutQuery($){return s$.has.preCheckoutQuery($)(this)}hasShippingQuery($){return s$.has.shippingQuery($)(this)}reply($,w,E){var X;let G=this.msg;return this.api.sendMessage(Q(this.chatId,"sendMessage"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDraft($,w,E){let X=this.msg;return this.api.sendMessageDraft(Q(this.chatId,"sendMessageDraft"),this.update.update_id,$,{...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X===null||X===void 0?void 0:X.message_thread_id}:{},...w},E)}forwardMessage($,w,E){var X;let G=this.msg;return this.api.forwardMessage($,Q(this.chatId,"forwardMessage"),Q(this.msgId,"forwardMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}forwardMessages($,w,E,X){var G;let A=this.msg;return this.api.forwardMessages($,Q(this.chatId,"forwardMessages"),w,{direct_messages_topic_id:(G=A===null||A===void 0?void 0:A.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}copyMessage($,w,E){var X;let G=this.msg;return this.api.copyMessage($,Q(this.chatId,"copyMessage"),Q(this.msgId,"copyMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}copyMessages($,w,E,X){var G;let A=this.msg;return this.api.copyMessages($,Q(this.chatId,"copyMessages"),w,{direct_messages_topic_id:(G=A===null||A===void 0?void 0:A.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPhoto($,w,E){var X;let G=this.msg;return this.api.sendPhoto(Q(this.chatId,"sendPhoto"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAudio($,w,E){var X;let G=this.msg;return this.api.sendAudio(Q(this.chatId,"sendAudio"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDocument($,w,E){var X;let G=this.msg;return this.api.sendDocument(Q(this.chatId,"sendDocument"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideo($,w,E){var X;let G=this.msg;return this.api.sendVideo(Q(this.chatId,"sendVideo"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAnimation($,w,E){var X;let G=this.msg;return this.api.sendAnimation(Q(this.chatId,"sendAnimation"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVoice($,w,E){var X;let G=this.msg;return this.api.sendVoice(Q(this.chatId,"sendVoice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideoNote($,w,E){var X;let G=this.msg;return this.api.sendVideoNote(Q(this.chatId,"sendVideoNote"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithMediaGroup($,w,E){var X;let G=this.msg;return this.api.sendMediaGroup(Q(this.chatId,"sendMediaGroup"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithLocation($,w,E,X){var G;let A=this.msg;return this.api.sendLocation(Q(this.chatId,"sendLocation"),$,w,{business_connection_id:this.businessConnectionId,...(A===null||A===void 0?void 0:A.is_topic_message)?{message_thread_id:A.message_thread_id}:{},direct_messages_topic_id:(G=A===null||A===void 0?void 0:A.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}editMessageLiveLocation($,w,E,X){let G=this.inlineMessageId;return G!==void 0?this.api.editMessageLiveLocationInline(G,$,w,{business_connection_id:this.businessConnectionId,...E},X):this.api.editMessageLiveLocation(Q(this.chatId,"editMessageLiveLocation"),Q(this.msgId,"editMessageLiveLocation"),$,w,{business_connection_id:this.businessConnectionId,...E},X)}stopMessageLiveLocation($,w){let E=this.inlineMessageId;return E!==void 0?this.api.stopMessageLiveLocationInline(E,{business_connection_id:this.businessConnectionId,...$},w):this.api.stopMessageLiveLocation(Q(this.chatId,"stopMessageLiveLocation"),Q(this.msgId,"stopMessageLiveLocation"),{business_connection_id:this.businessConnectionId,...$},w)}sendPaidMedia($,w,E,X){var G,A;let N=this.msg;return this.api.sendPaidMedia(Q(this.chatId,"sendPaidMedia"),$,w,{business_connection_id:this.businessConnectionId,...(N===null||N===void 0?void 0:N.is_topic_message)?{message_thread_id:N.message_thread_id}:{},direct_messages_topic_id:(A=(G=this.msg)===null||G===void 0?void 0:G.direct_messages_topic)===null||A===void 0?void 0:A.topic_id,...E},X)}replyWithVenue($,w,E,X,G,A){var N;let D=this.msg;return this.api.sendVenue(Q(this.chatId,"sendVenue"),$,w,E,X,{business_connection_id:this.businessConnectionId,...(D===null||D===void 0?void 0:D.is_topic_message)?{message_thread_id:D.message_thread_id}:{},direct_messages_topic_id:(N=D===null||D===void 0?void 0:D.direct_messages_topic)===null||N===void 0?void 0:N.topic_id,...G},A)}replyWithContact($,w,E,X){var G;let A=this.msg;return this.api.sendContact(Q(this.chatId,"sendContact"),$,w,{business_connection_id:this.businessConnectionId,...(A===null||A===void 0?void 0:A.is_topic_message)?{message_thread_id:A.message_thread_id}:{},direct_messages_topic_id:(G=A===null||A===void 0?void 0:A.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPoll($,w,E,X){let G=this.msg;return this.api.sendPoll(Q(this.chatId,"sendPoll"),$,w,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},...E},X)}replyWithChecklist($,w,E){return this.api.sendChecklist(Q(this.businessConnectionId,"sendChecklist"),Q(this.chatId,"sendChecklist"),$,w,E)}editMessageChecklist($,w,E){var X,G,A,N;let D=Q(this.msg,"editMessageChecklist"),O=(N=(G=(X=D.checklist_tasks_done)===null||X===void 0?void 0:X.checklist_message)!==null&&G!==void 0?G:(A=D.checklist_tasks_added)===null||A===void 0?void 0:A.checklist_message)!==null&&N!==void 0?N:D;return this.api.editMessageChecklist(Q(this.businessConnectionId,"editMessageChecklist"),Q(O.chat.id,"editMessageChecklist"),Q(O.message_id,"editMessageChecklist"),$,w,E)}replyWithDice($,w,E){var X;let G=this.msg;return this.api.sendDice(Q(this.chatId,"sendDice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithChatAction($,w,E){let X=this.msg;return this.api.sendChatAction(Q(this.chatId,"sendChatAction"),$,{business_connection_id:this.businessConnectionId,message_thread_id:X===null||X===void 0?void 0:X.message_thread_id,...w},E)}react($,w,E){return this.api.setMessageReaction(Q(this.chatId,"setMessageReaction"),Q(this.msgId,"setMessageReaction"),typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((X)=>typeof X==="string"?{type:"emoji",emoji:X}:X),w,E)}getUserProfilePhotos($,w){return this.api.getUserProfilePhotos(Q(this.from,"getUserProfilePhotos").id,$,w)}getUserProfileAudios($,w){return this.api.getUserProfileAudios(Q(this.from,"getUserProfileAudios").id,$,w)}setUserEmojiStatus($,w){return this.api.setUserEmojiStatus(Q(this.from,"setUserEmojiStatus").id,$,w)}getUserChatBoosts($,w){return this.api.getUserChatBoosts($!==null&&$!==void 0?$:Q(this.chatId,"getUserChatBoosts"),Q(this.from,"getUserChatBoosts").id,w)}getUserGifts($,w){return this.api.getUserGifts(Q(this.from,"getUserGifts").id,$,w)}getChatGifts($,w){return this.api.getChatGifts(Q(this.chatId,"getChatGifts"),$,w)}getBusinessConnection($){return this.api.getBusinessConnection(Q(this.businessConnectionId,"getBusinessConnection"),$)}getFile($){var w,E,X,G,A,N;let D=Q(this.msg,"getFile"),O=D.photo!==void 0?D.photo[D.photo.length-1]:(N=(A=(G=(X=(E=(w=D.animation)!==null&&w!==void 0?w:D.audio)!==null&&E!==void 0?E:D.document)!==null&&X!==void 0?X:D.video)!==null&&G!==void 0?G:D.video_note)!==null&&A!==void 0?A:D.voice)!==null&&N!==void 0?N:D.sticker;return this.api.getFile(Q(O,"getFile").file_id,$)}kickAuthor(...$){return this.banAuthor(...$)}banAuthor($,w){return this.api.banChatMember(Q(this.chatId,"banAuthor"),Q(this.from,"banAuthor").id,$,w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E){return this.api.banChatMember(Q(this.chatId,"banChatMember"),$,w,E)}unbanChatMember($,w,E){return this.api.unbanChatMember(Q(this.chatId,"unbanChatMember"),$,w,E)}restrictAuthor($,w,E){return this.api.restrictChatMember(Q(this.chatId,"restrictAuthor"),Q(this.from,"restrictAuthor").id,$,w,E)}restrictChatMember($,w,E,X){return this.api.restrictChatMember(Q(this.chatId,"restrictChatMember"),$,w,E,X)}promoteAuthor($,w){return this.api.promoteChatMember(Q(this.chatId,"promoteAuthor"),Q(this.from,"promoteAuthor").id,$,w)}promoteChatMember($,w,E){return this.api.promoteChatMember(Q(this.chatId,"promoteChatMember"),$,w,E)}setChatAdministratorAuthorCustomTitle($,w){return this.api.setChatAdministratorCustomTitle(Q(this.chatId,"setChatAdministratorAuthorCustomTitle"),Q(this.from,"setChatAdministratorAuthorCustomTitle").id,$,w)}setChatAdministratorCustomTitle($,w,E){return this.api.setChatAdministratorCustomTitle(Q(this.chatId,"setChatAdministratorCustomTitle"),$,w,E)}setAuthorTag($,w){return this.api.setChatMemberTag(Q(this.chatId,"setChatMemberTag"),Q(this.from,"setChatMemberTag").id,$,w)}setChatMemberTag($,w,E){return this.api.setChatMemberTag(Q(this.chatId,"setChatMemberTag"),$,w,E)}banChatSenderChat($,w){return this.api.banChatSenderChat(Q(this.chatId,"banChatSenderChat"),$,w)}unbanChatSenderChat($,w){return this.api.unbanChatSenderChat(Q(this.chatId,"unbanChatSenderChat"),$,w)}setChatPermissions($,w,E){return this.api.setChatPermissions(Q(this.chatId,"setChatPermissions"),$,w,E)}exportChatInviteLink($){return this.api.exportChatInviteLink(Q(this.chatId,"exportChatInviteLink"),$)}createChatInviteLink($,w){return this.api.createChatInviteLink(Q(this.chatId,"createChatInviteLink"),$,w)}editChatInviteLink($,w,E){return this.api.editChatInviteLink(Q(this.chatId,"editChatInviteLink"),$,w,E)}createChatSubscriptionInviteLink($,w,E,X){return this.api.createChatSubscriptionInviteLink(Q(this.chatId,"createChatSubscriptionInviteLink"),$,w,E,X)}editChatSubscriptionInviteLink($,w,E){return this.api.editChatSubscriptionInviteLink(Q(this.chatId,"editChatSubscriptionInviteLink"),$,w,E)}revokeChatInviteLink($,w){return this.api.revokeChatInviteLink(Q(this.chatId,"editChatInviteLink"),$,w)}approveChatJoinRequest($,w){return this.api.approveChatJoinRequest(Q(this.chatId,"approveChatJoinRequest"),$,w)}declineChatJoinRequest($,w){return this.api.declineChatJoinRequest(Q(this.chatId,"declineChatJoinRequest"),$,w)}approveSuggestedPost($,w){return this.api.approveSuggestedPost(Q(this.chatId,"approveSuggestedPost"),Q(this.msgId,"approveSuggestedPost"),$,w)}declineSuggestedPost($,w){return this.api.declineSuggestedPost(Q(this.chatId,"declineSuggestedPost"),Q(this.msgId,"declineSuggestedPost"),$,w)}setChatPhoto($,w){return this.api.setChatPhoto(Q(this.chatId,"setChatPhoto"),$,w)}deleteChatPhoto($){return this.api.deleteChatPhoto(Q(this.chatId,"deleteChatPhoto"),$)}setChatTitle($,w){return this.api.setChatTitle(Q(this.chatId,"setChatTitle"),$,w)}setChatDescription($,w){return this.api.setChatDescription(Q(this.chatId,"setChatDescription"),$,w)}pinChatMessage($,w,E){return this.api.pinChatMessage(Q(this.chatId,"pinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinChatMessage($,w,E){return this.api.unpinChatMessage(Q(this.chatId,"unpinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinAllChatMessages($){return this.api.unpinAllChatMessages(Q(this.chatId,"unpinAllChatMessages"),$)}leaveChat($){return this.api.leaveChat(Q(this.chatId,"leaveChat"),$)}getChat($){return this.api.getChat(Q(this.chatId,"getChat"),$)}getChatAdministrators($){return this.api.getChatAdministrators(Q(this.chatId,"getChatAdministrators"),$)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($){return this.api.getChatMemberCount(Q(this.chatId,"getChatMemberCount"),$)}getAuthor($){return this.api.getChatMember(Q(this.chatId,"getAuthor"),Q(this.from,"getAuthor").id,$)}getChatMember($,w){return this.api.getChatMember(Q(this.chatId,"getChatMember"),$,w)}setChatStickerSet($,w){return this.api.setChatStickerSet(Q(this.chatId,"setChatStickerSet"),$,w)}deleteChatStickerSet($){return this.api.deleteChatStickerSet(Q(this.chatId,"deleteChatStickerSet"),$)}createForumTopic($,w,E){return this.api.createForumTopic(Q(this.chatId,"createForumTopic"),$,w,E)}editForumTopic($,w){let E=Q(this.msg,"editForumTopic"),X=Q(E.message_thread_id,"editForumTopic");return this.api.editForumTopic(E.chat.id,X,$,w)}closeForumTopic($){let w=Q(this.msg,"closeForumTopic"),E=Q(w.message_thread_id,"closeForumTopic");return this.api.closeForumTopic(w.chat.id,E,$)}reopenForumTopic($){let w=Q(this.msg,"reopenForumTopic"),E=Q(w.message_thread_id,"reopenForumTopic");return this.api.reopenForumTopic(w.chat.id,E,$)}deleteForumTopic($){let w=Q(this.msg,"deleteForumTopic"),E=Q(w.message_thread_id,"deleteForumTopic");return this.api.deleteForumTopic(w.chat.id,E,$)}unpinAllForumTopicMessages($){let w=Q(this.msg,"unpinAllForumTopicMessages"),E=Q(w.message_thread_id,"unpinAllForumTopicMessages");return this.api.unpinAllForumTopicMessages(w.chat.id,E,$)}editGeneralForumTopic($,w){return this.api.editGeneralForumTopic(Q(this.chatId,"editGeneralForumTopic"),$,w)}closeGeneralForumTopic($){return this.api.closeGeneralForumTopic(Q(this.chatId,"closeGeneralForumTopic"),$)}reopenGeneralForumTopic($){return this.api.reopenGeneralForumTopic(Q(this.chatId,"reopenGeneralForumTopic"),$)}hideGeneralForumTopic($){return this.api.hideGeneralForumTopic(Q(this.chatId,"hideGeneralForumTopic"),$)}unhideGeneralForumTopic($){return this.api.unhideGeneralForumTopic(Q(this.chatId,"unhideGeneralForumTopic"),$)}unpinAllGeneralForumTopicMessages($){return this.api.unpinAllGeneralForumTopicMessages(Q(this.chatId,"unpinAllGeneralForumTopicMessages"),$)}answerCallbackQuery($,w){return this.api.answerCallbackQuery(Q(this.callbackQuery,"answerCallbackQuery").id,typeof $==="string"?{text:$}:$,w)}setChatMenuButton($,w){return this.api.setChatMenuButton($,w)}getChatMenuButton($,w){return this.api.getChatMenuButton($,w)}setMyDefaultAdministratorRights($,w){return this.api.setMyDefaultAdministratorRights($,w)}getMyDefaultAdministratorRights($,w){return this.api.getMyDefaultAdministratorRights($,w)}editMessageText($,w,E){var X,G,A,N,D;let O=this.inlineMessageId;return O!==void 0?this.api.editMessageTextInline(O,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageText(Q(this.chatId,"editMessageText"),Q((N=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(A=this.messageReaction)===null||A===void 0?void 0:A.message_id)!==null&&N!==void 0?N:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageText"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageCaption($,w){var E,X,G,A,N;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageCaptionInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageCaption(Q(this.chatId,"editMessageCaption"),Q((A=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&A!==void 0?A:(N=this.messageReactionCount)===null||N===void 0?void 0:N.message_id,"editMessageCaption"),{business_connection_id:this.businessConnectionId,...$},w)}editMessageMedia($,w,E){var X,G,A,N,D;let O=this.inlineMessageId;return O!==void 0?this.api.editMessageMediaInline(O,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageMedia(Q(this.chatId,"editMessageMedia"),Q((N=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(A=this.messageReaction)===null||A===void 0?void 0:A.message_id)!==null&&N!==void 0?N:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageMedia"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageReplyMarkup($,w){var E,X,G,A,N;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageReplyMarkupInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageReplyMarkup(Q(this.chatId,"editMessageReplyMarkup"),Q((A=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&A!==void 0?A:(N=this.messageReactionCount)===null||N===void 0?void 0:N.message_id,"editMessageReplyMarkup"),{business_connection_id:this.businessConnectionId,...$},w)}stopPoll($,w){var E,X,G,A,N;return this.api.stopPoll(Q(this.chatId,"stopPoll"),Q((A=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&A!==void 0?A:(N=this.messageReactionCount)===null||N===void 0?void 0:N.message_id,"stopPoll"),{business_connection_id:this.businessConnectionId,...$},w)}deleteMessage($){var w,E,X,G,A;return this.api.deleteMessage(Q(this.chatId,"deleteMessage"),Q((G=(E=(w=this.msg)===null||w===void 0?void 0:w.message_id)!==null&&E!==void 0?E:(X=this.messageReaction)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"deleteMessage"),$)}deleteMessages($,w){return this.api.deleteMessages(Q(this.chatId,"deleteMessages"),$,w)}deleteBusinessMessages($,w){return this.api.deleteBusinessMessages(Q(this.businessConnectionId,"deleteBusinessMessages"),$,w)}setBusinessAccountName($,w,E){return this.api.setBusinessAccountName(Q(this.businessConnectionId,"setBusinessAccountName"),$,w,E)}setBusinessAccountUsername($,w){return this.api.setBusinessAccountUsername(Q(this.businessConnectionId,"setBusinessAccountUsername"),$,w)}setBusinessAccountBio($,w){return this.api.setBusinessAccountBio(Q(this.businessConnectionId,"setBusinessAccountBio"),$,w)}setBusinessAccountProfilePhoto($,w,E){return this.api.setBusinessAccountProfilePhoto(Q(this.businessConnectionId,"setBusinessAccountProfilePhoto"),$,w,E)}removeBusinessAccountProfilePhoto($,w){return this.api.removeBusinessAccountProfilePhoto(Q(this.businessConnectionId,"removeBusinessAccountProfilePhoto"),$,w)}setBusinessAccountGiftSettings($,w,E){return this.api.setBusinessAccountGiftSettings(Q(this.businessConnectionId,"setBusinessAccountGiftSettings"),$,w,E)}getBusinessAccountStarBalance($){return this.api.getBusinessAccountStarBalance(Q(this.businessConnectionId,"getBusinessAccountStarBalance"),$)}transferBusinessAccountStars($,w){return this.api.transferBusinessAccountStars(Q(this.businessConnectionId,"transferBusinessAccountStars"),$,w)}getBusinessAccountGifts($,w){return this.api.getBusinessAccountGifts(Q(this.businessConnectionId,"getBusinessAccountGifts"),$,w)}convertGiftToStars($,w){return this.api.convertGiftToStars(Q(this.businessConnectionId,"convertGiftToStars"),$,w)}upgradeGift($,w,E){return this.api.upgradeGift(Q(this.businessConnectionId,"upgradeGift"),$,w,E)}transferGift($,w,E,X){return this.api.transferGift(Q(this.businessConnectionId,"transferGift"),$,w,E,X)}postStory($,w,E,X){return this.api.postStory(Q(this.businessConnectionId,"postStory"),$,w,E,X)}repostStory($,w,E){var X;let G=Q((X=this.msg)===null||X===void 0?void 0:X.story,"repostStory");return this.api.repostStory(Q(this.businessConnectionId,"repostStory"),G.chat.id,G.id,$,w,E)}editStory($,w,E,X){return this.api.editStory(Q(this.businessConnectionId,"editStory"),$,w,E,X)}deleteStory($,w){return this.api.deleteStory(Q(this.businessConnectionId,"deleteStory"),$,w)}replyWithSticker($,w,E){var X;let G=this.msg;return this.api.sendSticker(Q(this.chatId,"sendSticker"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}getCustomEmojiStickers($){var w,E;return this.api.getCustomEmojiStickers(((E=(w=this.msg)===null||w===void 0?void 0:w.entities)!==null&&E!==void 0?E:[]).filter((X)=>X.type==="custom_emoji").map((X)=>X.custom_emoji_id),$)}replyWithGift($,w,E){return this.api.sendGift(Q(this.from,"sendGift").id,$,w,E)}giftPremiumSubscription($,w,E,X){return this.api.giftPremiumSubscription(Q(this.from,"giftPremiumSubscription").id,$,w,E,X)}replyWithGiftToChannel($,w,E){return this.api.sendGiftToChannel(Q(this.chat,"sendGift").id,$,w,E)}answerInlineQuery($,w,E){return this.api.answerInlineQuery(Q(this.inlineQuery,"answerInlineQuery").id,$,w,E)}savePreparedInlineMessage($,w,E){return this.api.savePreparedInlineMessage(Q(this.from,"savePreparedInlineMessage").id,$,w,E)}replyWithInvoice($,w,E,X,G,A,N){var D;let O=this.msg;return this.api.sendInvoice(Q(this.chatId,"sendInvoice"),$,w,E,X,G,{...(O===null||O===void 0?void 0:O.is_topic_message)?{message_thread_id:O.message_thread_id}:{},direct_messages_topic_id:(D=O===null||O===void 0?void 0:O.direct_messages_topic)===null||D===void 0?void 0:D.topic_id,...A},N)}answerShippingQuery($,w,E){return this.api.answerShippingQuery(Q(this.shippingQuery,"answerShippingQuery").id,$,w,E)}answerPreCheckoutQuery($,w,E){return this.api.answerPreCheckoutQuery(Q(this.preCheckoutQuery,"answerPreCheckoutQuery").id,$,typeof w==="string"?{error_message:w}:w,E)}refundStarPayment($){var w;return this.api.refundStarPayment(Q(this.from,"refundStarPayment").id,Q((w=this.msg)===null||w===void 0?void 0:w.successful_payment,"refundStarPayment").telegram_payment_charge_id,$)}editUserStarSubscription($,w,E){return this.api.editUserStarSubscription(Q(this.from,"editUserStarSubscription").id,$,w,E)}verifyUser($,w){return this.api.verifyUser(Q(this.from,"verifyUser").id,$,w)}verifyChat($,w){return this.api.verifyChat(Q(this.chatId,"verifyChat"),$,w)}removeUserVerification($){return this.api.removeUserVerification(Q(this.from,"removeUserVerification").id,$)}removeChatVerification($){return this.api.removeChatVerification(Q(this.chatId,"removeChatVerification"),$)}readBusinessMessage($){return this.api.readBusinessMessage(Q(this.businessConnectionId,"readBusinessMessage"),Q(this.chatId,"readBusinessMessage"),Q(this.msgId,"readBusinessMessage"),$)}setPassportDataErrors($,w){return this.api.setPassportDataErrors(Q(this.from,"setPassportDataErrors").id,$,w)}replyWithGame($,w,E){let X=this.msg;return this.api.sendGame(Q(this.chatId,"sendGame"),$,{business_connection_id:this.businessConnectionId,...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X.message_thread_id}:{},...w},E)}}zH.Context=s$;s$.has=aw;function Q($,w){if($===void 0)throw Error(`Missing information for API call to ${w}`);return $}function F1($){return DD($).map((w)=>typeof w==="string"?(E)=>E===w?w:null:(E)=>E.match(w))}function j1($,w,E){for(let X of E){let G=X(w);if(G)return $.match=G,!0}return!1}function DD($){return Array.isArray($)?$:[$]}});var AJ=_((KH)=>{Object.defineProperty(KH,"__esModule",{value:!0});KH.Composer=KH.BotError=void 0;KH.run=QH;var Zw=OD();class GJ extends Error{constructor($,w){super(F2($));if(this.error=$,this.ctx=w,this.name="BotError",$ instanceof Error)this.stack=$.stack}}KH.BotError=GJ;function F2($){let w;if($ instanceof Error)w=`${$.name} in middleware: ${$.message}`;else{let E=typeof $;switch(w=`Non-error value of type ${E} thrown in middleware`,E){case"bigint":case"boolean":case"number":case"symbol":w+=`: ${$}`;break;case"string":w+=`: ${String($).substring(0,50)}`;break;default:w+="!";break}}return w}function cG($){return typeof $==="function"?$:(w,E)=>$.middleware()(w,E)}function IH($,w){return async(E,X)=>{let G=!1;await $(E,async()=>{if(G)throw Error("`next` already called before!");else G=!0;await w(E,X)})}}function XJ($,w){return w()}var j2=()=>Promise.resolve();async function QH($,w){await $(w,j2)}class M1{constructor(...$){this.handler=$.length===0?XJ:$.map(cG).reduce(IH)}middleware(){return this.handler}use(...$){let w=new M1(...$);return this.handler=IH(this.handler,cG(w)),w}on($,...w){return this.filter(Zw.Context.has.filterQuery($),...w)}hears($,...w){return this.filter(Zw.Context.has.text($),...w)}command($,...w){return this.filter(Zw.Context.has.command($),...w)}reaction($,...w){return this.filter(Zw.Context.has.reaction($),...w)}chatType($,...w){return this.filter(Zw.Context.has.chatType($),...w)}callbackQuery($,...w){return this.filter(Zw.Context.has.callbackQuery($),...w)}gameQuery($,...w){return this.filter(Zw.Context.has.gameQuery($),...w)}inlineQuery($,...w){return this.filter(Zw.Context.has.inlineQuery($),...w)}chosenInlineResult($,...w){return this.filter(Zw.Context.has.chosenInlineResult($),...w)}preCheckoutQuery($,...w){return this.filter(Zw.Context.has.preCheckoutQuery($),...w)}shippingQuery($,...w){return this.filter(Zw.Context.has.shippingQuery($),...w)}filter($,...w){let E=new M1(...w);return this.branch($,E,XJ),E}drop($,...w){return this.filter(async(E)=>!await $(E),...w)}fork(...$){let w=new M1(...$),E=cG(w);return this.use((X,G)=>Promise.all([G(),QH(E,X)])),w}lazy($){return this.use(async(w,E)=>{let X=await $(w),G=Array.isArray(X)?X:[X];await cG(new M1(...G))(w,E)})}route($,w,E=XJ){return this.lazy(async(X)=>{var G;let A=await $(X);return(G=A===void 0||!w[A]?E:w[A])!==null&&G!==void 0?G:[]})}branch($,w,E){return this.lazy(async(X)=>await $(X)?w:E)}errorBoundary($,...w){let E=new M1(...w),X=cG(E);return this.use(async(G,A)=>{let N=!1,D=()=>(N=!0,Promise.resolve());try{await X(G,D)}catch(O){N=!1,await $(new GJ(O,G),D)}if(N)await A()}),E}}KH.Composer=M1});var qH=_((U00,PH)=>{var YX=1000,HX=YX*60,LX=HX*60,T1=LX*24,R2=T1*7,z2=T1*365.25;PH.exports=function($,w){w=w||{};var E=typeof $;if(E==="string"&&$.length>0)return B2($);else if(E==="number"&&isFinite($))return w.long?Q2($):I2($);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify($))};function B2($){if($=String($),$.length>100)return;var w=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec($);if(!w)return;var E=parseFloat(w[1]),X=(w[2]||"ms").toLowerCase();switch(X){case"years":case"year":case"yrs":case"yr":case"y":return E*z2;case"weeks":case"week":case"w":return E*R2;case"days":case"day":case"d":return E*T1;case"hours":case"hour":case"hrs":case"hr":case"h":return E*LX;case"minutes":case"minute":case"mins":case"min":case"m":return E*HX;case"seconds":case"second":case"secs":case"sec":case"s":return E*YX;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return E;default:return}}function I2($){var w=Math.abs($);if(w>=T1)return Math.round($/T1)+"d";if(w>=LX)return Math.round($/LX)+"h";if(w>=HX)return Math.round($/HX)+"m";if(w>=YX)return Math.round($/YX)+"s";return $+"ms"}function Q2($){var w=Math.abs($);if(w>=T1)return WD($,w,T1,"day");if(w>=LX)return WD($,w,LX,"hour");if(w>=HX)return WD($,w,HX,"minute");if(w>=YX)return WD($,w,YX,"second");return $+" ms"}function WD($,w,E,X){var G=w>=E*1.5;return Math.round($/E)+" "+X+(G?"s":"")}});var NJ=_((Y00,SH)=>{function K2($){E.debug=E,E.default=E,E.coerce=O,E.disable=N,E.enable=G,E.enabled=D,E.humanize=qH(),E.destroy=W,Object.keys($).forEach((J)=>{E[J]=$[J]}),E.names=[],E.skips=[],E.formatters={};function w(J){let Y=0;for(let H=0;H<J.length;H++)Y=(Y<<5)-Y+J.charCodeAt(H),Y|=0;return E.colors[Math.abs(Y)%E.colors.length]}E.selectColor=w;function E(J){let Y,H=null,L,F;function j(...M){if(!j.enabled)return;let R=j,B=Number(new Date),I=B-(Y||B);if(R.diff=I,R.prev=Y,R.curr=B,Y=B,M[0]=E.coerce(M[0]),typeof M[0]!=="string")M.unshift("%O");let C=0;M[0]=M[0].replace(/%([a-zA-Z%])/g,(k,n)=>{if(k==="%%")return"%";C++;let H0=E.formatters[n];if(typeof H0==="function"){let b0=M[C];k=H0.call(R,b0),M.splice(C,1),C--}return k}),E.formatArgs.call(R,M),(R.log||E.log).apply(R,M)}if(j.namespace=J,j.useColors=E.useColors(),j.color=E.selectColor(J),j.extend=X,j.destroy=E.destroy,Object.defineProperty(j,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(H!==null)return H;if(L!==E.namespaces)L=E.namespaces,F=E.enabled(J);return F},set:(M)=>{H=M}}),typeof E.init==="function")E.init(j);return j}function X(J,Y){let H=E(this.namespace+(typeof Y>"u"?":":Y)+J);return H.log=this.log,H}function G(J){E.save(J),E.namespaces=J,E.names=[],E.skips=[];let Y=(typeof J==="string"?J:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let H of Y)if(H[0]==="-")E.skips.push(H.slice(1));else E.names.push(H)}function A(J,Y){let H=0,L=0,F=-1,j=0;while(H<J.length)if(L<Y.length&&(Y[L]===J[H]||Y[L]==="*"))if(Y[L]==="*")F=L,j=H,L++;else H++,L++;else if(F!==-1)L=F+1,j++,H=j;else return!1;while(L<Y.length&&Y[L]==="*")L++;return L===Y.length}function N(){let J=[...E.names,...E.skips.map((Y)=>"-"+Y)].join(",");return E.enable(""),J}function D(J){for(let Y of E.skips)if(A(J,Y))return!1;for(let Y of E.names)if(A(J,Y))return!0;return!1}function O(J){if(J instanceof Error)return J.stack||J.message;return J}function W(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return E.enable(E.load()),E}SH.exports=K2});var bH=_((kH,JD)=>{kH.formatArgs=P2;kH.save=q2;kH.load=S2;kH.useColors=V2;kH.storage=k2();kH.destroy=(()=>{let $=!1;return()=>{if(!$)$=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();kH.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function V2(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let $;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&($=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt($[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function P2($){if($[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+$[0]+(this.useColors?"%c ":" ")+"+"+JD.exports.humanize(this.diff),!this.useColors)return;let w="color: "+this.color;$.splice(1,0,w,"color: inherit");let E=0,X=0;$[0].replace(/%[a-zA-Z%]/g,(G)=>{if(G==="%%")return;if(E++,G==="%c")X=E}),$.splice(X,0,w)}kH.log=console.debug||console.log||(()=>{});function q2($){try{if($)kH.storage.setItem("debug",$);else kH.storage.removeItem("debug")}catch(w){}}function S2(){let $;try{$=kH.storage.getItem("debug")||kH.storage.getItem("DEBUG")}catch(w){}if(!$&&typeof process<"u"&&"env"in process)$=process.env.DEBUG;return $}function k2(){try{return localStorage}catch($){}}JD.exports=NJ()(kH);var{formatters:b2}=JD.exports;b2.j=function($){try{return JSON.stringify($)}catch(w){return"[UnexpectedJSONParseError]: "+w.message}}});var ZH={};OE(ZH,{default:()=>r2,createSupportsColor:()=>DJ});import OJ from"process";import g2 from"os";import _H from"tty";function Lw($,w=globalThis.Deno?globalThis.Deno.args:OJ.argv){let E=$.startsWith("-")?"":$.length===1?"-":"--",X=w.indexOf(E+$),G=w.indexOf("--");return X!==-1&&(G===-1||X<G)}function u2(){if(!("FORCE_COLOR"in t0))return;if(t0.FORCE_COLOR==="true")return 1;if(t0.FORCE_COLOR==="false")return 0;if(t0.FORCE_COLOR.length===0)return 1;let $=Math.min(Number.parseInt(t0.FORCE_COLOR,10),3);if(![0,1,2,3].includes($))return;return $}function n2($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function h2($,{streamIsTTY:w,sniffFlags:E=!0}={}){let X=u2();if(X!==void 0)UD=X;let G=E?UD:X;if(G===0)return 0;if(E){if(Lw("color=16m")||Lw("color=full")||Lw("color=truecolor"))return 3;if(Lw("color=256"))return 2}if("TF_BUILD"in t0&&"AGENT_NAME"in t0)return 1;if($&&!w&&G===void 0)return 0;let A=G||0;if(t0.TERM==="dumb")return A;if(OJ.platform==="win32"){let N=g2.release().split(".");if(Number(N[0])>=10&&Number(N[2])>=10586)return Number(N[2])>=14931?3:2;return 1}if("CI"in t0){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((N)=>(N in t0)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((N)=>(N in t0))||t0.CI_NAME==="codeship")return 1;return A}if("TEAMCITY_VERSION"in t0)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(t0.TEAMCITY_VERSION)?1:0;if(t0.COLORTERM==="truecolor")return 3;if(t0.TERM==="xterm-kitty")return 3;if(t0.TERM==="xterm-ghostty")return 3;if(t0.TERM==="wezterm")return 3;if("TERM_PROGRAM"in t0){let N=Number.parseInt((t0.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(t0.TERM_PROGRAM){case"iTerm.app":return N>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(t0.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(t0.TERM))return 1;if("COLORTERM"in t0)return 1;return A}function DJ($,w={}){let E=h2($,{streamIsTTY:$&&$.isTTY,...w});return n2(E)}var t0,UD,c2,r2;var CH=T(()=>{({env:t0}=OJ);if(Lw("no-color")||Lw("no-colors")||Lw("color=false")||Lw("color=never"))UD=0;else if(Lw("color")||Lw("colors")||Lw("color=true")||Lw("color=always"))UD=1;c2={stdout:DJ({isTTY:_H.isatty(1)}),stderr:DJ({isTTY:_H.isatty(2)})},r2=c2});var yH=_((vH,HD)=>{var t2=b$("tty"),YD=b$("util");vH.init=s2;vH.log=p2;vH.formatArgs=m2;vH.save=d2;vH.load=l2;vH.useColors=o2;vH.destroy=YD.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");vH.colors=[6,2,3,4,5,1];try{let $=(CH(),u9(ZH));if($&&($.stderr||$).level>=2)vH.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch($){}vH.inspectOpts=Object.keys(process.env).filter(($)=>{return/^debug_/i.test($)}).reduce(($,w)=>{let E=w.substring(6).toLowerCase().replace(/_([a-z])/g,(G,A)=>{return A.toUpperCase()}),X=process.env[w];if(/^(yes|on|true|enabled)$/i.test(X))X=!0;else if(/^(no|off|false|disabled)$/i.test(X))X=!1;else if(X==="null")X=null;else X=Number(X);return $[E]=X,$},{});function o2(){return"colors"in vH.inspectOpts?Boolean(vH.inspectOpts.colors):t2.isatty(process.stderr.fd)}function m2($){let{namespace:w,useColors:E}=this;if(E){let X=this.color,G="\x1B[3"+(X<8?X:"8;5;"+X),A=` ${G};1m${w} \x1B[0m`;$[0]=A+$[0].split(`
388
389
  `).join(`
389
- `+J),$.push(G+"m+"+UA.exports.humanize(this.diff)+"\x1B[0m")}else $[0]=uS()+w+" "+$[0]}function uS(){if(SH.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function hS(...$){return process.stderr.write(OA.formatWithOptions(SH.inspectOpts,...$)+`
390
- `)}function cS($){if($)process.env.DEBUG=$;else delete process.env.DEBUG}function nS(){return process.env.DEBUG}function mS($){$.inspectOpts={};let w=Object.keys(SH.inspectOpts);for(let E=0;E<w.length;E++)$.inspectOpts[w[E]]=SH.inspectOpts[w[E]]}UA.exports=EN()(SH);var{formatters:qH}=UA.exports;qH.o=function($){return this.inspectOpts.colors=this.useColors,OA.inspect($,this.inspectOpts).split(`
391
- `).map((w)=>w.trim()).join(" ")};qH.O=function($){return this.inspectOpts.colors=this.useColors,OA.inspect($,this.inspectOpts)}});var ZH=Z((ae,JN)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)JN.exports=IH();else JN.exports=bH()});var mw=Z((AN)=>{Object.defineProperty(AN,"__esModule",{value:!0});AN.defaultAdapter=AN.itrToStream=AN.debug=void 0;AN.baseFetchConfig=Gk;var sS=V$("http"),aS=V$("https"),eS=V$("stream"),$k=ZH();Object.defineProperty(AN,"debug",{enumerable:!0,get:function(){return $k.debug}});var wk=($)=>eS.Readable.from($,{objectMode:!1});AN.itrToStream=wk;var Ek=new Map,Xk=new Map;function CH($,w,E){let X=$.get(w);if(X===void 0)X=E(),$.set(w,X);return X}function Gk($){if($.startsWith("https:"))return{compress:!0,agent:CH(Xk,$,()=>new aS.Agent({keepAlive:!0}))};else if($.startsWith("http:"))return{agent:CH(Ek,$,()=>new sS.Agent({keepAlive:!0}))};else return{}}AN.defaultAdapter="express"});var YA=Z((fH)=>{Object.defineProperty(fH,"__esModule",{value:!0});fH.HttpError=fH.GrammyError=void 0;fH.toGrammyError=Nk;fH.toHttpError=Ok;var Dk=mw(),vH=(0,Dk.debug)("grammy:warn");class DN extends Error{constructor($,w,E,X){var G;super(`${$} (${w.error_code}: ${w.description})`);this.method=E,this.payload=X,this.ok=!1,this.name="GrammyError",this.error_code=w.error_code,this.description=w.description,this.parameters=(G=w.parameters)!==null&&G!==void 0?G:{}}}fH.GrammyError=DN;function Nk($,w,E){switch($.error_code){case 401:vH("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.");break;case 409:vH("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.");break}return new DN(`Call to '${w}' failed!`,$,w,E)}class NN extends Error{constructor($,w){super($);this.error=w,this.name="HttpError"}}fH.HttpError=NN;function Wk($){return typeof $==="object"&&$!==null&&"status"in $&&"statusText"in $}function Ok($,w,E){let X=`Network request for '${$}' failed!`;if(Wk(E))X+=` (${E.status}: ${E.statusText})`;if(w&&E instanceof Error)X+=` ${E.message}`;return new NN(X,E)}});var Lk={};var uH=Z((Mw)=>{var Fk=Mw&&Mw.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),jk=Mw&&Mw.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Fk(w,$,E)};Object.defineProperty(Mw,"__esModule",{value:!0});Mw.InputFile=void 0;var yH=V$("fs"),Mk=V$("node-fetch"),HA=V$("path"),Rk=mw(),zk=(0,Rk.debug)("grammy:warn");jk(CO(Lk),Mw);class WN{constructor($,w){if(this.consumed=!1,this.fileData=$,w!==null&&w!==void 0||(w=this.guessFilename($)),this.filename=w,typeof $==="string"&&($.startsWith("http:")||$.startsWith("https:")))zk(`InputFile received the local file path '${$}' that looks like a URL. Is this a mistake?`)}guessFilename($){if(typeof $==="string")return(0,HA.basename)($);if("url"in $)return(0,HA.basename)($.url);if(!($ instanceof URL))return;if($.pathname!=="/"){let w=(0,HA.basename)($.pathname);if(w)return w}return(0,HA.basename)($.hostname)}async toRaw(){if(this.consumed)throw Error("Cannot reuse InputFile data source!");let $=this.fileData;if(typeof $==="string")return(0,yH.createReadStream)($);if($ instanceof URL)return $.protocol==="file"?(0,yH.createReadStream)($.pathname):gH($);if("url"in $)return gH($.url);if($ instanceof Uint8Array)return $;if(typeof $==="function")return new WN(await $()).toRaw();return this.consumed=!0,$}toJSON(){throw Error("InputFile instances must be sent via grammY")}}Mw.InputFile=WN;async function*gH($){let{body:w}=await(0,Mk.default)($);for await(let E of w){if(typeof E==="string")throw Error(`Could not transfer file, received string data instead of bytes from '${$}'`);yield E}}});var ON=Z((RE)=>{var Tk=RE&&RE.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),Bk=RE&&RE.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Tk(w,$,E)};Object.defineProperty(RE,"__esModule",{value:!0});Bk(uH(),RE)});var mH=Z((nH)=>{Object.defineProperty(nH,"__esModule",{value:!0});nH.requiresFormDataUpload=UN;nH.createJsonPayload=Ik;nH.createFormDataPayload=Vk;var Qk=mw(),LA=ON();function UN($){return $ instanceof LA.InputFile||typeof $==="object"&&$!==null&&Object.values($).some((w)=>Array.isArray(w)?w.some(UN):w instanceof LA.InputFile||UN(w))}function hH($){return JSON.stringify($,(w,E)=>E!==null&&E!==void 0?E:void 0)}function Ik($){return{method:"POST",headers:{"content-type":"application/json",connection:"keep-alive"},body:hH($)}}async function*Kk($,w){try{yield*$}catch(E){w(E)}}function Vk($,w){let E=Pk(),X=qk($,E),G=Kk(X,w),J=(0,Qk.itrToStream)(G);return{method:"POST",headers:{"content-type":`multipart/form-data; boundary=${E}`,connection:"keep-alive"},body:J}}function Pk(){return"----------"+cH(32)}function cH($=16){return Array.from(Array($)).map(()=>Math.random().toString(36)[2]||0).join("")}var uG=new TextEncoder;async function*qk($,w){let E=YN($);yield uG.encode(`--${w}\r
392
- `);let X=uG.encode(`\r
390
+ `+A),$.push(G+"m+"+HD.exports.humanize(this.diff)+"\x1B[0m")}else $[0]=i2()+w+" "+$[0]}function i2(){if(vH.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function p2(...$){return process.stderr.write(YD.formatWithOptions(vH.inspectOpts,...$)+`
391
+ `)}function d2($){if($)process.env.DEBUG=$;else delete process.env.DEBUG}function l2(){return process.env.DEBUG}function s2($){$.inspectOpts={};let w=Object.keys(vH.inspectOpts);for(let E=0;E<w.length;E++)$.inspectOpts[w[E]]=vH.inspectOpts[w[E]]}HD.exports=NJ()(vH);var{formatters:fH}=HD.exports;fH.o=function($){return this.inspectOpts.colors=this.useColors,YD.inspect($,this.inspectOpts).split(`
392
+ `).map((w)=>w.trim()).join(" ")};fH.O=function($){return this.inspectOpts.colors=this.useColors,YD.inspect($,this.inspectOpts)}});var gH=_((T00,WJ)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)WJ.exports=bH();else WJ.exports=yH()});var rE=_((JJ)=>{Object.defineProperty(JJ,"__esModule",{value:!0});JJ.defaultAdapter=JJ.itrToStream=JJ.debug=void 0;JJ.baseFetchConfig=Yk;var Ak=b$("http"),Nk=b$("https"),Dk=b$("stream"),Ok=gH();Object.defineProperty(JJ,"debug",{enumerable:!0,get:function(){return Ok.debug}});var Wk=($)=>Dk.Readable.from($,{objectMode:!1});JJ.itrToStream=Wk;var Jk=new Map,Uk=new Map;function uH($,w,E){let X=$.get(w);if(X===void 0)X=E(),$.set(w,X);return X}function Yk($){if($.startsWith("https:"))return{compress:!0,agent:uH(Uk,$,()=>new Nk.Agent({keepAlive:!0}))};else if($.startsWith("http:"))return{agent:uH(Jk,$,()=>new Ak.Agent({keepAlive:!0}))};else return{}}JJ.defaultAdapter="express"});var LD=_((cH)=>{Object.defineProperty(cH,"__esModule",{value:!0});cH.HttpError=cH.GrammyError=void 0;cH.toGrammyError=jk;cH.toHttpError=Tk;var Fk=rE(),hH=(0,Fk.debug)("grammy:warn");class UJ extends Error{constructor($,w,E,X){var G;super(`${$} (${w.error_code}: ${w.description})`);this.method=E,this.payload=X,this.ok=!1,this.name="GrammyError",this.error_code=w.error_code,this.description=w.description,this.parameters=(G=w.parameters)!==null&&G!==void 0?G:{}}}cH.GrammyError=UJ;function jk($,w,E){switch($.error_code){case 401:hH("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.");break;case 409:hH("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.");break}return new UJ(`Call to '${w}' failed!`,$,w,E)}class YJ extends Error{constructor($,w){super($);this.error=w,this.name="HttpError"}}cH.HttpError=YJ;function Mk($){return typeof $==="object"&&$!==null&&"status"in $&&"statusText"in $}function Tk($,w,E){let X=`Network request for '${$}' failed!`;if(Mk(E))X+=` (${E.status}: ${E.statusText})`;if(w&&E instanceof Error)X+=` ${E.message}`;return new YJ(X,E)}});var Ik={};var mH=_((jE)=>{var Qk=jE&&jE.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),Kk=jE&&jE.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Qk(w,$,E)};Object.defineProperty(jE,"__esModule",{value:!0});jE.InputFile=void 0;var tH=b$("fs"),Vk=b$("node-fetch"),FD=b$("path"),Pk=rE(),qk=(0,Pk.debug)("grammy:warn");Kk(u9(Ik),jE);class HJ{constructor($,w){if(this.consumed=!1,this.fileData=$,w!==null&&w!==void 0||(w=this.guessFilename($)),this.filename=w,typeof $==="string"&&($.startsWith("http:")||$.startsWith("https:")))qk(`InputFile received the local file path '${$}' that looks like a URL. Is this a mistake?`)}guessFilename($){if(typeof $==="string")return(0,FD.basename)($);if("url"in $)return(0,FD.basename)($.url);if(!($ instanceof URL))return;if($.pathname!=="/"){let w=(0,FD.basename)($.pathname);if(w)return w}return(0,FD.basename)($.hostname)}async toRaw(){if(this.consumed)throw Error("Cannot reuse InputFile data source!");let $=this.fileData;if(typeof $==="string")return(0,tH.createReadStream)($);if($ instanceof URL)return $.protocol==="file"?(0,tH.createReadStream)($.pathname):oH($);if("url"in $)return oH($.url);if($ instanceof Uint8Array)return $;if(typeof $==="function")return new HJ(await $()).toRaw();return this.consumed=!0,$}toJSON(){throw Error("InputFile instances must be sent via grammY")}}jE.InputFile=HJ;async function*oH($){let{body:w}=await(0,Vk.default)($);for await(let E of w){if(typeof E==="string")throw Error(`Could not transfer file, received string data instead of bytes from '${$}'`);yield E}}});var LJ=_((z1)=>{var Sk=z1&&z1.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),kk=z1&&z1.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Sk(w,$,E)};Object.defineProperty(z1,"__esModule",{value:!0});kk(mH(),z1)});var lH=_((dH)=>{Object.defineProperty(dH,"__esModule",{value:!0});dH.requiresFormDataUpload=FJ;dH.createJsonPayload=_k;dH.createFormDataPayload=Ck;var bk=rE(),jD=LJ();function FJ($){return $ instanceof jD.InputFile||typeof $==="object"&&$!==null&&Object.values($).some((w)=>Array.isArray(w)?w.some(FJ):w instanceof jD.InputFile||FJ(w))}function iH($){return JSON.stringify($,(w,E)=>E!==null&&E!==void 0?E:void 0)}function _k($){return{method:"POST",headers:{"content-type":"application/json",connection:"keep-alive"},body:iH($)}}async function*Zk($,w){try{yield*$}catch(E){w(E)}}function Ck($,w){let E=fk(),X=vk($,E),G=Zk(X,w),A=(0,bk.itrToStream)(G);return{method:"POST",headers:{"content-type":`multipart/form-data; boundary=${E}`,connection:"keep-alive"},body:A}}function fk(){return"----------"+pH(32)}function pH($=16){return Array.from(Array($)).map(()=>Math.random().toString(36)[2]||0).join("")}var tG=new TextEncoder;async function*vk($,w){let E=jJ($);yield tG.encode(`--${w}\r
393
+ `);let X=tG.encode(`\r
393
394
  --${w}\r
394
- `),G=!0;for(let[J,A]of Object.entries($)){if(A==null)continue;if(!G)yield X;yield Sk(J,A instanceof LA.InputFile?A.toJSON():typeof A==="object"?hH(A):A),G=!1}for(let{id:J,origin:A,file:D}of E){if(!G)yield X;yield*kk(J,A,D),G=!1}yield uG.encode(`\r
395
+ `),G=!0;for(let[A,N]of Object.entries($)){if(N==null)continue;if(!G)yield X;yield xk(A,N instanceof jD.InputFile?N.toJSON():typeof N==="object"?iH(N):N),G=!1}for(let{id:A,origin:N,file:D}of E){if(!G)yield X;yield*yk(A,N,D),G=!1}yield tG.encode(`\r
395
396
  --${w}--\r
396
- `)}function YN($){if(typeof $!=="object"||$===null)return[];return Object.entries($).flatMap(([w,E])=>{if(Array.isArray(E))return E.flatMap((X)=>YN(X));else if(E instanceof LA.InputFile){let X=cH();Object.assign(E,{toJSON:()=>`attach://${X}`});let G=w==="media"&&"type"in $&&typeof $.type==="string"?$.type:w;return{id:X,origin:G,file:E}}else return YN(E)})}function Sk($,w){return uG.encode(`content-disposition:form-data;name="${$}"\r
397
+ `)}function jJ($){if(typeof $!=="object"||$===null)return[];return Object.entries($).flatMap(([w,E])=>{if(Array.isArray(E))return E.flatMap((X)=>jJ(X));else if(E instanceof jD.InputFile){let X=pH();Object.assign(E,{toJSON:()=>`attach://${X}`});let G=w==="media"&&"type"in $&&typeof $.type==="string"?$.type:w;return{id:X,origin:G,file:E}}else return jJ(E)})}function xk($,w){return tG.encode(`content-disposition:form-data;name="${$}"\r
397
398
  \r
398
- ${w}`)}async function*kk($,w,E){let X=E.filename||`${w}.${bk(w)}`;if(X.includes("\r")||X.includes(`
399
+ ${w}`)}async function*yk($,w,E){let X=E.filename||`${w}.${gk(w)}`;if(X.includes("\r")||X.includes(`
399
400
  `))throw Error(`File paths cannot contain carriage-return (\\r) or newline (\\n) characters! Filename for property '${w}' was:
400
401
  """
401
402
  ${X}
402
- """`);yield uG.encode(`content-disposition:form-data;name="${$}";filename=${X}\r
403
+ """`);yield tG.encode(`content-disposition:form-data;name="${$}";filename=${X}\r
403
404
  content-type:application/octet-stream\r
404
405
  \r
405
- `);let G=await E.toRaw();if(G instanceof Uint8Array)yield G;else yield*G}function bk($){switch($){case"certificate":return"pem";case"photo":case"thumbnail":return"jpg";case"voice":return"ogg";case"audio":return"mp3";case"animation":case"video":case"video_note":return"mp4";case"sticker":return"webp";default:return"dat"}}});var HN=Z((FA)=>{Object.defineProperty(FA,"__esModule",{value:!0});FA.fetch=FA.AbortController=void 0;var vk=V$("abort-controller");Object.defineProperty(FA,"AbortController",{enumerable:!0,get:function(){return vk.AbortController}});var fk=V$("node-fetch");Object.defineProperty(FA,"fetch",{enumerable:!0,get:function(){return fk.default}})});var dH=Z((iH)=>{Object.defineProperty(iH,"__esModule",{value:!0});iH.createRawApi=uk;var pH=mw(),rH=YA(),jA=mH(),yk=(0,pH.debug)("grammy:core");function gk($,w){return(E,X,G)=>w($,E,X,G)}class oH{constructor($,w={},E={}){var X,G,J,A,D,N;this.token=$,this.webhookReplyEnvelope=E,this.hasUsedWebhookReply=!1,this.installedTransformers=[],this.call=async(L,F,j)=>{let M=F!==null&&F!==void 0?F:{};if(yk(`Calling ${L}`),j!==void 0)pk(L,M,j);let z=this.options,B=(0,jA.requiresFormDataUpload)(M);if(this.webhookReplyEnvelope.send!==void 0&&!this.hasUsedWebhookReply&&!B&&z.canUseWebhookReply(L)){this.hasUsedWebhookReply=!0;let K0=(0,jA.createJsonPayload)({...M,method:L});return await this.webhookReplyEnvelope.send(K0.body),{ok:!0,result:!0}}let Q=rk(j),k=nk(Q,z.timeoutSeconds,L),v=mk(Q),C=z.buildUrl(z.apiRoot,this.token,L,z.environment),n=B?(0,jA.createFormDataPayload)(M,(K0)=>v.catch(K0)):(0,jA.createJsonPayload)(M),T0=Q.signal,f0={...z.baseFetchConfig,signal:T0,...n},d0=[this.fetch(C,f0).then((K0)=>K0.json()),v.promise,k.promise];try{return await Promise.race(d0)}catch(K0){throw(0,rH.toHttpError)(L,z.sensitiveLogs,K0)}finally{if(k.handle!==void 0)clearTimeout(k.handle)}};let W=(X=w.apiRoot)!==null&&X!==void 0?X:"https://api.telegram.org",O=(G=w.environment)!==null&&G!==void 0?G:"prod",{fetch:Y}=w,H=Y!==null&&Y!==void 0?Y:tH.fetch;if(this.options={apiRoot:W,environment:O,buildUrl:(J=w.buildUrl)!==null&&J!==void 0?J:hk,timeoutSeconds:(A=w.timeoutSeconds)!==null&&A!==void 0?A:500,baseFetchConfig:{...(0,pH.baseFetchConfig)(W),...w.baseFetchConfig},canUseWebhookReply:(D=w.canUseWebhookReply)!==null&&D!==void 0?D:()=>!1,sensitiveLogs:(N=w.sensitiveLogs)!==null&&N!==void 0?N:!1,fetch:(...L)=>H(...L)},this.fetch=this.options.fetch,this.options.apiRoot.endsWith("/"))throw Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0,this.options.apiRoot.length-1)}' instead of '${this.options.apiRoot}')`)}use(...$){return this.call=$.reduce(gk,this.call),this.installedTransformers.push(...$),this}async callApi($,w,E){let X=await this.call($,w,E);if(X.ok)return X.result;else throw(0,rH.toGrammyError)(X,$,w)}}function uk($,w,E){let X=new oH($,w,E),G={get(N,W){return W==="toJSON"?"__internal":W==="getMe"||W==="getWebhookInfo"||W==="getForumTopicIconStickers"||W==="getAvailableGifts"||W==="logOut"||W==="close"||W==="getMyStarBalance"||W==="removeMyProfilePhoto"?X.callApi.bind(X,W,{}):X.callApi.bind(X,W)},...ck},J=new Proxy({},G),A=X.installedTransformers,D={raw:J,installedTransformers:A,use:(...N)=>{return X.use(...N),D}};return D}var hk=($,w,E,X)=>{return`${$}/bot${w}/${X==="test"?"test/":""}${E}`},ck={set(){return!1},defineProperty(){return!1},deleteProperty(){return!1},ownKeys(){return[]}};function nk($,w,E){let X=void 0;return{promise:new Promise((J,A)=>{X=setTimeout(()=>{let D=`Request to '${E}' timed out after ${w} seconds`;A(Error(D)),$.abort()},1000*w)}),handle:X}}function mk($){let w=(X)=>{throw X};return{promise:new Promise((X,G)=>{w=(J)=>{G(J),$.abort()}}),catch:w}}function rk($){let w=new tH.AbortController;if($===void 0)return w;let E=$;function X(){w.abort(),E.removeEventListener("abort",X)}if(E.aborted)X();else E.addEventListener("abort",X);return{abort:X,signal:w.signal}}function pk($,w,E){if(typeof(E===null||E===void 0?void 0:E.addEventListener)==="function")return;let X=JSON.stringify(w);if(X.length>20)X=X.substring(0,16)+" ...";let G=JSON.stringify(E);if(G.length>20)G=G.substring(0,16)+" ...";throw Error(`Incorrect abort signal instance found! You passed two payloads to '${$}' but you should merge the second one containing '${G}' into the first one containing '${X}'! If you are using context shortcuts, you may want to use a method on 'ctx.api' instead.
406
+ `);let G=await E.toRaw();if(G instanceof Uint8Array)yield G;else yield*G}function gk($){switch($){case"certificate":return"pem";case"photo":case"thumbnail":return"jpg";case"voice":return"ogg";case"audio":return"mp3";case"animation":case"video":case"video_note":return"mp4";case"sticker":return"webp";default:return"dat"}}});var MJ=_((MD)=>{Object.defineProperty(MD,"__esModule",{value:!0});MD.fetch=MD.AbortController=void 0;var ck=b$("abort-controller");Object.defineProperty(MD,"AbortController",{enumerable:!0,get:function(){return ck.AbortController}});var rk=b$("node-fetch");Object.defineProperty(MD,"fetch",{enumerable:!0,get:function(){return rk.default}})});var EL=_((wL)=>{Object.defineProperty(wL,"__esModule",{value:!0});wL.createRawApi=ik;var aH=rE(),sH=LD(),TD=lH(),ok=(0,aH.debug)("grammy:core");function mk($,w){return(E,X,G)=>w($,E,X,G)}class eH{constructor($,w={},E={}){var X,G,A,N,D,O;this.token=$,this.webhookReplyEnvelope=E,this.hasUsedWebhookReply=!1,this.installedTransformers=[],this.call=async(L,F,j)=>{let M=F!==null&&F!==void 0?F:{};if(ok(`Calling ${L}`),j!==void 0)ek(L,M,j);let R=this.options,B=(0,TD.requiresFormDataUpload)(M);if(this.webhookReplyEnvelope.send!==void 0&&!this.hasUsedWebhookReply&&!B&&R.canUseWebhookReply(L)){this.hasUsedWebhookReply=!0;let V0=(0,TD.createJsonPayload)({...M,method:L});return await this.webhookReplyEnvelope.send(V0.body),{ok:!0,result:!0}}let I=ak(j),C=lk(I,R.timeoutSeconds,L),v=sk(I),k=R.buildUrl(R.apiRoot,this.token,L,R.environment),n=B?(0,TD.createFormDataPayload)(M,(V0)=>v.catch(V0)):(0,TD.createJsonPayload)(M),H0=I.signal,b0={...R.baseFetchConfig,signal:H0,...n},l0=[this.fetch(k,b0).then((V0)=>V0.json()),v.promise,C.promise];try{return await Promise.race(l0)}catch(V0){throw(0,sH.toHttpError)(L,R.sensitiveLogs,V0)}finally{if(C.handle!==void 0)clearTimeout(C.handle)}};let W=(X=w.apiRoot)!==null&&X!==void 0?X:"https://api.telegram.org",J=(G=w.environment)!==null&&G!==void 0?G:"prod",{fetch:Y}=w,H=Y!==null&&Y!==void 0?Y:$L.fetch;if(this.options={apiRoot:W,environment:J,buildUrl:(A=w.buildUrl)!==null&&A!==void 0?A:pk,timeoutSeconds:(N=w.timeoutSeconds)!==null&&N!==void 0?N:500,baseFetchConfig:{...(0,aH.baseFetchConfig)(W),...w.baseFetchConfig},canUseWebhookReply:(D=w.canUseWebhookReply)!==null&&D!==void 0?D:()=>!1,sensitiveLogs:(O=w.sensitiveLogs)!==null&&O!==void 0?O:!1,fetch:(...L)=>H(...L)},this.fetch=this.options.fetch,this.options.apiRoot.endsWith("/"))throw Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0,this.options.apiRoot.length-1)}' instead of '${this.options.apiRoot}')`)}use(...$){return this.call=$.reduce(mk,this.call),this.installedTransformers.push(...$),this}async callApi($,w,E){let X=await this.call($,w,E);if(X.ok)return X.result;else throw(0,sH.toGrammyError)(X,$,w)}}function ik($,w,E){let X=new eH($,w,E),G={get(O,W){return W==="toJSON"?"__internal":W==="getMe"||W==="getWebhookInfo"||W==="getForumTopicIconStickers"||W==="getAvailableGifts"||W==="logOut"||W==="close"||W==="getMyStarBalance"||W==="removeMyProfilePhoto"?X.callApi.bind(X,W,{}):X.callApi.bind(X,W)},...dk},A=new Proxy({},G),N=X.installedTransformers,D={raw:A,installedTransformers:N,use:(...O)=>{return X.use(...O),D}};return D}var pk=($,w,E,X)=>{return`${$}/bot${w}/${X==="test"?"test/":""}${E}`},dk={set(){return!1},defineProperty(){return!1},deleteProperty(){return!1},ownKeys(){return[]}};function lk($,w,E){let X=void 0;return{promise:new Promise((A,N)=>{X=setTimeout(()=>{let D=`Request to '${E}' timed out after ${w} seconds`;N(Error(D)),$.abort()},1000*w)}),handle:X}}function sk($){let w=(X)=>{throw X};return{promise:new Promise((X,G)=>{w=(A)=>{G(A),$.abort()}}),catch:w}}function ak($){let w=new $L.AbortController;if($===void 0)return w;let E=$;function X(){w.abort(),E.removeEventListener("abort",X)}if(E.aborted)X();else E.addEventListener("abort",X);return{abort:X,signal:w.signal}}function ek($,w,E){if(typeof(E===null||E===void 0?void 0:E.addEventListener)==="function")return;let X=JSON.stringify(w);if(X.length>20)X=X.substring(0,16)+" ...";let G=JSON.stringify(E);if(G.length>20)G=G.substring(0,16)+" ...";throw Error(`Incorrect abort signal instance found! You passed two payloads to '${$}' but you should merge the second one containing '${G}' into the first one containing '${X}'! If you are using context shortcuts, you may want to use a method on 'ctx.api' instead.
406
407
 
407
- If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`)}var tH=HN()});var LN=Z((sH)=>{Object.defineProperty(sH,"__esModule",{value:!0});sH.Api=void 0;var tk=dH();class lH{constructor($,w,E){this.token=$,this.options=w;let{raw:X,use:G,installedTransformers:J}=(0,tk.createRawApi)($,w,E);this.raw=X,this.config={use:G,installedTransformers:()=>J.slice()}}getUpdates($,w){return this.raw.getUpdates({...$},w)}setWebhook($,w,E){return this.raw.setWebhook({url:$,...w},E)}deleteWebhook($,w){return this.raw.deleteWebhook({...$},w)}getWebhookInfo($){return this.raw.getWebhookInfo($)}getMe($){return this.raw.getMe($)}logOut($){return this.raw.logOut($)}close($){return this.raw.close($)}sendMessage($,w,E,X){return this.raw.sendMessage({chat_id:$,text:w,...E},X)}sendMessageDraft($,w,E,X,G){return this.raw.sendMessageDraft({chat_id:$,draft_id:w,text:E,...X},G)}forwardMessage($,w,E,X,G){return this.raw.forwardMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}forwardMessages($,w,E,X,G){return this.raw.forwardMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}copyMessage($,w,E,X,G){return this.raw.copyMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}copyMessages($,w,E,X,G){return this.raw.copyMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}sendPhoto($,w,E,X){return this.raw.sendPhoto({chat_id:$,photo:w,...E},X)}sendAudio($,w,E,X){return this.raw.sendAudio({chat_id:$,audio:w,...E},X)}sendDocument($,w,E,X){return this.raw.sendDocument({chat_id:$,document:w,...E},X)}sendVideo($,w,E,X){return this.raw.sendVideo({chat_id:$,video:w,...E},X)}sendAnimation($,w,E,X){return this.raw.sendAnimation({chat_id:$,animation:w,...E},X)}sendVoice($,w,E,X){return this.raw.sendVoice({chat_id:$,voice:w,...E},X)}sendVideoNote($,w,E,X){return this.raw.sendVideoNote({chat_id:$,video_note:w,...E},X)}sendMediaGroup($,w,E,X){return this.raw.sendMediaGroup({chat_id:$,media:w,...E},X)}sendLocation($,w,E,X,G){return this.raw.sendLocation({chat_id:$,latitude:w,longitude:E,...X},G)}editMessageLiveLocation($,w,E,X,G,J){return this.raw.editMessageLiveLocation({chat_id:$,message_id:w,latitude:E,longitude:X,...G},J)}editMessageLiveLocationInline($,w,E,X,G){return this.raw.editMessageLiveLocation({inline_message_id:$,latitude:w,longitude:E,...X},G)}stopMessageLiveLocation($,w,E,X){return this.raw.stopMessageLiveLocation({chat_id:$,message_id:w,...E},X)}stopMessageLiveLocationInline($,w,E){return this.raw.stopMessageLiveLocation({inline_message_id:$,...w},E)}sendPaidMedia($,w,E,X,G){return this.raw.sendPaidMedia({chat_id:$,star_count:w,media:E,...X},G)}sendVenue($,w,E,X,G,J,A){return this.raw.sendVenue({chat_id:$,latitude:w,longitude:E,title:X,address:G,...J},A)}sendContact($,w,E,X,G){return this.raw.sendContact({chat_id:$,phone_number:w,first_name:E,...X},G)}sendPoll($,w,E,X,G){let J=E.map((A)=>typeof A==="string"?{text:A}:A);return this.raw.sendPoll({chat_id:$,question:w,options:J,...X},G)}sendChecklist($,w,E,X,G){return this.raw.sendChecklist({business_connection_id:$,chat_id:w,checklist:E,...X},G)}editMessageChecklist($,w,E,X,G,J){return this.raw.editMessageChecklist({business_connection_id:$,chat_id:w,message_id:E,checklist:X,...G},J)}sendDice($,w,E,X){return this.raw.sendDice({chat_id:$,emoji:w,...E},X)}setMessageReaction($,w,E,X,G){return this.raw.setMessageReaction({chat_id:$,message_id:w,reaction:E,...X},G)}sendChatAction($,w,E,X){return this.raw.sendChatAction({chat_id:$,action:w,...E},X)}getUserProfilePhotos($,w,E){return this.raw.getUserProfilePhotos({user_id:$,...w},E)}getUserProfileAudios($,w,E){return this.raw.getUserProfileAudios({user_id:$,...w},E)}setUserEmojiStatus($,w,E){return this.raw.setUserEmojiStatus({user_id:$,...w},E)}getUserChatBoosts($,w,E){return this.raw.getUserChatBoosts({chat_id:$,user_id:w},E)}getUserGifts($,w,E){return this.raw.getUserGifts({user_id:$,...w},E)}getChatGifts($,w,E){return this.raw.getChatGifts({chat_id:$,...w},E)}getBusinessConnection($,w){return this.raw.getBusinessConnection({business_connection_id:$},w)}getFile($,w){return this.raw.getFile({file_id:$},w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E,X){return this.raw.banChatMember({chat_id:$,user_id:w,...E},X)}unbanChatMember($,w,E,X){return this.raw.unbanChatMember({chat_id:$,user_id:w,...E},X)}restrictChatMember($,w,E,X,G){return this.raw.restrictChatMember({chat_id:$,user_id:w,permissions:E,...X},G)}promoteChatMember($,w,E,X){return this.raw.promoteChatMember({chat_id:$,user_id:w,...E},X)}setChatAdministratorCustomTitle($,w,E,X){return this.raw.setChatAdministratorCustomTitle({chat_id:$,user_id:w,custom_title:E},X)}setChatMemberTag($,w,E,X){return this.raw.setChatMemberTag({chat_id:$,user_id:w,tag:E},X)}banChatSenderChat($,w,E){return this.raw.banChatSenderChat({chat_id:$,sender_chat_id:w},E)}unbanChatSenderChat($,w,E){return this.raw.unbanChatSenderChat({chat_id:$,sender_chat_id:w},E)}setChatPermissions($,w,E,X){return this.raw.setChatPermissions({chat_id:$,permissions:w,...E},X)}exportChatInviteLink($,w){return this.raw.exportChatInviteLink({chat_id:$},w)}createChatInviteLink($,w,E){return this.raw.createChatInviteLink({chat_id:$,...w},E)}editChatInviteLink($,w,E,X){return this.raw.editChatInviteLink({chat_id:$,invite_link:w,...E},X)}createChatSubscriptionInviteLink($,w,E,X,G){return this.raw.createChatSubscriptionInviteLink({chat_id:$,subscription_period:w,subscription_price:E,...X},G)}editChatSubscriptionInviteLink($,w,E,X){return this.raw.editChatSubscriptionInviteLink({chat_id:$,invite_link:w,...E},X)}revokeChatInviteLink($,w,E){return this.raw.revokeChatInviteLink({chat_id:$,invite_link:w},E)}approveChatJoinRequest($,w,E){return this.raw.approveChatJoinRequest({chat_id:$,user_id:w},E)}declineChatJoinRequest($,w,E){return this.raw.declineChatJoinRequest({chat_id:$,user_id:w},E)}approveSuggestedPost($,w,E,X){return this.raw.approveSuggestedPost({chat_id:$,message_id:w,...E},X)}declineSuggestedPost($,w,E,X){return this.raw.declineSuggestedPost({chat_id:$,message_id:w,...E},X)}setChatPhoto($,w,E){return this.raw.setChatPhoto({chat_id:$,photo:w},E)}deleteChatPhoto($,w){return this.raw.deleteChatPhoto({chat_id:$},w)}setChatTitle($,w,E){return this.raw.setChatTitle({chat_id:$,title:w},E)}setChatDescription($,w,E){return this.raw.setChatDescription({chat_id:$,description:w},E)}pinChatMessage($,w,E,X){return this.raw.pinChatMessage({chat_id:$,message_id:w,...E},X)}unpinChatMessage($,w,E,X){return this.raw.unpinChatMessage({chat_id:$,message_id:w,...E},X)}unpinAllChatMessages($,w){return this.raw.unpinAllChatMessages({chat_id:$},w)}leaveChat($,w){return this.raw.leaveChat({chat_id:$},w)}getChat($,w){return this.raw.getChat({chat_id:$},w)}getChatAdministrators($,w){return this.raw.getChatAdministrators({chat_id:$},w)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($,w){return this.raw.getChatMemberCount({chat_id:$},w)}getChatMember($,w,E){return this.raw.getChatMember({chat_id:$,user_id:w},E)}setChatStickerSet($,w,E){return this.raw.setChatStickerSet({chat_id:$,sticker_set_name:w},E)}deleteChatStickerSet($,w){return this.raw.deleteChatStickerSet({chat_id:$},w)}getForumTopicIconStickers($){return this.raw.getForumTopicIconStickers($)}createForumTopic($,w,E,X){return this.raw.createForumTopic({chat_id:$,name:w,...E},X)}editForumTopic($,w,E,X){return this.raw.editForumTopic({chat_id:$,message_thread_id:w,...E},X)}closeForumTopic($,w,E){return this.raw.closeForumTopic({chat_id:$,message_thread_id:w},E)}reopenForumTopic($,w,E){return this.raw.reopenForumTopic({chat_id:$,message_thread_id:w},E)}deleteForumTopic($,w,E){return this.raw.deleteForumTopic({chat_id:$,message_thread_id:w},E)}unpinAllForumTopicMessages($,w,E){return this.raw.unpinAllForumTopicMessages({chat_id:$,message_thread_id:w},E)}editGeneralForumTopic($,w,E){return this.raw.editGeneralForumTopic({chat_id:$,name:w},E)}closeGeneralForumTopic($,w){return this.raw.closeGeneralForumTopic({chat_id:$},w)}reopenGeneralForumTopic($,w){return this.raw.reopenGeneralForumTopic({chat_id:$},w)}hideGeneralForumTopic($,w){return this.raw.hideGeneralForumTopic({chat_id:$},w)}unhideGeneralForumTopic($,w){return this.raw.unhideGeneralForumTopic({chat_id:$},w)}unpinAllGeneralForumTopicMessages($,w){return this.raw.unpinAllGeneralForumTopicMessages({chat_id:$},w)}answerCallbackQuery($,w,E){return this.raw.answerCallbackQuery({callback_query_id:$,...w},E)}setMyName($,w,E){return this.raw.setMyName({name:$,...w},E)}getMyName($,w){return this.raw.getMyName($!==null&&$!==void 0?$:{},w)}setMyCommands($,w,E){return this.raw.setMyCommands({commands:$,...w},E)}deleteMyCommands($,w){return this.raw.deleteMyCommands({...$},w)}getMyCommands($,w){return this.raw.getMyCommands({...$},w)}setMyDescription($,w,E){return this.raw.setMyDescription({description:$,...w},E)}getMyDescription($,w){return this.raw.getMyDescription({...$},w)}setMyShortDescription($,w,E){return this.raw.setMyShortDescription({short_description:$,...w},E)}getMyShortDescription($,w){return this.raw.getMyShortDescription({...$},w)}setMyProfilePhoto($,w){return this.raw.setMyProfilePhoto({photo:$},w)}removeMyProfilePhoto($){return this.raw.removeMyProfilePhoto($)}setChatMenuButton($,w){return this.raw.setChatMenuButton({...$},w)}getChatMenuButton($,w){return this.raw.getChatMenuButton({...$},w)}setMyDefaultAdministratorRights($,w){return this.raw.setMyDefaultAdministratorRights({...$},w)}getMyDefaultAdministratorRights($,w){return this.raw.getMyDefaultAdministratorRights({...$},w)}getMyStarBalance($){return this.raw.getMyStarBalance($)}editMessageText($,w,E,X,G){return this.raw.editMessageText({chat_id:$,message_id:w,text:E,...X},G)}editMessageTextInline($,w,E,X){return this.raw.editMessageText({inline_message_id:$,text:w,...E},X)}editMessageCaption($,w,E,X){return this.raw.editMessageCaption({chat_id:$,message_id:w,...E},X)}editMessageCaptionInline($,w,E){return this.raw.editMessageCaption({inline_message_id:$,...w},E)}editMessageMedia($,w,E,X,G){return this.raw.editMessageMedia({chat_id:$,message_id:w,media:E,...X},G)}editMessageMediaInline($,w,E,X){return this.raw.editMessageMedia({inline_message_id:$,media:w,...E},X)}editMessageReplyMarkup($,w,E,X){return this.raw.editMessageReplyMarkup({chat_id:$,message_id:w,...E},X)}editMessageReplyMarkupInline($,w,E){return this.raw.editMessageReplyMarkup({inline_message_id:$,...w},E)}stopPoll($,w,E,X){return this.raw.stopPoll({chat_id:$,message_id:w,...E},X)}deleteMessage($,w,E){return this.raw.deleteMessage({chat_id:$,message_id:w},E)}deleteMessages($,w,E){return this.raw.deleteMessages({chat_id:$,message_ids:w},E)}deleteBusinessMessages($,w,E){return this.raw.deleteBusinessMessages({business_connection_id:$,message_ids:w},E)}setBusinessAccountName($,w,E,X){return this.raw.setBusinessAccountName({business_connection_id:$,first_name:w,...E},X)}setBusinessAccountUsername($,w,E){return this.raw.setBusinessAccountUsername({business_connection_id:$,username:w},E)}setBusinessAccountBio($,w,E){return this.raw.setBusinessAccountBio({business_connection_id:$,bio:w},E)}setBusinessAccountProfilePhoto($,w,E,X){return this.raw.setBusinessAccountProfilePhoto({business_connection_id:$,photo:w,...E},X)}removeBusinessAccountProfilePhoto($,w,E){return this.raw.removeBusinessAccountProfilePhoto({business_connection_id:$,...w},E)}setBusinessAccountGiftSettings($,w,E,X){return this.raw.setBusinessAccountGiftSettings({business_connection_id:$,show_gift_button:w,accepted_gift_types:E},X)}getBusinessAccountStarBalance($,w){return this.raw.getBusinessAccountStarBalance({business_connection_id:$},w)}transferBusinessAccountStars($,w,E){return this.raw.transferBusinessAccountStars({business_connection_id:$,star_count:w},E)}getBusinessAccountGifts($,w,E){return this.raw.getBusinessAccountGifts({business_connection_id:$,...w},E)}convertGiftToStars($,w,E){return this.raw.convertGiftToStars({business_connection_id:$,owned_gift_id:w},E)}upgradeGift($,w,E,X){return this.raw.upgradeGift({business_connection_id:$,owned_gift_id:w,...E},X)}transferGift($,w,E,X,G){return this.raw.transferGift({business_connection_id:$,owned_gift_id:w,new_owner_chat_id:E,star_count:X},G)}postStory($,w,E,X,G){return this.raw.postStory({business_connection_id:$,content:w,active_period:E,...X},G)}repostStory($,w,E,X,G,J){return this.raw.repostStory({business_connection_id:$,from_chat_id:w,from_story_id:E,active_period:X,...G},J)}editStory($,w,E,X,G){return this.raw.editStory({business_connection_id:$,story_id:w,content:E,...X},G)}deleteStory($,w,E){return this.raw.deleteStory({business_connection_id:$,story_id:w},E)}sendSticker($,w,E,X){return this.raw.sendSticker({chat_id:$,sticker:w,...E},X)}getStickerSet($,w){return this.raw.getStickerSet({name:$},w)}getCustomEmojiStickers($,w){return this.raw.getCustomEmojiStickers({custom_emoji_ids:$},w)}uploadStickerFile($,w,E,X){return this.raw.uploadStickerFile({user_id:$,sticker_format:w,sticker:E},X)}createNewStickerSet($,w,E,X,G,J){return this.raw.createNewStickerSet({user_id:$,name:w,title:E,stickers:X,...G},J)}addStickerToSet($,w,E,X){return this.raw.addStickerToSet({user_id:$,name:w,sticker:E},X)}setStickerPositionInSet($,w,E){return this.raw.setStickerPositionInSet({sticker:$,position:w},E)}deleteStickerFromSet($,w){return this.raw.deleteStickerFromSet({sticker:$},w)}replaceStickerInSet($,w,E,X,G){return this.raw.replaceStickerInSet({user_id:$,name:w,old_sticker:E,sticker:X},G)}setStickerEmojiList($,w,E){return this.raw.setStickerEmojiList({sticker:$,emoji_list:w},E)}setStickerKeywords($,w,E){return this.raw.setStickerKeywords({sticker:$,keywords:w},E)}setStickerMaskPosition($,w,E){return this.raw.setStickerMaskPosition({sticker:$,mask_position:w},E)}setStickerSetTitle($,w,E){return this.raw.setStickerSetTitle({name:$,title:w},E)}deleteStickerSet($,w){return this.raw.deleteStickerSet({name:$},w)}setStickerSetThumbnail($,w,E,X,G){return this.raw.setStickerSetThumbnail({name:$,user_id:w,thumbnail:E,format:X},G)}setCustomEmojiStickerSetThumbnail($,w,E){return this.raw.setCustomEmojiStickerSetThumbnail({name:$,custom_emoji_id:w},E)}getAvailableGifts($){return this.raw.getAvailableGifts($)}sendGift($,w,E,X){return this.raw.sendGift({user_id:$,gift_id:w,...E},X)}giftPremiumSubscription($,w,E,X,G){return this.raw.giftPremiumSubscription({user_id:$,month_count:w,star_count:E,...X},G)}sendGiftToChannel($,w,E,X){return this.raw.sendGift({chat_id:$,gift_id:w,...E},X)}answerInlineQuery($,w,E,X){return this.raw.answerInlineQuery({inline_query_id:$,results:w,...E},X)}answerWebAppQuery($,w,E){return this.raw.answerWebAppQuery({web_app_query_id:$,result:w},E)}savePreparedInlineMessage($,w,E,X){return this.raw.savePreparedInlineMessage({user_id:$,result:w,...E},X)}sendInvoice($,w,E,X,G,J,A,D){return this.raw.sendInvoice({chat_id:$,title:w,description:E,payload:X,currency:G,prices:J,...A},D)}createInvoiceLink($,w,E,X,G,J,A,D){return this.raw.createInvoiceLink({title:$,description:w,payload:E,provider_token:X,currency:G,prices:J,...A},D)}answerShippingQuery($,w,E,X){return this.raw.answerShippingQuery({shipping_query_id:$,ok:w,...E},X)}answerPreCheckoutQuery($,w,E,X){return this.raw.answerPreCheckoutQuery({pre_checkout_query_id:$,ok:w,...E},X)}getStarTransactions($,w){return this.raw.getStarTransactions({...$},w)}refundStarPayment($,w,E){return this.raw.refundStarPayment({user_id:$,telegram_payment_charge_id:w},E)}editUserStarSubscription($,w,E,X){return this.raw.editUserStarSubscription({user_id:$,telegram_payment_charge_id:w,is_canceled:E},X)}verifyUser($,w,E){return this.raw.verifyUser({user_id:$,...w},E)}verifyChat($,w,E){return this.raw.verifyChat({chat_id:$,...w},E)}removeUserVerification($,w){return this.raw.removeUserVerification({user_id:$},w)}removeChatVerification($,w){return this.raw.removeChatVerification({chat_id:$},w)}readBusinessMessage($,w,E,X){return this.raw.readBusinessMessage({business_connection_id:$,chat_id:w,message_id:E},X)}setPassportDataErrors($,w,E){return this.raw.setPassportDataErrors({user_id:$,errors:w},E)}sendGame($,w,E,X){return this.raw.sendGame({chat_id:$,game_short_name:w,...E},X)}setGameScore($,w,E,X,G,J){return this.raw.setGameScore({chat_id:$,message_id:w,user_id:E,score:X,...G},J)}setGameScoreInline($,w,E,X,G){return this.raw.setGameScore({inline_message_id:$,user_id:w,score:E,...X},G)}getGameHighScores($,w,E,X){return this.raw.getGameHighScores({chat_id:$,message_id:w,user_id:E},X)}getGameHighScoresInline($,w,E){return this.raw.getGameHighScores({inline_message_id:$,user_id:w},E)}}sH.Api=lH});var zN=Z((RN)=>{Object.defineProperty(RN,"__esModule",{value:!0});RN.Bot=RN.BotError=RN.DEFAULT_UPDATE_TYPES=void 0;var hG=wN();Object.defineProperty(RN,"BotError",{enumerable:!0,get:function(){return hG.BotError}});var ik=AA(),eH=LN(),FN=YA(),$L=GA(),MN=mw(),$w=(0,MN.debug)("grammy:bot"),dk=(0,MN.debug)("grammy:warn"),YX=(0,MN.debug)("grammy:error");RN.DEFAULT_UPDATE_TYPES=["message","edited_message","channel_post","edited_channel_post","business_connection","business_message","edited_business_message","deleted_business_messages","inline_query","chosen_inline_result","callback_query","shipping_query","pre_checkout_query","purchased_paid_media","poll","poll_answer","my_chat_member","chat_join_request","chat_boost","removed_chat_boost"];class EL extends hG.Composer{constructor($,w){var E;super();if(this.token=$,this.pollingRunning=!1,this.lastTriedUpdateId=0,this.observedUpdateTypes=new Set,this.errorHandler=async(X)=>{var G,J;if(console.error("Error in middleware while handling update",(J=(G=X.ctx)===null||G===void 0?void 0:G.update)===null||J===void 0?void 0:J.update_id,X.error),console.error("No error handler was set!"),console.error("Set your own error handler with `bot.catch = ...`"),this.pollingRunning)console.error("Stopping bot"),await this.stop();throw X},!$)throw Error("Empty token!");this.me=w===null||w===void 0?void 0:w.botInfo,this.clientConfig=w===null||w===void 0?void 0:w.client,this.ContextConstructor=(E=w===null||w===void 0?void 0:w.ContextConstructor)!==null&&E!==void 0?E:ik.Context,this.api=new eH.Api($,this.clientConfig)}set botInfo($){this.me=$}get botInfo(){if(this.me===void 0)throw Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!");return this.me}on($,...w){for(let[E]of(0,$L.parse)($).flatMap($L.preprocess))this.observedUpdateTypes.add(E);return super.on($,...w)}reaction($,...w){return this.observedUpdateTypes.add("message_reaction"),super.reaction($,...w)}isInited(){return this.me!==void 0}async init($){var w;if(!this.isInited()){$w("Initializing bot"),(w=this.mePromise)!==null&&w!==void 0||(this.mePromise=wL(()=>this.api.getMe($),$));let E;try{E=await this.mePromise}finally{this.mePromise=void 0}if(this.me===void 0)this.me=E;else $w("Bot info was set by now, will not overwrite")}$w(`I am ${this.me.username}!`)}async handleUpdates($){for(let w of $){this.lastTriedUpdateId=w.update_id;try{await this.handleUpdate(w)}catch(E){if(E instanceof hG.BotError)await this.errorHandler(E);else throw console.error("FATAL: grammY unable to handle:",E),E}}}async handleUpdate($,w){if(this.me===void 0)throw Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object.");$w(`Processing update ${$.update_id}`);let E=new eH.Api(this.token,this.clientConfig,w),X=this.api.config.installedTransformers();if(X.length>0)E.config.use(...X);let G=new this.ContextConstructor($,E,this.me);try{await(0,hG.run)(this.middleware(),G)}catch(J){throw YX(`Error in middleware for update ${$.update_id}`),new hG.BotError(J,G)}}async start($){var w,E,X;let G=[];if(!this.isInited())G.push(this.init((w=this.pollingAbortController)===null||w===void 0?void 0:w.signal));if(this.pollingRunning){await Promise.all(G),$w("Simple long polling already running!");return}this.pollingRunning=!0,this.pollingAbortController=new ak.AbortController;try{G.push(wL(async()=>{var J;await this.api.deleteWebhook({drop_pending_updates:$===null||$===void 0?void 0:$.drop_pending_updates},(J=this.pollingAbortController)===null||J===void 0?void 0:J.signal)},(E=this.pollingAbortController)===null||E===void 0?void 0:E.signal)),await Promise.all(G),await((X=$===null||$===void 0?void 0:$.onStart)===null||X===void 0?void 0:X.call($,this.botInfo))}catch(J){throw this.pollingRunning=!1,this.pollingAbortController=void 0,J}if(!this.pollingRunning)return;lk(this.observedUpdateTypes,$===null||$===void 0?void 0:$.allowed_updates),this.use=sk,$w("Starting simple long polling"),await this.loop($),$w("Middleware is done running")}async stop(){var $;if(this.pollingRunning){$w("Stopping bot, saving update offset"),this.pollingRunning=!1,($=this.pollingAbortController)===null||$===void 0||$.abort();let w=this.lastTriedUpdateId+1;await this.api.getUpdates({offset:w,limit:1}).finally(()=>this.pollingAbortController=void 0)}else $w("Bot is not running!")}isRunning(){return this.pollingRunning}catch($){this.errorHandler=$}async loop($){var w,E;let X=$===null||$===void 0?void 0:$.limit,G=(w=$===null||$===void 0?void 0:$.timeout)!==null&&w!==void 0?w:30,J=(E=$===null||$===void 0?void 0:$.allowed_updates)!==null&&E!==void 0?E:[];try{while(this.pollingRunning){let A=await this.fetchUpdates({limit:X,timeout:G,allowed_updates:J});if(A===void 0)break;await this.handleUpdates(A),J=void 0}}finally{this.pollingRunning=!1}}async fetchUpdates({limit:$,timeout:w,allowed_updates:E}){var X;let G=this.lastTriedUpdateId+1,J=void 0;do try{J=await this.api.getUpdates({offset:G,limit:$,timeout:w,allowed_updates:E},(X=this.pollingAbortController)===null||X===void 0?void 0:X.signal)}catch(A){await this.handlePollingError(A)}while(J===void 0&&this.pollingRunning);return J}async handlePollingError($){var w;if(!this.pollingRunning){$w("Pending getUpdates request cancelled");return}let E=3;if($ instanceof FN.GrammyError){if(YX($.message),$.error_code===401||$.error_code===409)throw $;else if($.error_code===429)YX("Bot API server is closing."),E=(w=$.parameters.retry_after)!==null&&w!==void 0?w:E}else YX($);YX(`Call to getUpdates failed, retrying in ${E} seconds ...`),await jN(E)}}RN.Bot=EL;async function wL($,w){let X=50;async function G(A){let D=!1,N="rethrow";if(A instanceof FN.HttpError)D=!0,N="retry";else if(A instanceof FN.GrammyError){if(A.error_code>=500)D=!0,N="retry";else if(A.error_code===429){let W=A.parameters.retry_after;if(typeof W==="number")await jN(W,w),X=50;else D=!0;N="retry"}}if(D){if(X!==50)await jN(X,w);X=Math.min(1200000,2*X)}return N}let J={ok:!1};while(!J.ok)try{J={ok:!0,value:await $()}}catch(A){switch(YX(A),await G(A)){case"retry":continue;case"rethrow":throw A}}return J.value}async function jN($,w){let E,X;function G(){if(X===null||X===void 0||X(Error("Aborted delay")),E!==void 0)clearTimeout(E)}try{await new Promise((J,A)=>{if(X=A,w===null||w===void 0?void 0:w.aborted){G();return}w===null||w===void 0||w.addEventListener("abort",G),E=setTimeout(J,1000*$)})}finally{w===null||w===void 0||w.removeEventListener("abort",G)}}function lk($,w=RN.DEFAULT_UPDATE_TYPES){let E=Array.from($).filter((X)=>!w.includes(X));if(E.length>0)dk(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${E.map((X)=>`'${X}'`).join(", ")}`)}function sk(){throw Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs
408
+ If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`)}var $L=MJ()});var TJ=_((GL)=>{Object.defineProperty(GL,"__esModule",{value:!0});GL.Api=void 0;var wb=EL();class XL{constructor($,w,E){this.token=$,this.options=w;let{raw:X,use:G,installedTransformers:A}=(0,wb.createRawApi)($,w,E);this.raw=X,this.config={use:G,installedTransformers:()=>A.slice()}}getUpdates($,w){return this.raw.getUpdates({...$},w)}setWebhook($,w,E){return this.raw.setWebhook({url:$,...w},E)}deleteWebhook($,w){return this.raw.deleteWebhook({...$},w)}getWebhookInfo($){return this.raw.getWebhookInfo($)}getMe($){return this.raw.getMe($)}logOut($){return this.raw.logOut($)}close($){return this.raw.close($)}sendMessage($,w,E,X){return this.raw.sendMessage({chat_id:$,text:w,...E},X)}sendMessageDraft($,w,E,X,G){return this.raw.sendMessageDraft({chat_id:$,draft_id:w,text:E,...X},G)}forwardMessage($,w,E,X,G){return this.raw.forwardMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}forwardMessages($,w,E,X,G){return this.raw.forwardMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}copyMessage($,w,E,X,G){return this.raw.copyMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}copyMessages($,w,E,X,G){return this.raw.copyMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}sendPhoto($,w,E,X){return this.raw.sendPhoto({chat_id:$,photo:w,...E},X)}sendAudio($,w,E,X){return this.raw.sendAudio({chat_id:$,audio:w,...E},X)}sendDocument($,w,E,X){return this.raw.sendDocument({chat_id:$,document:w,...E},X)}sendVideo($,w,E,X){return this.raw.sendVideo({chat_id:$,video:w,...E},X)}sendAnimation($,w,E,X){return this.raw.sendAnimation({chat_id:$,animation:w,...E},X)}sendVoice($,w,E,X){return this.raw.sendVoice({chat_id:$,voice:w,...E},X)}sendVideoNote($,w,E,X){return this.raw.sendVideoNote({chat_id:$,video_note:w,...E},X)}sendMediaGroup($,w,E,X){return this.raw.sendMediaGroup({chat_id:$,media:w,...E},X)}sendLocation($,w,E,X,G){return this.raw.sendLocation({chat_id:$,latitude:w,longitude:E,...X},G)}editMessageLiveLocation($,w,E,X,G,A){return this.raw.editMessageLiveLocation({chat_id:$,message_id:w,latitude:E,longitude:X,...G},A)}editMessageLiveLocationInline($,w,E,X,G){return this.raw.editMessageLiveLocation({inline_message_id:$,latitude:w,longitude:E,...X},G)}stopMessageLiveLocation($,w,E,X){return this.raw.stopMessageLiveLocation({chat_id:$,message_id:w,...E},X)}stopMessageLiveLocationInline($,w,E){return this.raw.stopMessageLiveLocation({inline_message_id:$,...w},E)}sendPaidMedia($,w,E,X,G){return this.raw.sendPaidMedia({chat_id:$,star_count:w,media:E,...X},G)}sendVenue($,w,E,X,G,A,N){return this.raw.sendVenue({chat_id:$,latitude:w,longitude:E,title:X,address:G,...A},N)}sendContact($,w,E,X,G){return this.raw.sendContact({chat_id:$,phone_number:w,first_name:E,...X},G)}sendPoll($,w,E,X,G){let A=E.map((N)=>typeof N==="string"?{text:N}:N);return this.raw.sendPoll({chat_id:$,question:w,options:A,...X},G)}sendChecklist($,w,E,X,G){return this.raw.sendChecklist({business_connection_id:$,chat_id:w,checklist:E,...X},G)}editMessageChecklist($,w,E,X,G,A){return this.raw.editMessageChecklist({business_connection_id:$,chat_id:w,message_id:E,checklist:X,...G},A)}sendDice($,w,E,X){return this.raw.sendDice({chat_id:$,emoji:w,...E},X)}setMessageReaction($,w,E,X,G){return this.raw.setMessageReaction({chat_id:$,message_id:w,reaction:E,...X},G)}sendChatAction($,w,E,X){return this.raw.sendChatAction({chat_id:$,action:w,...E},X)}getUserProfilePhotos($,w,E){return this.raw.getUserProfilePhotos({user_id:$,...w},E)}getUserProfileAudios($,w,E){return this.raw.getUserProfileAudios({user_id:$,...w},E)}setUserEmojiStatus($,w,E){return this.raw.setUserEmojiStatus({user_id:$,...w},E)}getUserChatBoosts($,w,E){return this.raw.getUserChatBoosts({chat_id:$,user_id:w},E)}getUserGifts($,w,E){return this.raw.getUserGifts({user_id:$,...w},E)}getChatGifts($,w,E){return this.raw.getChatGifts({chat_id:$,...w},E)}getBusinessConnection($,w){return this.raw.getBusinessConnection({business_connection_id:$},w)}getFile($,w){return this.raw.getFile({file_id:$},w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E,X){return this.raw.banChatMember({chat_id:$,user_id:w,...E},X)}unbanChatMember($,w,E,X){return this.raw.unbanChatMember({chat_id:$,user_id:w,...E},X)}restrictChatMember($,w,E,X,G){return this.raw.restrictChatMember({chat_id:$,user_id:w,permissions:E,...X},G)}promoteChatMember($,w,E,X){return this.raw.promoteChatMember({chat_id:$,user_id:w,...E},X)}setChatAdministratorCustomTitle($,w,E,X){return this.raw.setChatAdministratorCustomTitle({chat_id:$,user_id:w,custom_title:E},X)}setChatMemberTag($,w,E,X){return this.raw.setChatMemberTag({chat_id:$,user_id:w,tag:E},X)}banChatSenderChat($,w,E){return this.raw.banChatSenderChat({chat_id:$,sender_chat_id:w},E)}unbanChatSenderChat($,w,E){return this.raw.unbanChatSenderChat({chat_id:$,sender_chat_id:w},E)}setChatPermissions($,w,E,X){return this.raw.setChatPermissions({chat_id:$,permissions:w,...E},X)}exportChatInviteLink($,w){return this.raw.exportChatInviteLink({chat_id:$},w)}createChatInviteLink($,w,E){return this.raw.createChatInviteLink({chat_id:$,...w},E)}editChatInviteLink($,w,E,X){return this.raw.editChatInviteLink({chat_id:$,invite_link:w,...E},X)}createChatSubscriptionInviteLink($,w,E,X,G){return this.raw.createChatSubscriptionInviteLink({chat_id:$,subscription_period:w,subscription_price:E,...X},G)}editChatSubscriptionInviteLink($,w,E,X){return this.raw.editChatSubscriptionInviteLink({chat_id:$,invite_link:w,...E},X)}revokeChatInviteLink($,w,E){return this.raw.revokeChatInviteLink({chat_id:$,invite_link:w},E)}approveChatJoinRequest($,w,E){return this.raw.approveChatJoinRequest({chat_id:$,user_id:w},E)}declineChatJoinRequest($,w,E){return this.raw.declineChatJoinRequest({chat_id:$,user_id:w},E)}approveSuggestedPost($,w,E,X){return this.raw.approveSuggestedPost({chat_id:$,message_id:w,...E},X)}declineSuggestedPost($,w,E,X){return this.raw.declineSuggestedPost({chat_id:$,message_id:w,...E},X)}setChatPhoto($,w,E){return this.raw.setChatPhoto({chat_id:$,photo:w},E)}deleteChatPhoto($,w){return this.raw.deleteChatPhoto({chat_id:$},w)}setChatTitle($,w,E){return this.raw.setChatTitle({chat_id:$,title:w},E)}setChatDescription($,w,E){return this.raw.setChatDescription({chat_id:$,description:w},E)}pinChatMessage($,w,E,X){return this.raw.pinChatMessage({chat_id:$,message_id:w,...E},X)}unpinChatMessage($,w,E,X){return this.raw.unpinChatMessage({chat_id:$,message_id:w,...E},X)}unpinAllChatMessages($,w){return this.raw.unpinAllChatMessages({chat_id:$},w)}leaveChat($,w){return this.raw.leaveChat({chat_id:$},w)}getChat($,w){return this.raw.getChat({chat_id:$},w)}getChatAdministrators($,w){return this.raw.getChatAdministrators({chat_id:$},w)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($,w){return this.raw.getChatMemberCount({chat_id:$},w)}getChatMember($,w,E){return this.raw.getChatMember({chat_id:$,user_id:w},E)}setChatStickerSet($,w,E){return this.raw.setChatStickerSet({chat_id:$,sticker_set_name:w},E)}deleteChatStickerSet($,w){return this.raw.deleteChatStickerSet({chat_id:$},w)}getForumTopicIconStickers($){return this.raw.getForumTopicIconStickers($)}createForumTopic($,w,E,X){return this.raw.createForumTopic({chat_id:$,name:w,...E},X)}editForumTopic($,w,E,X){return this.raw.editForumTopic({chat_id:$,message_thread_id:w,...E},X)}closeForumTopic($,w,E){return this.raw.closeForumTopic({chat_id:$,message_thread_id:w},E)}reopenForumTopic($,w,E){return this.raw.reopenForumTopic({chat_id:$,message_thread_id:w},E)}deleteForumTopic($,w,E){return this.raw.deleteForumTopic({chat_id:$,message_thread_id:w},E)}unpinAllForumTopicMessages($,w,E){return this.raw.unpinAllForumTopicMessages({chat_id:$,message_thread_id:w},E)}editGeneralForumTopic($,w,E){return this.raw.editGeneralForumTopic({chat_id:$,name:w},E)}closeGeneralForumTopic($,w){return this.raw.closeGeneralForumTopic({chat_id:$},w)}reopenGeneralForumTopic($,w){return this.raw.reopenGeneralForumTopic({chat_id:$},w)}hideGeneralForumTopic($,w){return this.raw.hideGeneralForumTopic({chat_id:$},w)}unhideGeneralForumTopic($,w){return this.raw.unhideGeneralForumTopic({chat_id:$},w)}unpinAllGeneralForumTopicMessages($,w){return this.raw.unpinAllGeneralForumTopicMessages({chat_id:$},w)}answerCallbackQuery($,w,E){return this.raw.answerCallbackQuery({callback_query_id:$,...w},E)}setMyName($,w,E){return this.raw.setMyName({name:$,...w},E)}getMyName($,w){return this.raw.getMyName($!==null&&$!==void 0?$:{},w)}setMyCommands($,w,E){return this.raw.setMyCommands({commands:$,...w},E)}deleteMyCommands($,w){return this.raw.deleteMyCommands({...$},w)}getMyCommands($,w){return this.raw.getMyCommands({...$},w)}setMyDescription($,w,E){return this.raw.setMyDescription({description:$,...w},E)}getMyDescription($,w){return this.raw.getMyDescription({...$},w)}setMyShortDescription($,w,E){return this.raw.setMyShortDescription({short_description:$,...w},E)}getMyShortDescription($,w){return this.raw.getMyShortDescription({...$},w)}setMyProfilePhoto($,w){return this.raw.setMyProfilePhoto({photo:$},w)}removeMyProfilePhoto($){return this.raw.removeMyProfilePhoto($)}setChatMenuButton($,w){return this.raw.setChatMenuButton({...$},w)}getChatMenuButton($,w){return this.raw.getChatMenuButton({...$},w)}setMyDefaultAdministratorRights($,w){return this.raw.setMyDefaultAdministratorRights({...$},w)}getMyDefaultAdministratorRights($,w){return this.raw.getMyDefaultAdministratorRights({...$},w)}getMyStarBalance($){return this.raw.getMyStarBalance($)}editMessageText($,w,E,X,G){return this.raw.editMessageText({chat_id:$,message_id:w,text:E,...X},G)}editMessageTextInline($,w,E,X){return this.raw.editMessageText({inline_message_id:$,text:w,...E},X)}editMessageCaption($,w,E,X){return this.raw.editMessageCaption({chat_id:$,message_id:w,...E},X)}editMessageCaptionInline($,w,E){return this.raw.editMessageCaption({inline_message_id:$,...w},E)}editMessageMedia($,w,E,X,G){return this.raw.editMessageMedia({chat_id:$,message_id:w,media:E,...X},G)}editMessageMediaInline($,w,E,X){return this.raw.editMessageMedia({inline_message_id:$,media:w,...E},X)}editMessageReplyMarkup($,w,E,X){return this.raw.editMessageReplyMarkup({chat_id:$,message_id:w,...E},X)}editMessageReplyMarkupInline($,w,E){return this.raw.editMessageReplyMarkup({inline_message_id:$,...w},E)}stopPoll($,w,E,X){return this.raw.stopPoll({chat_id:$,message_id:w,...E},X)}deleteMessage($,w,E){return this.raw.deleteMessage({chat_id:$,message_id:w},E)}deleteMessages($,w,E){return this.raw.deleteMessages({chat_id:$,message_ids:w},E)}deleteBusinessMessages($,w,E){return this.raw.deleteBusinessMessages({business_connection_id:$,message_ids:w},E)}setBusinessAccountName($,w,E,X){return this.raw.setBusinessAccountName({business_connection_id:$,first_name:w,...E},X)}setBusinessAccountUsername($,w,E){return this.raw.setBusinessAccountUsername({business_connection_id:$,username:w},E)}setBusinessAccountBio($,w,E){return this.raw.setBusinessAccountBio({business_connection_id:$,bio:w},E)}setBusinessAccountProfilePhoto($,w,E,X){return this.raw.setBusinessAccountProfilePhoto({business_connection_id:$,photo:w,...E},X)}removeBusinessAccountProfilePhoto($,w,E){return this.raw.removeBusinessAccountProfilePhoto({business_connection_id:$,...w},E)}setBusinessAccountGiftSettings($,w,E,X){return this.raw.setBusinessAccountGiftSettings({business_connection_id:$,show_gift_button:w,accepted_gift_types:E},X)}getBusinessAccountStarBalance($,w){return this.raw.getBusinessAccountStarBalance({business_connection_id:$},w)}transferBusinessAccountStars($,w,E){return this.raw.transferBusinessAccountStars({business_connection_id:$,star_count:w},E)}getBusinessAccountGifts($,w,E){return this.raw.getBusinessAccountGifts({business_connection_id:$,...w},E)}convertGiftToStars($,w,E){return this.raw.convertGiftToStars({business_connection_id:$,owned_gift_id:w},E)}upgradeGift($,w,E,X){return this.raw.upgradeGift({business_connection_id:$,owned_gift_id:w,...E},X)}transferGift($,w,E,X,G){return this.raw.transferGift({business_connection_id:$,owned_gift_id:w,new_owner_chat_id:E,star_count:X},G)}postStory($,w,E,X,G){return this.raw.postStory({business_connection_id:$,content:w,active_period:E,...X},G)}repostStory($,w,E,X,G,A){return this.raw.repostStory({business_connection_id:$,from_chat_id:w,from_story_id:E,active_period:X,...G},A)}editStory($,w,E,X,G){return this.raw.editStory({business_connection_id:$,story_id:w,content:E,...X},G)}deleteStory($,w,E){return this.raw.deleteStory({business_connection_id:$,story_id:w},E)}sendSticker($,w,E,X){return this.raw.sendSticker({chat_id:$,sticker:w,...E},X)}getStickerSet($,w){return this.raw.getStickerSet({name:$},w)}getCustomEmojiStickers($,w){return this.raw.getCustomEmojiStickers({custom_emoji_ids:$},w)}uploadStickerFile($,w,E,X){return this.raw.uploadStickerFile({user_id:$,sticker_format:w,sticker:E},X)}createNewStickerSet($,w,E,X,G,A){return this.raw.createNewStickerSet({user_id:$,name:w,title:E,stickers:X,...G},A)}addStickerToSet($,w,E,X){return this.raw.addStickerToSet({user_id:$,name:w,sticker:E},X)}setStickerPositionInSet($,w,E){return this.raw.setStickerPositionInSet({sticker:$,position:w},E)}deleteStickerFromSet($,w){return this.raw.deleteStickerFromSet({sticker:$},w)}replaceStickerInSet($,w,E,X,G){return this.raw.replaceStickerInSet({user_id:$,name:w,old_sticker:E,sticker:X},G)}setStickerEmojiList($,w,E){return this.raw.setStickerEmojiList({sticker:$,emoji_list:w},E)}setStickerKeywords($,w,E){return this.raw.setStickerKeywords({sticker:$,keywords:w},E)}setStickerMaskPosition($,w,E){return this.raw.setStickerMaskPosition({sticker:$,mask_position:w},E)}setStickerSetTitle($,w,E){return this.raw.setStickerSetTitle({name:$,title:w},E)}deleteStickerSet($,w){return this.raw.deleteStickerSet({name:$},w)}setStickerSetThumbnail($,w,E,X,G){return this.raw.setStickerSetThumbnail({name:$,user_id:w,thumbnail:E,format:X},G)}setCustomEmojiStickerSetThumbnail($,w,E){return this.raw.setCustomEmojiStickerSetThumbnail({name:$,custom_emoji_id:w},E)}getAvailableGifts($){return this.raw.getAvailableGifts($)}sendGift($,w,E,X){return this.raw.sendGift({user_id:$,gift_id:w,...E},X)}giftPremiumSubscription($,w,E,X,G){return this.raw.giftPremiumSubscription({user_id:$,month_count:w,star_count:E,...X},G)}sendGiftToChannel($,w,E,X){return this.raw.sendGift({chat_id:$,gift_id:w,...E},X)}answerInlineQuery($,w,E,X){return this.raw.answerInlineQuery({inline_query_id:$,results:w,...E},X)}answerWebAppQuery($,w,E){return this.raw.answerWebAppQuery({web_app_query_id:$,result:w},E)}savePreparedInlineMessage($,w,E,X){return this.raw.savePreparedInlineMessage({user_id:$,result:w,...E},X)}sendInvoice($,w,E,X,G,A,N,D){return this.raw.sendInvoice({chat_id:$,title:w,description:E,payload:X,currency:G,prices:A,...N},D)}createInvoiceLink($,w,E,X,G,A,N,D){return this.raw.createInvoiceLink({title:$,description:w,payload:E,provider_token:X,currency:G,prices:A,...N},D)}answerShippingQuery($,w,E,X){return this.raw.answerShippingQuery({shipping_query_id:$,ok:w,...E},X)}answerPreCheckoutQuery($,w,E,X){return this.raw.answerPreCheckoutQuery({pre_checkout_query_id:$,ok:w,...E},X)}getStarTransactions($,w){return this.raw.getStarTransactions({...$},w)}refundStarPayment($,w,E){return this.raw.refundStarPayment({user_id:$,telegram_payment_charge_id:w},E)}editUserStarSubscription($,w,E,X){return this.raw.editUserStarSubscription({user_id:$,telegram_payment_charge_id:w,is_canceled:E},X)}verifyUser($,w,E){return this.raw.verifyUser({user_id:$,...w},E)}verifyChat($,w,E){return this.raw.verifyChat({chat_id:$,...w},E)}removeUserVerification($,w){return this.raw.removeUserVerification({user_id:$},w)}removeChatVerification($,w){return this.raw.removeChatVerification({chat_id:$},w)}readBusinessMessage($,w,E,X){return this.raw.readBusinessMessage({business_connection_id:$,chat_id:w,message_id:E},X)}setPassportDataErrors($,w,E){return this.raw.setPassportDataErrors({user_id:$,errors:w},E)}sendGame($,w,E,X){return this.raw.sendGame({chat_id:$,game_short_name:w,...E},X)}setGameScore($,w,E,X,G,A){return this.raw.setGameScore({chat_id:$,message_id:w,user_id:E,score:X,...G},A)}setGameScoreInline($,w,E,X,G){return this.raw.setGameScore({inline_message_id:$,user_id:w,score:E,...X},G)}getGameHighScores($,w,E,X){return this.raw.getGameHighScores({chat_id:$,message_id:w,user_id:E},X)}getGameHighScoresInline($,w,E){return this.raw.getGameHighScores({inline_message_id:$,user_id:w},E)}}GL.Api=XL});var QJ=_((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});IJ.Bot=IJ.BotError=IJ.DEFAULT_UPDATE_TYPES=void 0;var oG=AJ();Object.defineProperty(IJ,"BotError",{enumerable:!0,get:function(){return oG.BotError}});var Eb=OD(),NL=TJ(),RJ=LD(),DL=ND(),BJ=rE(),ew=(0,BJ.debug)("grammy:bot"),Xb=(0,BJ.debug)("grammy:warn"),FX=(0,BJ.debug)("grammy:error");IJ.DEFAULT_UPDATE_TYPES=["message","edited_message","channel_post","edited_channel_post","business_connection","business_message","edited_business_message","deleted_business_messages","inline_query","chosen_inline_result","callback_query","shipping_query","pre_checkout_query","purchased_paid_media","poll","poll_answer","my_chat_member","chat_join_request","chat_boost","removed_chat_boost"];class WL extends oG.Composer{constructor($,w){var E;super();if(this.token=$,this.pollingRunning=!1,this.lastTriedUpdateId=0,this.observedUpdateTypes=new Set,this.errorHandler=async(X)=>{var G,A;if(console.error("Error in middleware while handling update",(A=(G=X.ctx)===null||G===void 0?void 0:G.update)===null||A===void 0?void 0:A.update_id,X.error),console.error("No error handler was set!"),console.error("Set your own error handler with `bot.catch = ...`"),this.pollingRunning)console.error("Stopping bot"),await this.stop();throw X},!$)throw Error("Empty token!");this.me=w===null||w===void 0?void 0:w.botInfo,this.clientConfig=w===null||w===void 0?void 0:w.client,this.ContextConstructor=(E=w===null||w===void 0?void 0:w.ContextConstructor)!==null&&E!==void 0?E:Eb.Context,this.api=new NL.Api($,this.clientConfig)}set botInfo($){this.me=$}get botInfo(){if(this.me===void 0)throw Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!");return this.me}on($,...w){for(let[E]of(0,DL.parse)($).flatMap(DL.preprocess))this.observedUpdateTypes.add(E);return super.on($,...w)}reaction($,...w){return this.observedUpdateTypes.add("message_reaction"),super.reaction($,...w)}isInited(){return this.me!==void 0}async init($){var w;if(!this.isInited()){ew("Initializing bot"),(w=this.mePromise)!==null&&w!==void 0||(this.mePromise=OL(()=>this.api.getMe($),$));let E;try{E=await this.mePromise}finally{this.mePromise=void 0}if(this.me===void 0)this.me=E;else ew("Bot info was set by now, will not overwrite")}ew(`I am ${this.me.username}!`)}async handleUpdates($){for(let w of $){this.lastTriedUpdateId=w.update_id;try{await this.handleUpdate(w)}catch(E){if(E instanceof oG.BotError)await this.errorHandler(E);else throw console.error("FATAL: grammY unable to handle:",E),E}}}async handleUpdate($,w){if(this.me===void 0)throw Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object.");ew(`Processing update ${$.update_id}`);let E=new NL.Api(this.token,this.clientConfig,w),X=this.api.config.installedTransformers();if(X.length>0)E.config.use(...X);let G=new this.ContextConstructor($,E,this.me);try{await(0,oG.run)(this.middleware(),G)}catch(A){throw FX(`Error in middleware for update ${$.update_id}`),new oG.BotError(A,G)}}async start($){var w,E,X;let G=[];if(!this.isInited())G.push(this.init((w=this.pollingAbortController)===null||w===void 0?void 0:w.signal));if(this.pollingRunning){await Promise.all(G),ew("Simple long polling already running!");return}this.pollingRunning=!0,this.pollingAbortController=new Nb.AbortController;try{G.push(OL(async()=>{var A;await this.api.deleteWebhook({drop_pending_updates:$===null||$===void 0?void 0:$.drop_pending_updates},(A=this.pollingAbortController)===null||A===void 0?void 0:A.signal)},(E=this.pollingAbortController)===null||E===void 0?void 0:E.signal)),await Promise.all(G),await((X=$===null||$===void 0?void 0:$.onStart)===null||X===void 0?void 0:X.call($,this.botInfo))}catch(A){throw this.pollingRunning=!1,this.pollingAbortController=void 0,A}if(!this.pollingRunning)return;Gb(this.observedUpdateTypes,$===null||$===void 0?void 0:$.allowed_updates),this.use=Ab,ew("Starting simple long polling"),await this.loop($),ew("Middleware is done running")}async stop(){var $;if(this.pollingRunning){ew("Stopping bot, saving update offset"),this.pollingRunning=!1,($=this.pollingAbortController)===null||$===void 0||$.abort();let w=this.lastTriedUpdateId+1;await this.api.getUpdates({offset:w,limit:1}).finally(()=>this.pollingAbortController=void 0)}else ew("Bot is not running!")}isRunning(){return this.pollingRunning}catch($){this.errorHandler=$}async loop($){var w,E;let X=$===null||$===void 0?void 0:$.limit,G=(w=$===null||$===void 0?void 0:$.timeout)!==null&&w!==void 0?w:30,A=(E=$===null||$===void 0?void 0:$.allowed_updates)!==null&&E!==void 0?E:[];try{while(this.pollingRunning){let N=await this.fetchUpdates({limit:X,timeout:G,allowed_updates:A});if(N===void 0)break;await this.handleUpdates(N),A=void 0}}finally{this.pollingRunning=!1}}async fetchUpdates({limit:$,timeout:w,allowed_updates:E}){var X;let G=this.lastTriedUpdateId+1,A=void 0;do try{A=await this.api.getUpdates({offset:G,limit:$,timeout:w,allowed_updates:E},(X=this.pollingAbortController)===null||X===void 0?void 0:X.signal)}catch(N){await this.handlePollingError(N)}while(A===void 0&&this.pollingRunning);return A}async handlePollingError($){var w;if(!this.pollingRunning){ew("Pending getUpdates request cancelled");return}let E=3;if($ instanceof RJ.GrammyError){if(FX($.message),$.error_code===401||$.error_code===409)throw $;else if($.error_code===429)FX("Bot API server is closing."),E=(w=$.parameters.retry_after)!==null&&w!==void 0?w:E}else FX($);FX(`Call to getUpdates failed, retrying in ${E} seconds ...`),await zJ(E)}}IJ.Bot=WL;async function OL($,w){let X=50;async function G(N){let D=!1,O="rethrow";if(N instanceof RJ.HttpError)D=!0,O="retry";else if(N instanceof RJ.GrammyError){if(N.error_code>=500)D=!0,O="retry";else if(N.error_code===429){let W=N.parameters.retry_after;if(typeof W==="number")await zJ(W,w),X=50;else D=!0;O="retry"}}if(D){if(X!==50)await zJ(X,w);X=Math.min(1200000,2*X)}return O}let A={ok:!1};while(!A.ok)try{A={ok:!0,value:await $()}}catch(N){switch(FX(N),await G(N)){case"retry":continue;case"rethrow":throw N}}return A.value}async function zJ($,w){let E,X;function G(){if(X===null||X===void 0||X(Error("Aborted delay")),E!==void 0)clearTimeout(E)}try{await new Promise((A,N)=>{if(X=N,w===null||w===void 0?void 0:w.aborted){G();return}w===null||w===void 0||w.addEventListener("abort",G),E=setTimeout(A,1000*$)})}finally{w===null||w===void 0||w.removeEventListener("abort",G)}}function Gb($,w=IJ.DEFAULT_UPDATE_TYPES){let E=Array.from($).filter((X)=>!w.includes(X));if(E.length>0)Xb(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${E.map((X)=>`'${X}'`).join(", ")}`)}function Ab(){throw Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs
408
409
 
409
- On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`)}var ak=HN()});var DL=Z((AL)=>{Object.defineProperty(AL,"__esModule",{value:!0});AL.API_CONSTANTS=void 0;var JL=zN(),ek=[...JL.DEFAULT_UPDATE_TYPES,"chat_member","message_reaction","message_reaction_count"],$b={can_send_messages:!0,can_send_audios:!0,can_send_documents:!0,can_send_photos:!0,can_send_videos:!0,can_send_video_notes:!0,can_send_voice_notes:!0,can_send_polls:!0,can_send_other_messages:!0,can_add_web_page_previews:!0,can_change_info:!0,can_invite_users:!0,can_edit_tag:!0,can_pin_messages:!0,can_manage_topics:!0};AL.API_CONSTANTS={DEFAULT_UPDATE_TYPES:JL.DEFAULT_UPDATE_TYPES,ALL_UPDATE_TYPES:ek,ALL_CHAT_PERMISSIONS:$b};Object.freeze(AL.API_CONSTANTS)});var OL=Z((NL)=>{Object.defineProperty(NL,"__esModule",{value:!0});NL.InlineQueryResultBuilder=void 0;function O$($){return{...$,...BN($)}}function BN($){return{text(w,E={}){let X={message_text:w,...E};return{...$,input_message_content:X}},location(w,E,X={}){let G={latitude:w,longitude:E,...X};return{...$,input_message_content:G}},venue(w,E,X,G,J){let A={title:w,latitude:E,longitude:X,address:G,...J};return{...$,input_message_content:A}},contact(w,E,X={}){let G={first_name:w,phone_number:E,...X};return{...$,input_message_content:G}},invoice(w,E,X,G,J,A,D={}){let N={title:w,description:E,payload:X,provider_token:G,currency:J,prices:A,...D};return{...$,input_message_content:N}}}}NL.InlineQueryResultBuilder={article($,w,E={}){return BN({type:"article",id:$,title:w,...E})},audio($,w,E,X={}){return O$({type:"audio",id:$,title:w,audio_url:typeof E==="string"?E:E.href,...X})},audioCached($,w,E={}){return O$({type:"audio",id:$,audio_file_id:w,...E})},contact($,w,E,X={}){return O$({type:"contact",id:$,phone_number:w,first_name:E,...X})},documentPdf($,w,E,X={}){return O$({type:"document",mime_type:"application/pdf",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentZip($,w,E,X={}){return O$({type:"document",mime_type:"application/zip",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentCached($,w,E,X={}){return O$({type:"document",id:$,title:w,document_file_id:E,...X})},game($,w,E={}){return{type:"game",id:$,game_short_name:w,...E}},gif($,w,E,X={}){return O$({type:"gif",id:$,gif_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},gifCached($,w,E={}){return O$({type:"gif",id:$,gif_file_id:w,...E})},location($,w,E,X,G={}){return O$({type:"location",id:$,title:w,latitude:E,longitude:X,...G})},mpeg4gif($,w,E,X={}){return O$({type:"mpeg4_gif",id:$,mpeg4_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},mpeg4gifCached($,w,E={}){return O$({type:"mpeg4_gif",id:$,mpeg4_file_id:w,...E})},photo($,w,E={}){let X=typeof w==="string"?w:w.href;return O$({type:"photo",id:$,photo_url:X,thumbnail_url:X,...E})},photoCached($,w,E={}){return O$({type:"photo",id:$,photo_file_id:w,...E})},stickerCached($,w,E={}){return O$({type:"sticker",id:$,sticker_file_id:w,...E})},venue($,w,E,X,G,J={}){return O$({type:"venue",id:$,title:w,latitude:E,longitude:X,address:G,...J})},videoHtml($,w,E,X,G={}){return BN({type:"video",mime_type:"text/html",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoMp4($,w,E,X,G={}){return O$({type:"video",mime_type:"video/mp4",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoCached($,w,E,X={}){return O$({type:"video",id:$,title:w,video_file_id:E,...X})},voice($,w,E,X={}){return O$({type:"voice",id:$,title:w,voice_url:typeof E==="string"?E:E.href,...X})},voiceCached($,w,E,X={}){return O$({type:"voice",id:$,title:w,voice_file_id:E,...X})}}});var HL=Z((UL)=>{Object.defineProperty(UL,"__esModule",{value:!0});UL.InputMediaBuilder=void 0;UL.InputMediaBuilder={photo($,w={}){return{type:"photo",media:$,...w}},video($,w={}){return{type:"video",media:$,...w}},animation($,w={}){return{type:"animation",media:$,...w}},audio($,w={}){return{type:"audio",media:$,...w}},document($,w={}){return{type:"document",media:$,...w}}}});var RL=Z((jL)=>{Object.defineProperty(jL,"__esModule",{value:!0});jL.InlineKeyboard=jL.Keyboard=void 0;class s${constructor($=[[]]){this.keyboard=$}add(...$){var w;return(w=this.keyboard[this.keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.keyboard.push($),this}text($,w){return this.add(s$.text($,w))}static text($,w){return typeof w==="string"?{text:$,style:w}:{text:$,...w}}requestUsers($,w,E={}){return this.add(s$.requestUsers($,w,E))}static requestUsers($,w,E={}){return typeof $==="string"?{text:$,request_users:{request_id:w,...E}}:{...$,request_users:{request_id:w,...E}}}requestChat($,w,E={chat_is_channel:!1}){return this.add(s$.requestChat($,w,E))}static requestChat($,w,E={chat_is_channel:!1}){let X={request_id:w,...E};return typeof $==="string"?{text:$,request_chat:X}:{...$,request_chat:X}}requestContact($){return this.add(s$.requestContact($))}static requestContact($){return typeof $==="string"?{text:$,request_contact:!0}:{...$,request_contact:!0}}requestLocation($){return this.add(s$.requestLocation($))}static requestLocation($){return typeof $==="string"?{text:$,request_location:!0}:{...$,request_location:!0}}requestPoll($,w){return this.add(s$.requestPoll($,w))}static requestPoll($,w){let E={type:w};return typeof $==="string"?{text:$,request_poll:E}:{...$,request_poll:E}}webApp($,w){return this.add(s$.webApp($,w))}static webApp($,w){let E={url:w};return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}style($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.icon_custom_emoji_id=$,this}persistent($=!0){return this.is_persistent=$,this}selected($=!0){return this.selective=$,this}oneTime($=!0){return this.one_time_keyboard=$,this}resized($=!0){return this.resize_keyboard=$,this}placeholder($){return this.input_field_placeholder=$,this}toTransposed(){let $=this.keyboard,w=LL($);return this.clone(w)}toFlowed($,w={}){let E=this.keyboard,X=FL(E,$,w);return this.clone(X)}clone($=this.keyboard){let w=new s$($.map((E)=>E.slice()));return w.is_persistent=this.is_persistent,w.selective=this.selective,w.one_time_keyboard=this.one_time_keyboard,w.resize_keyboard=this.resize_keyboard,w.input_field_placeholder=this.input_field_placeholder,w}append(...$){for(let w of $){let E=s$.from(w);this.keyboard.push(...E.keyboard.map((X)=>X.slice()))}return this}build(){return this.keyboard}static from($){if($ instanceof s$)return $.clone();function w(E){return typeof E==="string"?s$.text(E):E}return new s$($.map((E)=>E.map(w)))}}jL.Keyboard=s$;class L${constructor($=[[]]){this.inline_keyboard=$}add(...$){var w;return(w=this.inline_keyboard[this.inline_keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.inline_keyboard.push($),this}url($,w){return this.add(L$.url($,w))}static url($,w){return typeof $==="string"?{text:$,url:w}:{...$,url:w}}text($,w=typeof $==="string"?$:$.text){return this.add(L$.text($,w))}static text($,w=typeof $==="string"?$:$.text){return typeof $==="string"?{text:$,callback_data:w}:{...$,callback_data:w}}webApp($,w){return this.add(L$.webApp($,w))}static webApp($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}login($,w){return this.add(L$.login($,w))}static login($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,login_url:E}:{...$,login_url:E}}switchInline($,w=""){return this.add(L$.switchInline($,w))}static switchInline($,w=""){return typeof $==="string"?{text:$,switch_inline_query:w}:{...$,switch_inline_query:w}}switchInlineCurrent($,w=""){return this.add(L$.switchInlineCurrent($,w))}static switchInlineCurrent($,w=""){return typeof $==="string"?{text:$,switch_inline_query_current_chat:w}:{...$,switch_inline_query_current_chat:w}}switchInlineChosen($,w={}){return this.add(L$.switchInlineChosen($,w))}static switchInlineChosen($,w={}){return typeof $==="string"?{text:$,switch_inline_query_chosen_chat:w}:{...$,switch_inline_query_chosen_chat:w}}copyText($,w){return this.add(L$.copyText($,w))}static copyText($,w){let E=typeof w==="string"?{text:w}:w;return typeof $==="string"?{text:$,copy_text:E}:{...$,copy_text:E}}game($){return this.add(L$.game($))}static game($){let w={};return typeof $==="string"?{text:$,callback_game:w}:{...$,callback_game:w}}pay($){return this.add(L$.pay($))}static pay($){return typeof $==="string"?{text:$,pay:!0}:{...$,pay:!0}}style($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");return E[X-1].style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");return E[X-1].icon_custom_emoji_id=$,this}toTransposed(){let $=this.inline_keyboard,w=LL($);return new L$(w)}toFlowed($,w={}){let E=this.inline_keyboard,X=FL(E,$,w);return new L$(X)}clone(){return new L$(this.inline_keyboard.map(($)=>$.slice()))}append(...$){for(let w of $){let E=L$.from(w);this.inline_keyboard.push(...E.inline_keyboard.map((X)=>X.slice()))}return this}static from($){if($ instanceof L$)return $.clone();return new L$($.map((w)=>w.slice()))}}jL.InlineKeyboard=L$;function LL($){var w;let E=[];for(let X=0;X<$.length;X++){let G=$[X];for(let J=0;J<G.length;J++){let A=G[J];((w=E[J])!==null&&w!==void 0?w:E[J]=[]).push(A)}}return E}function FL($,w,{fillLastRow:E=!1}){var X;let G=w;if(E)G=$.map((D)=>D.length).reduce((D,N)=>D+N,0)%w;let J=[];for(let A of $)for(let D of A){let N=Math.max(0,J.length-1),W=N===0?G:w,O=(X=J[N])!==null&&X!==void 0?X:J[N]=[];if(O.length===W)O=[],J.push(O);O.push(D)}return J}});var KL=Z((QL)=>{Object.defineProperty(QL,"__esModule",{value:!0});QL.MemorySessionStorage=void 0;QL.session=Gb;QL.lazySession=Db;QL.enhanceStorage=Wb;var Eb=mw(),Xb=(0,Eb.debug)("grammy:session");function Gb($={}){return $.type==="multi"?Ab($):Jb($)}function Jb($){let{initial:w,storage:E,getSessionKey:X,custom:G}=QN($);return async(J,A)=>{let D=new MA(E,J,"session",w),N=await X(J);await D.init(N,{custom:G,lazy:!1}),await A(),await D.finish()}}function Ab($){let w=Object.keys($).filter((X)=>X!=="type"),E=Object.fromEntries(w.map((X)=>[X,QN($[X])]));return async(X,G)=>{X.session={};let J=await Promise.all(w.map(async(A)=>{let{initial:D,storage:N,getSessionKey:W,custom:O}=E[A],Y=new MA(N,X.session,A,D),H=await W(X);return await Y.init(H,{custom:O,lazy:!1}),Y}));if(await G(),X.session==null)J.forEach((A)=>A.delete());await Promise.all(J.map((A)=>A.finish()))}}function Db($={}){if($.type!==void 0&&$.type!=="single")throw Error("Cannot use lazy multi sessions!");let{initial:w,storage:E,getSessionKey:X,custom:G}=QN($);return async(J,A)=>{let D=new MA(E,J,"session",w),N=await X(J);await D.init(N,{custom:G,lazy:!0}),await A(),await D.finish()}}class MA{constructor($,w,E,X){this.storage=$,this.obj=w,this.prop=E,this.initial=X,this.fetching=!1,this.read=!1,this.wrote=!1}load(){if(this.key===void 0)return;if(this.wrote)return;if(this.promise===void 0)this.fetching=!0,this.promise=Promise.resolve(this.storage.read(this.key)).then(($)=>{var w;if(this.fetching=!1,this.wrote)return this.value;if($!==void 0)return this.value=$,$;if($=(w=this.initial)===null||w===void 0?void 0:w.call(this),$!==void 0)this.wrote=!0,this.value=$;return $});return this.promise}async init($,w){if(this.key=$,!w.lazy)await this.load();Object.defineProperty(this.obj,this.prop,{enumerable:!0,get:()=>{if($===void 0){let E=TL("access",w);throw Error(E)}if(this.read=!0,!w.lazy||this.wrote)return this.value;return this.load(),this.fetching?this.promise:this.value},set:(E)=>{if($===void 0){let X=TL("assign",w);throw Error(X)}this.wrote=!0,this.fetching=!1,this.value=E}})}delete(){Object.assign(this.obj,{[this.prop]:void 0})}async finish(){if(this.key!==void 0){if(this.read)await this.load();if(this.read||this.wrote){let $=await this.value;if($==null)await this.storage.delete(this.key);else await this.storage.write(this.key,$)}}}}function QN($={}){let{prefix:w="",getSessionKey:E=zL,initial:X,storage:G}=$;if(G==null)Xb("Storing session data in memory, all data will be lost when the bot restarts."),G=new IN;return{initial:X,storage:G,getSessionKey:async(A)=>{let D=await E(A);return D===void 0?void 0:w+D},custom:E!==zL}}function zL($){var w;return(w=$.chatId)===null||w===void 0?void 0:w.toString()}function TL($,w){let{lazy:E=!1,custom:X}=w;return`Cannot ${$} ${E?"lazy ":""}session data because ${X?"the custom `getSessionKey` function returned undefined for this update":"this update does not belong to a chat, so the session key is undefined"}!`}function Nb($){return $===void 0||typeof $==="object"&&$!==null&&"__d"in $}function Wb($){let{storage:w,millisecondsToLive:E,migrations:X}=$;if(w=Ob(w),E!==void 0)w=Ub(w,E);if(X!==void 0)w=Yb(w,X);return Hb(w)}function Ob($){return{read:async(w)=>{let E=await $.read(w);return Nb(E)?E:{__d:E}},write:(w,E)=>$.write(w,E),delete:(w)=>$.delete(w)}}function Ub($,w){let E={read:async(X)=>{let G=await $.read(X);if(G===void 0)return;if(G.e===void 0)return await E.write(X,G),G;if(G.e<Date.now()){await E.delete(X);return}return G},write:async(X,G)=>{G.e=BL(G,w).expires,await $.write(X,G)},delete:(X)=>$.delete(X)};return E}function Yb($,w){let E=Object.keys(w).map((W)=>parseInt(W)).sort((W,O)=>W-O),X=E.length;if(X===0)throw Error("No migrations given!");let G=E[0],J=X-1,A=E[J],D=new Map;E.forEach((W,O)=>D.set(W,O));function N(W){let O=J;while(W<=E[O])O--;return O}return{read:async(W)=>{var O;let Y=await $.read(W);if(Y===void 0)return Y;let{__d:H,v:L=G-1}=Y,F=1+((O=D.get(L))!==null&&O!==void 0?O:N(L));for(;F<X;F++)H=w[E[F]](H);return{...Y,v:A,__d:H}},write:(W,O)=>$.write(W,{v:A,...O}),delete:(W)=>$.delete(W)}}function Hb($){return{read:(w)=>Promise.resolve($.read(w)).then((E)=>E===null||E===void 0?void 0:E.__d),write:(w,E)=>$.write(w,{__d:E}),delete:(w)=>$.delete(w)}}class IN{constructor($){this.timeToLive=$,this.storage=new Map}read($){let w=this.storage.get($);if(w===void 0)return;if(w.expires!==void 0&&w.expires<Date.now()){this.delete($);return}return w.session}readAll(){return this.readAllValues()}readAllKeys(){return Array.from(this.storage.keys())}readAllValues(){return Array.from(this.storage.keys()).map(($)=>this.read($)).filter(($)=>$!==void 0)}readAllEntries(){return Array.from(this.storage.keys()).map(($)=>[$,this.read($)]).filter(($)=>$[1]!==void 0)}has($){return this.storage.has($)}write($,w){this.storage.set($,BL(w,this.timeToLive))}delete($){this.storage.delete($)}}QL.MemorySessionStorage=IN;function BL($,w){if(w!==void 0&&w<1/0){let E=Date.now();return{session:$,expires:E+w}}else return{session:$}}});var SL=Z((PL)=>{Object.defineProperty(PL,"__esModule",{value:!0});PL.adapters=void 0;var R$="X-Telegram-Bot-Api-Secret-Token",RA=R$.toLowerCase(),Rw="secret token is wrong",HX=()=>new Response(null,{status:200}),LX=($)=>new Response($,{status:200,headers:{"Content-Type":"application/json"}}),FX=()=>new Response('"unauthorized"',{status:401,statusText:Rw}),Mb=($,w,E)=>({get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[R$],end:()=>E(null,{statusCode:200}),respond:(X)=>E(null,{statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E(null,{statusCode:401})}),Rb=($,w)=>{let E;return{get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[R$],end:()=>E({statusCode:200}),respond:(X)=>E({statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E({statusCode:401}),handlerReturn:new Promise((X)=>E=X)}},zb=($,w)=>{var E,X;return{get update(){return w.body},header:(X=(E=$.res)===null||E===void 0?void 0:E.headers)===null||X===void 0?void 0:X[R$],end:()=>$.res={status:200,body:""},respond:(G)=>{var J,A,D,N;(A=(J=$.res)===null||J===void 0?void 0:J.set)===null||A===void 0||A.call(J,"Content-Type","application/json"),(N=(D=$.res)===null||D===void 0?void 0:D.send)===null||N===void 0||N.call(D,G)},unauthorized:()=>{var G,J;(J=(G=$.res)===null||G===void 0?void 0:G.send)===null||J===void 0||J.call(G,401,Rw)}}},Tb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>w({status:204}),respond:(E)=>w({jsonBody:E}),unauthorized:()=>w({status:401,body:Rw}),handlerReturn:new Promise((E)=>w=E)}},Bb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{w(HX())},respond:(E)=>{w(LX(E))},unauthorized:()=>{w(FX())},handlerReturn:new Promise((E)=>w=E)}},Qb=($)=>{let w;return $.respondWith(new Promise((E)=>{w=E})),{get update(){return $.request.json()},header:$.request.headers.get(R$)||void 0,end:()=>{w(HX())},respond:(E)=>{w(LX(E))},unauthorized:()=>{w(FX())}}},Ib=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{w(HX())},respond:(E)=>{w(LX(E))},unauthorized:()=>{w(FX())},handlerReturn:new Promise((E)=>w=E)}},Kb=($,w)=>({get update(){return $.body},header:$.header(R$),end:()=>w.end(),respond:(E)=>{w.set("Content-Type","application/json"),w.send(E)},unauthorized:()=>{w.status(401).send(Rw)}}),Vb=($,w)=>({get update(){return $.body},header:$.headers[RA],end:()=>w.send(""),respond:(E)=>w.headers({"Content-Type":"application/json"}).send(E),unauthorized:()=>w.code(401).send(Rw)}),Pb=($)=>{let w;return{get update(){return $.req.json()},header:$.req.header(R$),end:()=>{w($.body(""))},respond:(E)=>{w($.json(E))},unauthorized:()=>{$.status(401),w($.body(""))},handlerReturn:new Promise((E)=>w=E)}},VL=($,w)=>{let E=$.headers[RA];return{get update(){return new Promise((X,G)=>{let J=[];$.on("data",(A)=>J.push(A)).once("end",()=>{let A=Buffer.concat(J).toString("utf-8");try{X(JSON.parse(A))}catch(D){G(D)}}).once("error",G)})},header:Array.isArray(E)?E[0]:E,end:()=>w.end(),respond:(X)=>w.writeHead(200,{"Content-Type":"application/json"}).end(X),unauthorized:()=>w.writeHead(401).end(Rw)}},qb=($)=>({get update(){return $.request.body},header:$.get(R$)||void 0,end:()=>{$.body=""},respond:(w)=>{$.set("Content-Type","application/json"),$.response.body=w},unauthorized:()=>{$.status=401}}),Sb=($,w)=>({get update(){return $.body},header:$.headers[RA],end:()=>w.end(),respond:(E)=>w.status(200).json(E),unauthorized:()=>w.status(401).send(Rw)}),kb=($)=>({get update(){return $.body},header:$.headers.get(R$)||void 0,end:()=>$.response.sendStatus(200),respond:(w)=>$.response.status(200).send(w),unauthorized:()=>$.response.status(401).send(Rw)}),bb=($)=>({get update(){return $.request.body.json()},header:$.request.headers.get(R$)||void 0,end:()=>{$.response.status=200},respond:(w)=>{$.response.type="json",$.response.body=w},unauthorized:()=>{$.response.status=401}}),Zb=($)=>({get update(){return $.request.json()},header:$.request.headers.get(R$)||void 0,end:()=>$.respondWith(HX()),respond:(w)=>$.respondWith(LX(w)),unauthorized:()=>$.respondWith(FX())}),Cb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{if(w)w(HX())},respond:(E)=>{if(w)w(LX(E))},unauthorized:()=>{if(w)w(FX())},handlerReturn:new Promise((E)=>w=E)}},_b=({request:$})=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{if(w)w(HX())},respond:(E)=>{if(w)w(LX(E))},unauthorized:()=>{if(w)w(FX())},handlerReturn:new Promise((E)=>w=E)}},vb=($,w)=>{var E;return{get update(){return $.json()},header:(E=$.headers.get(R$))!==null&&E!==void 0?E:void 0,end:()=>w.end(null),respond:(X)=>w.send(200,X),unauthorized:()=>w.send(401,Rw)}},fb=($)=>{let w;return{get update(){return $.body},header:$.headers[RA],end(){w("")},respond(E){$.set.headers["content-type"]="application/json",w(E)},unauthorized(){$.set.status=401,w("")},handlerReturn:new Promise((E)=>w=E)}};PL.adapters={"aws-lambda":Mb,"aws-lambda-async":Rb,azure:zb,"azure-v4":Tb,bun:Bb,cloudflare:Qb,"cloudflare-mod":Ib,elysia:fb,express:Kb,fastify:Vb,hono:Pb,http:VL,https:VL,koa:qb,"next-js":Sb,nhttp:kb,oak:bb,serveHttp:Zb,"std/http":Cb,sveltekit:_b,worktop:vb}});var CL=Z((ZL)=>{Object.defineProperty(ZL,"__esModule",{value:!0});ZL.webhookCallback=hb;var bL=mw(),xb=SL(),kL=(0,bL.debug)("grammy:error"),yb=($,w,E,X=()=>w('"unauthorized"'))=>({update:Promise.resolve($),respond:w,header:E,unauthorized:X}),gb={...xb.adapters,callback:yb};function ub($,w){if(w===void 0)return!0;if($===void 0)return!1;let E=new TextEncoder,X=E.encode($),G=E.encode(w);if(X.length!==G.length)return!1;let J=0;for(let A=0;A<G.length;A++){let D=A<X.length?X[A]:0,N=G[A];J|=D^N}return J===0}function hb($,w=bL.defaultAdapter,E,X,G){if($.isRunning())throw Error("Bot is already running via long polling, the webhook setup won't receive any updates!");else $.start=()=>{throw Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!")};let{onTimeout:J="throw",timeoutMilliseconds:A=1e4,secretToken:D}=typeof E==="object"?E:{onTimeout:E,timeoutMilliseconds:X,secretToken:G},N=!1,W=typeof w==="string"?gb[w]:w;return async(...O)=>{var Y;let H=W(...O);if(!N)await $.init(),N=!0;if(!ub(H.header,D))return await H.unauthorized(),H.handlerReturn;let L=!1,F={async send(j){L=!0,await H.respond(j)}};if(await cb($.handleUpdate(await H.update,F),typeof J==="function"?()=>J(...O):J,A),!L)(Y=H.end)===null||Y===void 0||Y.call(H);return H.handlerReturn}}function cb($,w,E){if(E===1/0)return $;return new Promise((X,G)=>{let J=setTimeout(()=>{if(kL(`Request timed out after ${E} ms`),w==="throw")G(Error(`Request timed out after ${E} ms`));else{if(typeof w==="function")w();X()}let A=Date.now();$.finally(()=>{let D=Date.now()-A;kL(`Request completed ${D} ms after timeout!`)})},E);$.then(X).catch(G).finally(()=>clearTimeout(J))})}});var fL=Z((P0)=>{var mb=P0&&P0.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),jX=P0&&P0.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))mb(w,$,E)};Object.defineProperty(P0,"__esModule",{value:!0});P0.HttpError=P0.GrammyError=P0.Api=P0.matchFilter=P0.Composer=P0.Context=P0.InputFile=P0.BotError=P0.Bot=void 0;var _L=zN();Object.defineProperty(P0,"Bot",{enumerable:!0,get:function(){return _L.Bot}});Object.defineProperty(P0,"BotError",{enumerable:!0,get:function(){return _L.BotError}});var rb=ON();Object.defineProperty(P0,"InputFile",{enumerable:!0,get:function(){return rb.InputFile}});var pb=AA();Object.defineProperty(P0,"Context",{enumerable:!0,get:function(){return pb.Context}});jX(DL(),P0);jX(OL(),P0);jX(HL(),P0);jX(RL(),P0);jX(KL(),P0);jX(CL(),P0);var ob=wN();Object.defineProperty(P0,"Composer",{enumerable:!0,get:function(){return ob.Composer}});var tb=GA();Object.defineProperty(P0,"matchFilter",{enumerable:!0,get:function(){return tb.matchFilter}});var ib=LN();Object.defineProperty(P0,"Api",{enumerable:!0,get:function(){return ib.Api}});var vL=YA();Object.defineProperty(P0,"GrammyError",{enumerable:!0,get:function(){return vL.GrammyError}});Object.defineProperty(P0,"HttpError",{enumerable:!0,get:function(){return vL.HttpError}})});function VN($){let w=new MX.InlineKeyboard;for(let E of $){for(let X of E)w.text(X.label,X.value);w.row()}return w}function lb($){let w=O0(),E=w.gateway.telegram.token;if(!E)throw Error("Telegram token is not configured.");let X=new MX.Bot(E),G=new Map,J=null;function A(H){let L=w.gateway.telegram.authorized_users.map(String);return L.length>0&&L.includes(String(H))}function D(H){let L=Date.now();if(G.has(H))return!0;G.set(H,L);for(let[F,j]of G)if(L-j>db)G.delete(F);return!1}function N(H){if(!H)return!1;return H.getTime()<$}async function W(H){let L=await X.api.getFile(H),F=await fetch(`https://api.telegram.org/file/bot${E}/${L.file_path}`);return new Uint8Array(await F.arrayBuffer())}async function O(H){if(J)await J(H)}function Y(H,L,F){let j=H.from;return{platform:"telegram",chatId:String(H.chat?.id??H.callbackQuery?.message?.chat.id??""),userId:String(j.id),username:j.username,displayName:[j.first_name,j.last_name].filter(Boolean).join(" ").trim()||void 0,text:L,platformMessageId:String(H.msg?.message_id??H.message?.message_id??""),attachments:F}}return{platform:"telegram",async start(H){J=H;let L=["start","help","status","mode","cwd","agent","tasks","task","approve","reject","assign","jobs","run","mem","sessions","session"];X.command(L,async(F)=>{if(!F.from||!A(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`cmd:${j}`))return;if(N(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=F.message?.text?.split(" ")[0]?.replace(/^\//,"").split("@")[0]??"help",z=F.message?.text?.split(" ").slice(1).join(" ")??"",B=z?`/${M} ${z}`:`/${M}`;await O(Y(F,B))}),X.on("message",async(F)=>{if(!F.from||!A(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`msg:${j}`))return;if(N(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=[];if(F.message?.voice)try{M.push({kind:"audio",data:await W(F.message.voice.file_id),mimeType:F.message.voice.mime_type??"audio/ogg",format:"ogg",duration:F.message.voice.duration})}catch(B){KN.warn("Failed to download voice message",{err:B})}if(F.message?.audio)try{M.push({kind:"audio",data:await W(F.message.audio.file_id),mimeType:F.message.audio.mime_type??"audio/mpeg",format:(F.message.audio.mime_type??"audio/mpeg").split("/").at(1)??"mp3",duration:F.message.audio.duration})}catch(B){KN.warn("Failed to download audio message",{err:B})}let z=F.message?.text??F.message?.caption??"";if(!z&&M.length===0)return;await O(Y(F,z,M.length>0?M:void 0))}),X.on("callback_query:data",async(F)=>{if(!F.from||!A(F.from.id)||!F.callbackQuery)return;let j=F.callbackQuery.id;if(D(`cb:${j}`)){await F.answerCallbackQuery();return}let M=String(F.callbackQuery.message?.chat.id??F.chat?.id??""),z=`${M}:${F.callbackQuery.message?.message_id}`;await O({platform:"telegram",chatId:M,userId:String(F.from.id),username:F.from.username,displayName:[F.from.first_name,F.from.last_name].filter(Boolean).join(" ").trim()||void 0,text:F.callbackQuery.data??"",platformMessageId:z}),await F.answerCallbackQuery()}),KN.info("Starting Telegram gateway adapter"),X.start({allowed_updates:["message","callback_query"]})},async stop(){X.stop()},async send(H,L,F){let j={};if(F?.parseMode==="html")j.parse_mode="HTML";if(F?.buttons?.length)j.reply_markup=VN(F.buttons);let M=L.slice(0,4096),z=await X.api.sendMessage(H,M,j);return`${z.chat.id}:${z.message_id}`},async updateMessage(H,L,F,j){let[,M]=L.split(":");if(!M)return;let z={};if(j?.parseMode==="html")z.parse_mode="HTML";if(j?.buttons?.length)z.reply_markup=VN(j.buttons);try{await X.api.editMessageText(H,Number(M),F.slice(0,4096),z)}catch(B){if(!String(B instanceof Error?B.message:"").includes("message is not modified"))throw B}},async sendWithButtons(H,L,F,j){let M={reply_markup:VN(F)};if(j?.parseMode==="html")M.parse_mode="HTML";let z=await X.api.sendMessage(H,L.slice(0,4096),M);return`${z.chat.id}:${z.message_id}`},async downloadAudio(H){return W(H)},async sendAudio(H,L,F,j){let M=F==="ogg"||F==="oga"?"ogg":"mp3",z=new MX.InputFile(L,`audio.${M}`),B=j?{caption:j}:{};if(M==="ogg")await X.api.sendVoice(H,z,B);else await X.api.sendAudio(H,z,B)},async showTyping(H){try{await X.api.sendChatAction(H,"typing")}catch{}},async registerCommands(H){await X.api.setMyCommands(H.map((L)=>({command:L.command,description:L.description})))}}}var MX,KN,db=60000;var xL=R(()=>{C$();p$();oJ();MX=DJ(fL(),1),KN=Z0("gateway:telegram");pJ("telegram",($)=>lb($))});import{existsSync as sb}from"fs";class yL{adapters=new Map;sessionLock=new t8;permissionManager=new o8;startTime=Date.now();adapterStatus=new Map;pendingSessionApprove=new Set;rateLimiter=new r8;async start(){let $=O0(),w=[];if($.gateway.telegram.enabled&&$.gateway.telegram.token)w.push("telegram");if($.gateway.slack.enabled&&$.gateway.slack.bot_token&&$.gateway.slack.app_token)w.push("slack");for(let G of w)try{let J=TY(G,this.startTime);this.adapters.set(J.platform,J),await this.safeStart(J)}catch(J){let A=p8(String(J));zE.error(`Failed to create ${G} adapter`,A),this.adapterStatus.set(G,{error:A})}for(let[,G]of this.adapters)if("registerCommands"in G)try{await G.registerCommands(ab)}catch(J){zE.warn("Failed to register bot commands",{platform:G.platform,err:J})}await xY();let E=O0();for(let G of["telegram","slack"]){let J=E.gateway[G];if(J.enabled&&J.authorized_users.length===0)zE.warn(`${G}: authorized_users is empty \u2014 all users will be denied. Add user IDs to config.`)}let X=[...this.adapters.keys()].join(", ");zE.info(`Gateway started with adapters: ${X||"none"}`)}async stop(){this.permissionManager.denyAll(),await Promise.all([...this.adapters.values()].map(($)=>$.stop().catch(()=>{}))),this.adapters.clear()}resolvePermission($,w){return this.permissionManager.resolve($,w)}async safeStart($){try{await $.start(async(w)=>this.handleIncoming(w)),this.adapterStatus.set($.platform,{})}catch(w){this.adapterStatus.set($.platform,{error:String(w)}),zE.error(`Failed to start ${$.platform} adapter`,p8(String(w)))}}normalizeCallbackText($){if($.startsWith("task:approve:"))return`/approve ${$.slice(13)}`;if($.startsWith("task:reject:"))return`/reject ${$.slice(12)}`;if($.startsWith("perm:approve:")){let w=$.slice(13);if(this.permissionManager.resolve(w,!0))return`__perm_resolved:${w}:approved`;return`/approve ${w}`}if($.startsWith("perm:deny:")){let w=$.slice(10);if(this.permissionManager.resolve(w,!1))return`__perm_resolved:${w}:denied`;return`/reject ${w}`}if($.startsWith("perm:session:")){let w=$.slice(13);return this.permissionManager.resolve(w,!0),this.pendingSessionApprove.add(w),`__perm_resolved:${w}:session`}return $}async handleIncoming($){let w=O0(),E=w.gateway[$.platform],X=E.authorized_users.map(String),G=await PY({platform:$.platform,chatId:$.chatId,username:$.username,displayName:$.displayName,authorized:X.length>0&&X.includes($.userId),mode:E.mode,threadId:$.threadId});if(!G.authorized)return;if(!this.rateLimiter.allow(G.id)){await this.sendText($,"\u23F8 Slow down \u2014 too many messages. Try again in a minute.");return}let J=$.text.trim(),A=$.attachments?.find((W)=>W.kind==="audio");if(J){if(J=this.normalizeCallbackText(J),J.startsWith("__perm_resolved:")){let O=J.split(":")[2],Y=O==="approved"?"\u2705 Permission approved.":O==="session"?"\u2705 Permission approved for this session.":"\u274C Permission denied.";if(await this.sendText($,Y),O==="session"){let H=await jw(G.id);if(H)await a1(H.id,{auto_approve:!0})}return}}if(!J&&A&&w.speech.enabled)try{let W=await sY({audio:A.data,format:A.format});await this.handleIncoming({...$,text:W,fromVoice:!0,attachments:[]});return}catch(W){await this.sendText($,`Voice transcription failed: ${W instanceof Error?W.message:String(W)}`);return}if(!J){await this.sendText($,"Send text or a voice message.");return}await DX({chatKey:G.id,direction:"in",role:"user",text:J,platformMessageId:$.platformMessageId,threadId:$.threadId,metadata:$.fromVoice?{from_voice:!0}:void 0});let D=await mY({chatKey:G.id,rawText:J,currentMode:G.mode,currentWorkingDir:G.working_dir});if(D){if(D.mode)G.mode=D.mode;let W=D.html??D.text??"",O=D.text??W,Y=D.html?"html":void 0,H=this.adapters.get($.platform);if(H&&D.buttons?.length&&"sendWithButtons"in H)await H.sendWithButtons($.chatId,W,D.buttons,{threadId:$.threadId,parseMode:Y});else if(H)await H.send($.chatId,W,{threadId:$.threadId,parseMode:Y});if($.fromVoice&&O)await this.trySendVoiceReply($,O);await DX({chatKey:G.id,direction:"out",role:"system",text:O,threadId:$.threadId});return}if(G.mode.startsWith("job:")){let W=G.mode.slice(4),O=await eJ(W),Y=O?`Triggered ${O.name} \u2192 ${await A1({jobId:O.id,triggerBy:"bridge-msg",envOverrides:{MSG:J}})}`:`Job not found: ${W}`;if(await this.sendText($,Y),$.fromVoice)await this.trySendVoiceReply($,Y);await DX({chatKey:G.id,direction:"out",role:"system",text:Y,threadId:$.threadId});return}if(G.mode==="direct"){await this.sendText($,"Direct mode active. Use /help for commands, or /agent claude to start an agent session."),await DX({chatKey:G.id,direction:"out",role:"system",text:"Direct mode active. Use /help for commands, or /agent claude to start an agent session.",threadId:$.threadId});return}let N=await rY({chatKey:G.id,mode:G.mode,cwd:G.working_dir});if(!this.sessionLock.tryAcquire(N.id)){await this.sendText($,`\u23F3 ${N.backend} is still processing \u2014 please wait.`);return}try{await this.runAgentTurnWithPreview($,G,N,J)}finally{this.sessionLock.release(N.id)}}async runAgentTurnWithPreview($,w,E,X){if(!E.cwd||!sb(E.cwd)){await this.sendText($,"Set a working directory first: /cwd <absolute-path>");return}let G=this.adapters.get($.platform);if(!G)return;if("showTyping"in G)await G.showTyping($.chatId).catch(()=>{});let J=await G.send($.chatId,`${E.backend} is thinking\u2026`,{threadId:$.threadId}),A=null;if(J&&$A.supports(G))A=new $A(G),await A.init(E.id,$.chatId,J,`${E.backend} is thinking\u2026`);await a1(E.id,{status:"running",last_activity_at:new Date});try{let D=await vY({chatKey:w.id,chatId:$.chatId,platform:$.platform,adapter:G,permissionManager:this.permissionManager,session:{id:E.id,backend:E.backend,cwd:E.cwd,model:E.model,runtime_session_id:E.runtime_session_id,auto_approve:E.auto_approve,task_id:E.task_id},threadId:$.threadId},X,J,A);if(await a1(E.id,{status:"idle",runtime_session_id:D.runtimeSessionId,last_activity_at:new Date,last_error:null}),A&&J)await A.finalize(E.id,D.output);else if(J&&"updateMessage"in G)await G.updateMessage($.chatId,J,D.output,{threadId:$.threadId}).catch(()=>G.send($.chatId,D.output,{threadId:$.threadId}));else await G.send($.chatId,D.output,{threadId:$.threadId});if(await DX({chatKey:w.id,direction:"out",role:"assistant",text:D.output,gatewaySessionId:E.id,threadId:$.threadId,platformMessageId:J}),$.fromVoice)await this.trySendVoiceReply($,D.output)}catch(D){A?.cleanup(E.id);let N=`Agent error: ${D instanceof Error?D.message:String(D)}`;await a1(E.id,{status:"error",last_error:N,last_activity_at:new Date});let W=N.slice(0,1000);if(J&&"updateMessage"in G)await G.updateMessage($.chatId,J,W,{threadId:$.threadId}).catch(()=>G.send($.chatId,W,{threadId:$.threadId}));else await G.send($.chatId,W,{threadId:$.threadId}).catch(()=>{});if(D instanceof Error&&/auth|api.key|401/i.test(D.message))await fY(E.id)}}async sendText($,w){let E=this.adapters.get($.platform);if(!E)return;await E.send($.chatId,w,{threadId:$.threadId})}async trySendVoiceReply($,w){if(!O0().tts.enabled)return;let X=this.adapters.get($.platform);if(!X||!("sendAudio"in X))return;try{let G=await aY(w);await X.sendAudio($.chatId,G.audio,G.format,"Voice reply")}catch(G){zE.warn("TTS failed",{err:G})}}async notifyTaskReview($){let w=await CY(),E=`\uD83D\uDC40 <b>Review requested</b>
410
+ On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`)}var Nb=MJ()});var LL=_((HL)=>{Object.defineProperty(HL,"__esModule",{value:!0});HL.API_CONSTANTS=void 0;var YL=QJ(),Db=[...YL.DEFAULT_UPDATE_TYPES,"chat_member","message_reaction","message_reaction_count"],Ob={can_send_messages:!0,can_send_audios:!0,can_send_documents:!0,can_send_photos:!0,can_send_videos:!0,can_send_video_notes:!0,can_send_voice_notes:!0,can_send_polls:!0,can_send_other_messages:!0,can_add_web_page_previews:!0,can_change_info:!0,can_invite_users:!0,can_edit_tag:!0,can_pin_messages:!0,can_manage_topics:!0};HL.API_CONSTANTS={DEFAULT_UPDATE_TYPES:YL.DEFAULT_UPDATE_TYPES,ALL_UPDATE_TYPES:Db,ALL_CHAT_PERMISSIONS:Ob};Object.freeze(HL.API_CONSTANTS)});var ML=_((FL)=>{Object.defineProperty(FL,"__esModule",{value:!0});FL.InlineQueryResultBuilder=void 0;function U$($){return{...$,...VJ($)}}function VJ($){return{text(w,E={}){let X={message_text:w,...E};return{...$,input_message_content:X}},location(w,E,X={}){let G={latitude:w,longitude:E,...X};return{...$,input_message_content:G}},venue(w,E,X,G,A){let N={title:w,latitude:E,longitude:X,address:G,...A};return{...$,input_message_content:N}},contact(w,E,X={}){let G={first_name:w,phone_number:E,...X};return{...$,input_message_content:G}},invoice(w,E,X,G,A,N,D={}){let O={title:w,description:E,payload:X,provider_token:G,currency:A,prices:N,...D};return{...$,input_message_content:O}}}}FL.InlineQueryResultBuilder={article($,w,E={}){return VJ({type:"article",id:$,title:w,...E})},audio($,w,E,X={}){return U$({type:"audio",id:$,title:w,audio_url:typeof E==="string"?E:E.href,...X})},audioCached($,w,E={}){return U$({type:"audio",id:$,audio_file_id:w,...E})},contact($,w,E,X={}){return U$({type:"contact",id:$,phone_number:w,first_name:E,...X})},documentPdf($,w,E,X={}){return U$({type:"document",mime_type:"application/pdf",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentZip($,w,E,X={}){return U$({type:"document",mime_type:"application/zip",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentCached($,w,E,X={}){return U$({type:"document",id:$,title:w,document_file_id:E,...X})},game($,w,E={}){return{type:"game",id:$,game_short_name:w,...E}},gif($,w,E,X={}){return U$({type:"gif",id:$,gif_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},gifCached($,w,E={}){return U$({type:"gif",id:$,gif_file_id:w,...E})},location($,w,E,X,G={}){return U$({type:"location",id:$,title:w,latitude:E,longitude:X,...G})},mpeg4gif($,w,E,X={}){return U$({type:"mpeg4_gif",id:$,mpeg4_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},mpeg4gifCached($,w,E={}){return U$({type:"mpeg4_gif",id:$,mpeg4_file_id:w,...E})},photo($,w,E={}){let X=typeof w==="string"?w:w.href;return U$({type:"photo",id:$,photo_url:X,thumbnail_url:X,...E})},photoCached($,w,E={}){return U$({type:"photo",id:$,photo_file_id:w,...E})},stickerCached($,w,E={}){return U$({type:"sticker",id:$,sticker_file_id:w,...E})},venue($,w,E,X,G,A={}){return U$({type:"venue",id:$,title:w,latitude:E,longitude:X,address:G,...A})},videoHtml($,w,E,X,G={}){return VJ({type:"video",mime_type:"text/html",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoMp4($,w,E,X,G={}){return U$({type:"video",mime_type:"video/mp4",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoCached($,w,E,X={}){return U$({type:"video",id:$,title:w,video_file_id:E,...X})},voice($,w,E,X={}){return U$({type:"voice",id:$,title:w,voice_url:typeof E==="string"?E:E.href,...X})},voiceCached($,w,E,X={}){return U$({type:"voice",id:$,title:w,voice_file_id:E,...X})}}});var zL=_((TL)=>{Object.defineProperty(TL,"__esModule",{value:!0});TL.InputMediaBuilder=void 0;TL.InputMediaBuilder={photo($,w={}){return{type:"photo",media:$,...w}},video($,w={}){return{type:"video",media:$,...w}},animation($,w={}){return{type:"animation",media:$,...w}},audio($,w={}){return{type:"audio",media:$,...w}},document($,w={}){return{type:"document",media:$,...w}}}});var VL=_((QL)=>{Object.defineProperty(QL,"__esModule",{value:!0});QL.InlineKeyboard=QL.Keyboard=void 0;class a${constructor($=[[]]){this.keyboard=$}add(...$){var w;return(w=this.keyboard[this.keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.keyboard.push($),this}text($,w){return this.add(a$.text($,w))}static text($,w){return typeof w==="string"?{text:$,style:w}:{text:$,...w}}requestUsers($,w,E={}){return this.add(a$.requestUsers($,w,E))}static requestUsers($,w,E={}){return typeof $==="string"?{text:$,request_users:{request_id:w,...E}}:{...$,request_users:{request_id:w,...E}}}requestChat($,w,E={chat_is_channel:!1}){return this.add(a$.requestChat($,w,E))}static requestChat($,w,E={chat_is_channel:!1}){let X={request_id:w,...E};return typeof $==="string"?{text:$,request_chat:X}:{...$,request_chat:X}}requestContact($){return this.add(a$.requestContact($))}static requestContact($){return typeof $==="string"?{text:$,request_contact:!0}:{...$,request_contact:!0}}requestLocation($){return this.add(a$.requestLocation($))}static requestLocation($){return typeof $==="string"?{text:$,request_location:!0}:{...$,request_location:!0}}requestPoll($,w){return this.add(a$.requestPoll($,w))}static requestPoll($,w){let E={type:w};return typeof $==="string"?{text:$,request_poll:E}:{...$,request_poll:E}}webApp($,w){return this.add(a$.webApp($,w))}static webApp($,w){let E={url:w};return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}style($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.icon_custom_emoji_id=$,this}persistent($=!0){return this.is_persistent=$,this}selected($=!0){return this.selective=$,this}oneTime($=!0){return this.one_time_keyboard=$,this}resized($=!0){return this.resize_keyboard=$,this}placeholder($){return this.input_field_placeholder=$,this}toTransposed(){let $=this.keyboard,w=BL($);return this.clone(w)}toFlowed($,w={}){let E=this.keyboard,X=IL(E,$,w);return this.clone(X)}clone($=this.keyboard){let w=new a$($.map((E)=>E.slice()));return w.is_persistent=this.is_persistent,w.selective=this.selective,w.one_time_keyboard=this.one_time_keyboard,w.resize_keyboard=this.resize_keyboard,w.input_field_placeholder=this.input_field_placeholder,w}append(...$){for(let w of $){let E=a$.from(w);this.keyboard.push(...E.keyboard.map((X)=>X.slice()))}return this}build(){return this.keyboard}static from($){if($ instanceof a$)return $.clone();function w(E){return typeof E==="string"?a$.text(E):E}return new a$($.map((E)=>E.map(w)))}}QL.Keyboard=a$;class j${constructor($=[[]]){this.inline_keyboard=$}add(...$){var w;return(w=this.inline_keyboard[this.inline_keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.inline_keyboard.push($),this}url($,w){return this.add(j$.url($,w))}static url($,w){return typeof $==="string"?{text:$,url:w}:{...$,url:w}}text($,w=typeof $==="string"?$:$.text){return this.add(j$.text($,w))}static text($,w=typeof $==="string"?$:$.text){return typeof $==="string"?{text:$,callback_data:w}:{...$,callback_data:w}}webApp($,w){return this.add(j$.webApp($,w))}static webApp($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}login($,w){return this.add(j$.login($,w))}static login($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,login_url:E}:{...$,login_url:E}}switchInline($,w=""){return this.add(j$.switchInline($,w))}static switchInline($,w=""){return typeof $==="string"?{text:$,switch_inline_query:w}:{...$,switch_inline_query:w}}switchInlineCurrent($,w=""){return this.add(j$.switchInlineCurrent($,w))}static switchInlineCurrent($,w=""){return typeof $==="string"?{text:$,switch_inline_query_current_chat:w}:{...$,switch_inline_query_current_chat:w}}switchInlineChosen($,w={}){return this.add(j$.switchInlineChosen($,w))}static switchInlineChosen($,w={}){return typeof $==="string"?{text:$,switch_inline_query_chosen_chat:w}:{...$,switch_inline_query_chosen_chat:w}}copyText($,w){return this.add(j$.copyText($,w))}static copyText($,w){let E=typeof w==="string"?{text:w}:w;return typeof $==="string"?{text:$,copy_text:E}:{...$,copy_text:E}}game($){return this.add(j$.game($))}static game($){let w={};return typeof $==="string"?{text:$,callback_game:w}:{...$,callback_game:w}}pay($){return this.add(j$.pay($))}static pay($){return typeof $==="string"?{text:$,pay:!0}:{...$,pay:!0}}style($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");return E[X-1].style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");return E[X-1].icon_custom_emoji_id=$,this}toTransposed(){let $=this.inline_keyboard,w=BL($);return new j$(w)}toFlowed($,w={}){let E=this.inline_keyboard,X=IL(E,$,w);return new j$(X)}clone(){return new j$(this.inline_keyboard.map(($)=>$.slice()))}append(...$){for(let w of $){let E=j$.from(w);this.inline_keyboard.push(...E.inline_keyboard.map((X)=>X.slice()))}return this}static from($){if($ instanceof j$)return $.clone();return new j$($.map((w)=>w.slice()))}}QL.InlineKeyboard=j$;function BL($){var w;let E=[];for(let X=0;X<$.length;X++){let G=$[X];for(let A=0;A<G.length;A++){let N=G[A];((w=E[A])!==null&&w!==void 0?w:E[A]=[]).push(N)}}return E}function IL($,w,{fillLastRow:E=!1}){var X;let G=w;if(E)G=$.map((D)=>D.length).reduce((D,O)=>D+O,0)%w;let A=[];for(let N of $)for(let D of N){let O=Math.max(0,A.length-1),W=O===0?G:w,J=(X=A[O])!==null&&X!==void 0?X:A[O]=[];if(J.length===W)J=[],A.push(J);J.push(D)}return A}});var _L=_((kL)=>{Object.defineProperty(kL,"__esModule",{value:!0});kL.MemorySessionStorage=void 0;kL.session=Yb;kL.lazySession=Fb;kL.enhanceStorage=Mb;var Jb=rE(),Ub=(0,Jb.debug)("grammy:session");function Yb($={}){return $.type==="multi"?Lb($):Hb($)}function Hb($){let{initial:w,storage:E,getSessionKey:X,custom:G}=PJ($);return async(A,N)=>{let D=new RD(E,A,"session",w),O=await X(A);await D.init(O,{custom:G,lazy:!1}),await N(),await D.finish()}}function Lb($){let w=Object.keys($).filter((X)=>X!=="type"),E=Object.fromEntries(w.map((X)=>[X,PJ($[X])]));return async(X,G)=>{X.session={};let A=await Promise.all(w.map(async(N)=>{let{initial:D,storage:O,getSessionKey:W,custom:J}=E[N],Y=new RD(O,X.session,N,D),H=await W(X);return await Y.init(H,{custom:J,lazy:!1}),Y}));if(await G(),X.session==null)A.forEach((N)=>N.delete());await Promise.all(A.map((N)=>N.finish()))}}function Fb($={}){if($.type!==void 0&&$.type!=="single")throw Error("Cannot use lazy multi sessions!");let{initial:w,storage:E,getSessionKey:X,custom:G}=PJ($);return async(A,N)=>{let D=new RD(E,A,"session",w),O=await X(A);await D.init(O,{custom:G,lazy:!0}),await N(),await D.finish()}}class RD{constructor($,w,E,X){this.storage=$,this.obj=w,this.prop=E,this.initial=X,this.fetching=!1,this.read=!1,this.wrote=!1}load(){if(this.key===void 0)return;if(this.wrote)return;if(this.promise===void 0)this.fetching=!0,this.promise=Promise.resolve(this.storage.read(this.key)).then(($)=>{var w;if(this.fetching=!1,this.wrote)return this.value;if($!==void 0)return this.value=$,$;if($=(w=this.initial)===null||w===void 0?void 0:w.call(this),$!==void 0)this.wrote=!0,this.value=$;return $});return this.promise}async init($,w){if(this.key=$,!w.lazy)await this.load();Object.defineProperty(this.obj,this.prop,{enumerable:!0,get:()=>{if($===void 0){let E=qL("access",w);throw Error(E)}if(this.read=!0,!w.lazy||this.wrote)return this.value;return this.load(),this.fetching?this.promise:this.value},set:(E)=>{if($===void 0){let X=qL("assign",w);throw Error(X)}this.wrote=!0,this.fetching=!1,this.value=E}})}delete(){Object.assign(this.obj,{[this.prop]:void 0})}async finish(){if(this.key!==void 0){if(this.read)await this.load();if(this.read||this.wrote){let $=await this.value;if($==null)await this.storage.delete(this.key);else await this.storage.write(this.key,$)}}}}function PJ($={}){let{prefix:w="",getSessionKey:E=PL,initial:X,storage:G}=$;if(G==null)Ub("Storing session data in memory, all data will be lost when the bot restarts."),G=new qJ;return{initial:X,storage:G,getSessionKey:async(N)=>{let D=await E(N);return D===void 0?void 0:w+D},custom:E!==PL}}function PL($){var w;return(w=$.chatId)===null||w===void 0?void 0:w.toString()}function qL($,w){let{lazy:E=!1,custom:X}=w;return`Cannot ${$} ${E?"lazy ":""}session data because ${X?"the custom `getSessionKey` function returned undefined for this update":"this update does not belong to a chat, so the session key is undefined"}!`}function jb($){return $===void 0||typeof $==="object"&&$!==null&&"__d"in $}function Mb($){let{storage:w,millisecondsToLive:E,migrations:X}=$;if(w=Tb(w),E!==void 0)w=Rb(w,E);if(X!==void 0)w=zb(w,X);return Bb(w)}function Tb($){return{read:async(w)=>{let E=await $.read(w);return jb(E)?E:{__d:E}},write:(w,E)=>$.write(w,E),delete:(w)=>$.delete(w)}}function Rb($,w){let E={read:async(X)=>{let G=await $.read(X);if(G===void 0)return;if(G.e===void 0)return await E.write(X,G),G;if(G.e<Date.now()){await E.delete(X);return}return G},write:async(X,G)=>{G.e=SL(G,w).expires,await $.write(X,G)},delete:(X)=>$.delete(X)};return E}function zb($,w){let E=Object.keys(w).map((W)=>parseInt(W)).sort((W,J)=>W-J),X=E.length;if(X===0)throw Error("No migrations given!");let G=E[0],A=X-1,N=E[A],D=new Map;E.forEach((W,J)=>D.set(W,J));function O(W){let J=A;while(W<=E[J])J--;return J}return{read:async(W)=>{var J;let Y=await $.read(W);if(Y===void 0)return Y;let{__d:H,v:L=G-1}=Y,F=1+((J=D.get(L))!==null&&J!==void 0?J:O(L));for(;F<X;F++)H=w[E[F]](H);return{...Y,v:N,__d:H}},write:(W,J)=>$.write(W,{v:N,...J}),delete:(W)=>$.delete(W)}}function Bb($){return{read:(w)=>Promise.resolve($.read(w)).then((E)=>E===null||E===void 0?void 0:E.__d),write:(w,E)=>$.write(w,{__d:E}),delete:(w)=>$.delete(w)}}class qJ{constructor($){this.timeToLive=$,this.storage=new Map}read($){let w=this.storage.get($);if(w===void 0)return;if(w.expires!==void 0&&w.expires<Date.now()){this.delete($);return}return w.session}readAll(){return this.readAllValues()}readAllKeys(){return Array.from(this.storage.keys())}readAllValues(){return Array.from(this.storage.keys()).map(($)=>this.read($)).filter(($)=>$!==void 0)}readAllEntries(){return Array.from(this.storage.keys()).map(($)=>[$,this.read($)]).filter(($)=>$[1]!==void 0)}has($){return this.storage.has($)}write($,w){this.storage.set($,SL(w,this.timeToLive))}delete($){this.storage.delete($)}}kL.MemorySessionStorage=qJ;function SL($,w){if(w!==void 0&&w<1/0){let E=Date.now();return{session:$,expires:E+w}}else return{session:$}}});var vL=_((CL)=>{Object.defineProperty(CL,"__esModule",{value:!0});CL.adapters=void 0;var K$="X-Telegram-Bot-Api-Secret-Token",zD=K$.toLowerCase(),ME="secret token is wrong",jX=()=>new Response(null,{status:200}),MX=($)=>new Response($,{status:200,headers:{"Content-Type":"application/json"}}),TX=()=>new Response('"unauthorized"',{status:401,statusText:ME}),Vb=($,w,E)=>({get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[K$],end:()=>E(null,{statusCode:200}),respond:(X)=>E(null,{statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E(null,{statusCode:401})}),Pb=($,w)=>{let E;return{get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[K$],end:()=>E({statusCode:200}),respond:(X)=>E({statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E({statusCode:401}),handlerReturn:new Promise((X)=>E=X)}},qb=($,w)=>{var E,X;return{get update(){return w.body},header:(X=(E=$.res)===null||E===void 0?void 0:E.headers)===null||X===void 0?void 0:X[K$],end:()=>$.res={status:200,body:""},respond:(G)=>{var A,N,D,O;(N=(A=$.res)===null||A===void 0?void 0:A.set)===null||N===void 0||N.call(A,"Content-Type","application/json"),(O=(D=$.res)===null||D===void 0?void 0:D.send)===null||O===void 0||O.call(D,G)},unauthorized:()=>{var G,A;(A=(G=$.res)===null||G===void 0?void 0:G.send)===null||A===void 0||A.call(G,401,ME)}}},Sb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(K$)||void 0,end:()=>w({status:204}),respond:(E)=>w({jsonBody:E}),unauthorized:()=>w({status:401,body:ME}),handlerReturn:new Promise((E)=>w=E)}},kb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(K$)||void 0,end:()=>{w(jX())},respond:(E)=>{w(MX(E))},unauthorized:()=>{w(TX())},handlerReturn:new Promise((E)=>w=E)}},bb=($)=>{let w;return $.respondWith(new Promise((E)=>{w=E})),{get update(){return $.request.json()},header:$.request.headers.get(K$)||void 0,end:()=>{w(jX())},respond:(E)=>{w(MX(E))},unauthorized:()=>{w(TX())}}},_b=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(K$)||void 0,end:()=>{w(jX())},respond:(E)=>{w(MX(E))},unauthorized:()=>{w(TX())},handlerReturn:new Promise((E)=>w=E)}},Zb=($,w)=>({get update(){return $.body},header:$.header(K$),end:()=>w.end(),respond:(E)=>{w.set("Content-Type","application/json"),w.send(E)},unauthorized:()=>{w.status(401).send(ME)}}),Cb=($,w)=>({get update(){return $.body},header:$.headers[zD],end:()=>w.send(""),respond:(E)=>w.headers({"Content-Type":"application/json"}).send(E),unauthorized:()=>w.code(401).send(ME)}),fb=($)=>{let w;return{get update(){return $.req.json()},header:$.req.header(K$),end:()=>{w($.body(""))},respond:(E)=>{w($.json(E))},unauthorized:()=>{$.status(401),w($.body(""))},handlerReturn:new Promise((E)=>w=E)}},ZL=($,w)=>{let E=$.headers[zD];return{get update(){return new Promise((X,G)=>{let A=[];$.on("data",(N)=>A.push(N)).once("end",()=>{let N=Buffer.concat(A).toString("utf-8");try{X(JSON.parse(N))}catch(D){G(D)}}).once("error",G)})},header:Array.isArray(E)?E[0]:E,end:()=>w.end(),respond:(X)=>w.writeHead(200,{"Content-Type":"application/json"}).end(X),unauthorized:()=>w.writeHead(401).end(ME)}},vb=($)=>({get update(){return $.request.body},header:$.get(K$)||void 0,end:()=>{$.body=""},respond:(w)=>{$.set("Content-Type","application/json"),$.response.body=w},unauthorized:()=>{$.status=401}}),xb=($,w)=>({get update(){return $.body},header:$.headers[zD],end:()=>w.end(),respond:(E)=>w.status(200).json(E),unauthorized:()=>w.status(401).send(ME)}),yb=($)=>({get update(){return $.body},header:$.headers.get(K$)||void 0,end:()=>$.response.sendStatus(200),respond:(w)=>$.response.status(200).send(w),unauthorized:()=>$.response.status(401).send(ME)}),gb=($)=>({get update(){return $.request.body.json()},header:$.request.headers.get(K$)||void 0,end:()=>{$.response.status=200},respond:(w)=>{$.response.type="json",$.response.body=w},unauthorized:()=>{$.response.status=401}}),ub=($)=>({get update(){return $.request.json()},header:$.request.headers.get(K$)||void 0,end:()=>$.respondWith(jX()),respond:(w)=>$.respondWith(MX(w)),unauthorized:()=>$.respondWith(TX())}),nb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(K$)||void 0,end:()=>{if(w)w(jX())},respond:(E)=>{if(w)w(MX(E))},unauthorized:()=>{if(w)w(TX())},handlerReturn:new Promise((E)=>w=E)}},hb=({request:$})=>{let w;return{get update(){return $.json()},header:$.headers.get(K$)||void 0,end:()=>{if(w)w(jX())},respond:(E)=>{if(w)w(MX(E))},unauthorized:()=>{if(w)w(TX())},handlerReturn:new Promise((E)=>w=E)}},cb=($,w)=>{var E;return{get update(){return $.json()},header:(E=$.headers.get(K$))!==null&&E!==void 0?E:void 0,end:()=>w.end(null),respond:(X)=>w.send(200,X),unauthorized:()=>w.send(401,ME)}},rb=($)=>{let w;return{get update(){return $.body},header:$.headers[zD],end(){w("")},respond(E){$.set.headers["content-type"]="application/json",w(E)},unauthorized(){$.set.status=401,w("")},handlerReturn:new Promise((E)=>w=E)}};CL.adapters={"aws-lambda":Vb,"aws-lambda-async":Pb,azure:qb,"azure-v4":Sb,bun:kb,cloudflare:bb,"cloudflare-mod":_b,elysia:rb,express:Zb,fastify:Cb,hono:fb,http:ZL,https:ZL,koa:vb,"next-js":xb,nhttp:yb,oak:gb,serveHttp:ub,"std/http":nb,sveltekit:hb,worktop:cb}});var uL=_((gL)=>{Object.defineProperty(gL,"__esModule",{value:!0});gL.webhookCallback=pb;var yL=rE(),tb=vL(),xL=(0,yL.debug)("grammy:error"),ob=($,w,E,X=()=>w('"unauthorized"'))=>({update:Promise.resolve($),respond:w,header:E,unauthorized:X}),mb={...tb.adapters,callback:ob};function ib($,w){if(w===void 0)return!0;if($===void 0)return!1;let E=new TextEncoder,X=E.encode($),G=E.encode(w);if(X.length!==G.length)return!1;let A=0;for(let N=0;N<G.length;N++){let D=N<X.length?X[N]:0,O=G[N];A|=D^O}return A===0}function pb($,w=yL.defaultAdapter,E,X,G){if($.isRunning())throw Error("Bot is already running via long polling, the webhook setup won't receive any updates!");else $.start=()=>{throw Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!")};let{onTimeout:A="throw",timeoutMilliseconds:N=1e4,secretToken:D}=typeof E==="object"?E:{onTimeout:E,timeoutMilliseconds:X,secretToken:G},O=!1,W=typeof w==="string"?mb[w]:w;return async(...J)=>{var Y;let H=W(...J);if(!O)await $.init(),O=!0;if(!ib(H.header,D))return await H.unauthorized(),H.handlerReturn;let L=!1,F={async send(j){L=!0,await H.respond(j)}};if(await db($.handleUpdate(await H.update,F),typeof A==="function"?()=>A(...J):A,N),!L)(Y=H.end)===null||Y===void 0||Y.call(H);return H.handlerReturn}}function db($,w,E){if(E===1/0)return $;return new Promise((X,G)=>{let A=setTimeout(()=>{if(xL(`Request timed out after ${E} ms`),w==="throw")G(Error(`Request timed out after ${E} ms`));else{if(typeof w==="function")w();X()}let N=Date.now();$.finally(()=>{let D=Date.now()-N;xL(`Request completed ${D} ms after timeout!`)})},E);$.then(X).catch(G).finally(()=>clearTimeout(A))})}});var cL=_((q0)=>{var sb=q0&&q0.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),RX=q0&&q0.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))sb(w,$,E)};Object.defineProperty(q0,"__esModule",{value:!0});q0.HttpError=q0.GrammyError=q0.Api=q0.matchFilter=q0.Composer=q0.Context=q0.InputFile=q0.BotError=q0.Bot=void 0;var nL=QJ();Object.defineProperty(q0,"Bot",{enumerable:!0,get:function(){return nL.Bot}});Object.defineProperty(q0,"BotError",{enumerable:!0,get:function(){return nL.BotError}});var ab=LJ();Object.defineProperty(q0,"InputFile",{enumerable:!0,get:function(){return ab.InputFile}});var eb=OD();Object.defineProperty(q0,"Context",{enumerable:!0,get:function(){return eb.Context}});RX(LL(),q0);RX(ML(),q0);RX(zL(),q0);RX(VL(),q0);RX(_L(),q0);RX(uL(),q0);var $_=AJ();Object.defineProperty(q0,"Composer",{enumerable:!0,get:function(){return $_.Composer}});var w_=ND();Object.defineProperty(q0,"matchFilter",{enumerable:!0,get:function(){return w_.matchFilter}});var E_=TJ();Object.defineProperty(q0,"Api",{enumerable:!0,get:function(){return E_.Api}});var hL=LD();Object.defineProperty(q0,"GrammyError",{enumerable:!0,get:function(){return hL.GrammyError}});Object.defineProperty(q0,"HttpError",{enumerable:!0,get:function(){return hL.HttpError}})});function kJ($){let w=new zX.InlineKeyboard;for(let E of $){for(let X of E)w.text(X.label,X.value);w.row()}return w}function G_($){let w=G0(),E=w.gateway.telegram.token;if(!E)throw Error("Telegram token is not configured.");let X=new zX.Bot(E),G=new Map,A=null;function N(H){let L=w.gateway.telegram.authorized_users.map(String);return L.length>0&&L.includes(String(H))}function D(H){let L=Date.now();if(G.has(H))return!0;G.set(H,L);for(let[F,j]of G)if(L-j>X_)G.delete(F);return!1}function O(H){if(!H)return!1;return H.getTime()<$}async function W(H){let L=await X.api.getFile(H),F=await fetch(`https://api.telegram.org/file/bot${E}/${L.file_path}`);return new Uint8Array(await F.arrayBuffer())}async function J(H){if(A)await A(H)}function Y(H,L,F){let j=H.from;return{platform:"telegram",chatId:String(H.chat?.id??H.callbackQuery?.message?.chat.id??""),userId:String(j.id),username:j.username,displayName:[j.first_name,j.last_name].filter(Boolean).join(" ").trim()||void 0,text:L,platformMessageId:String(H.msg?.message_id??H.message?.message_id??""),attachments:F}}return{platform:"telegram",async start(H){A=H;let L=["start","help","status","mode","cwd","agent","tasks","task","approve","reject","assign","jobs","run","mem","sessions","session"];X.command(L,async(F)=>{if(!F.from||!N(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`cmd:${j}`))return;if(O(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=F.message?.text?.split(" ")[0]?.replace(/^\//,"").split("@")[0]??"help",R=F.message?.text?.split(" ").slice(1).join(" ")??"",B=R?`/${M} ${R}`:`/${M}`;await J(Y(F,B))}),X.on("message",async(F)=>{if(!F.from||!N(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`msg:${j}`))return;if(O(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=[];if(F.message?.voice)try{M.push({kind:"audio",data:await W(F.message.voice.file_id),mimeType:F.message.voice.mime_type??"audio/ogg",format:"ogg",duration:F.message.voice.duration})}catch(B){SJ.warn("Failed to download voice message",{err:B})}if(F.message?.audio)try{M.push({kind:"audio",data:await W(F.message.audio.file_id),mimeType:F.message.audio.mime_type??"audio/mpeg",format:(F.message.audio.mime_type??"audio/mpeg").split("/").at(1)??"mp3",duration:F.message.audio.duration})}catch(B){SJ.warn("Failed to download audio message",{err:B})}let R=F.message?.text??F.message?.caption??"";if(!R&&M.length===0)return;await J(Y(F,R,M.length>0?M:void 0))}),X.on("callback_query:data",async(F)=>{if(!F.from||!N(F.from.id)||!F.callbackQuery)return;let j=F.callbackQuery.id;if(D(`cb:${j}`)){await F.answerCallbackQuery();return}let M=String(F.callbackQuery.message?.chat.id??F.chat?.id??""),R=`${M}:${F.callbackQuery.message?.message_id}`;await J({platform:"telegram",chatId:M,userId:String(F.from.id),username:F.from.username,displayName:[F.from.first_name,F.from.last_name].filter(Boolean).join(" ").trim()||void 0,text:F.callbackQuery.data??"",platformMessageId:R}),await F.answerCallbackQuery()}),SJ.info("Starting Telegram gateway adapter"),X.start({allowed_updates:["message","callback_query"]})},async stop(){X.stop()},async send(H,L,F){let j={};if(F?.parseMode==="html")j.parse_mode="HTML";if(F?.buttons?.length)j.reply_markup=kJ(F.buttons);let M=L.slice(0,4096),R=await X.api.sendMessage(H,M,j);return`${R.chat.id}:${R.message_id}`},async updateMessage(H,L,F,j){let[,M]=L.split(":");if(!M)return;let R={};if(j?.parseMode==="html")R.parse_mode="HTML";if(j?.buttons?.length)R.reply_markup=kJ(j.buttons);try{await X.api.editMessageText(H,Number(M),F.slice(0,4096),R)}catch(B){if(!String(B instanceof Error?B.message:"").includes("message is not modified"))throw B}},async sendWithButtons(H,L,F,j){let M={reply_markup:kJ(F)};if(j?.parseMode==="html")M.parse_mode="HTML";let R=await X.api.sendMessage(H,L.slice(0,4096),M);return`${R.chat.id}:${R.message_id}`},async downloadAudio(H){return W(H)},async sendAudio(H,L,F,j){let M=F==="ogg"||F==="oga"?"ogg":"mp3",R=new zX.InputFile(L,`audio.${M}`),B=j?{caption:j}:{};if(M==="ogg")await X.api.sendVoice(H,R,B);else await X.api.sendAudio(H,R,B)},async showTyping(H){try{await X.api.sendChatAction(H,"typing")}catch{}},async registerCommands(H){await X.api.setMyCommands(H.map((L)=>({command:L.command,description:L.description})))}}}var zX,SJ,X_=60000;var rL=T(()=>{R$();z$();lN();zX=UN(cL(),1),SJ=B0("gateway:telegram");dN("telegram",($)=>G_($))});import{existsSync as A_}from"fs";class tL{adapters=new Map;sessionLock=new sW;permissionManager=new lW;startTime=Date.now();adapterStatus=new Map;pendingSessionApprove=new Set;rateLimiter=new pW;async start(){let $=G0(),w=[];if($.gateway.telegram.enabled&&$.gateway.telegram.token)w.push("telegram");if($.gateway.slack.enabled&&$.gateway.slack.bot_token&&$.gateway.slack.app_token)w.push("slack");for(let G of w)try{let A=q7(G,this.startTime);this.adapters.set(A.platform,A),await this.safeStart(A)}catch(A){let N=dW(String(A));B1.error(`Failed to create ${G} adapter`,N),this.adapterStatus.set(G,{error:N})}for(let[,G]of this.adapters)if("registerCommands"in G)try{await G.registerCommands(N_)}catch(A){B1.warn("Failed to register bot commands",{platform:G.platform,err:A})}await r7();let E=G0();for(let G of["telegram","slack"]){let A=E.gateway[G];if(A.enabled&&A.authorized_users.length===0)B1.warn(`${G}: authorized_users is empty \u2014 all users will be denied. Add user IDs to config.`)}let X=[...this.adapters.keys()].join(", ");B1.info(`Gateway started with adapters: ${X||"none"}`)}async stop(){this.permissionManager.denyAll(),await Promise.all([...this.adapters.values()].map(($)=>$.stop().catch(()=>{}))),this.adapters.clear()}resolvePermission($,w){return this.permissionManager.resolve($,w)}async safeStart($){try{await $.start(async(w)=>this.handleIncoming(w)),this.adapterStatus.set($.platform,{})}catch(w){this.adapterStatus.set($.platform,{error:String(w)}),B1.error(`Failed to start ${$.platform} adapter`,dW(String(w)))}}normalizeCallbackText($){if($.startsWith("task:approve:"))return`/approve ${$.slice(13)}`;if($.startsWith("task:reject:"))return`/reject ${$.slice(12)}`;if($.startsWith("perm:approve:")){let w=$.slice(13);if(this.permissionManager.resolve(w,!0))return`__perm_resolved:${w}:approved`;return`/approve ${w}`}if($.startsWith("perm:deny:")){let w=$.slice(10);if(this.permissionManager.resolve(w,!1))return`__perm_resolved:${w}:denied`;return`/reject ${w}`}if($.startsWith("perm:session:")){let w=$.slice(13);return this.permissionManager.resolve(w,!0),this.pendingSessionApprove.add(w),`__perm_resolved:${w}:session`}return $}async handleIncoming($){let w=G0(),E=w.gateway[$.platform],X=E.authorized_users.map(String),G=await _7({platform:$.platform,chatId:$.chatId,username:$.username,displayName:$.displayName,authorized:X.length>0&&X.includes($.userId),mode:E.mode,threadId:$.threadId});if(!G.authorized)return;if(!this.rateLimiter.allow(G.id)){await this.sendText($,"\u23F8 Slow down \u2014 too many messages. Try again in a minute.");return}let A=$.text.trim(),N=$.attachments?.find((W)=>W.kind==="audio");if(A){if(A=this.normalizeCallbackText(A),A.startsWith("__perm_resolved:")){let J=A.split(":")[2],Y=J==="approved"?"\u2705 Permission approved.":J==="session"?"\u2705 Permission approved for this session.":"\u274C Permission denied.";if(await this.sendText($,Y),J==="session"){let H=await FE(G.id);if(H)await sw(H.id,{auto_approve:!0})}return}}if(!A&&N&&w.speech.enabled)try{let W=await GH({audio:N.data,format:N.format});await this.handleIncoming({...$,text:W,fromVoice:!0,attachments:[]});return}catch(W){await this.sendText($,`Voice transcription failed: ${W instanceof Error?W.message:String(W)}`);return}if(!A){await this.sendText($,"Send text or a voice message.");return}await JX({chatKey:G.id,direction:"in",role:"user",text:A,platformMessageId:$.platformMessageId,threadId:$.threadId,metadata:$.fromVoice?{from_voice:!0}:void 0});let D=await l7({chatKey:G.id,rawText:A,currentMode:G.mode,currentWorkingDir:G.working_dir});if(D){if(D.mode)G.mode=D.mode;let W=D.html??D.text??"",J=D.text??W,Y=D.html?"html":void 0,H=this.adapters.get($.platform);if(H&&D.buttons?.length&&"sendWithButtons"in H)await H.sendWithButtons($.chatId,W,D.buttons,{threadId:$.threadId,parseMode:Y});else if(H)await H.send($.chatId,W,{threadId:$.threadId,parseMode:Y});if($.fromVoice&&J)await this.trySendVoiceReply($,J);await JX({chatKey:G.id,direction:"out",role:"system",text:J,threadId:$.threadId});return}if(G.mode.startsWith("job:")){let W=G.mode.slice(4),J=await wD(W),Y=J?`Triggered ${J.name} \u2192 ${await Nw({jobId:J.id,triggerBy:"bridge-msg",envOverrides:{MSG:A}})}`:`Job not found: ${W}`;if(await this.sendText($,Y),$.fromVoice)await this.trySendVoiceReply($,Y);await JX({chatKey:G.id,direction:"out",role:"system",text:Y,threadId:$.threadId});return}if(G.mode==="direct"){await this.sendText($,"Direct mode active. Use /help for commands, or /agent claude to start an agent session."),await JX({chatKey:G.id,direction:"out",role:"system",text:"Direct mode active. Use /help for commands, or /agent claude to start an agent session.",threadId:$.threadId});return}let O=await s7({chatKey:G.id,mode:G.mode,cwd:G.working_dir});if(!this.sessionLock.tryAcquire(O.id)){await this.sendText($,`\u23F3 ${O.backend} is still processing \u2014 please wait.`);return}try{await this.runAgentTurnWithPreview($,G,O,A)}finally{this.sessionLock.release(O.id)}}async runAgentTurnWithPreview($,w,E,X){if(!E.cwd||!A_(E.cwd)){await this.sendText($,"Set a working directory first: /cwd <absolute-path>");return}let G=this.adapters.get($.platform);if(!G)return;if("showTyping"in G)await G.showTyping($.chatId).catch(()=>{});let A=await G.send($.chatId,`${E.backend} is thinking\u2026`,{threadId:$.threadId}),N=null;if(A&&ED.supports(G))N=new ED(G),await N.init(E.id,$.chatId,A,`${E.backend} is thinking\u2026`);await sw(E.id,{status:"running",last_activity_at:new Date});try{let D=await h7({chatKey:w.id,chatId:$.chatId,platform:$.platform,adapter:G,permissionManager:this.permissionManager,session:{id:E.id,backend:E.backend,cwd:E.cwd,model:E.model,runtime_session_id:E.runtime_session_id,auto_approve:E.auto_approve,task_id:E.task_id},threadId:$.threadId},X,A,N);if(await sw(E.id,{status:"idle",runtime_session_id:D.runtimeSessionId,last_activity_at:new Date,last_error:null}),N&&A)await N.finalize(E.id,D.output);else if(A&&"updateMessage"in G)await G.updateMessage($.chatId,A,D.output,{threadId:$.threadId}).catch(()=>G.send($.chatId,D.output,{threadId:$.threadId}));else await G.send($.chatId,D.output,{threadId:$.threadId});if(await JX({chatKey:w.id,direction:"out",role:"assistant",text:D.output,gatewaySessionId:E.id,threadId:$.threadId,platformMessageId:A}),$.fromVoice)await this.trySendVoiceReply($,D.output)}catch(D){N?.cleanup(E.id);let O=`Agent error: ${D instanceof Error?D.message:String(D)}`;await sw(E.id,{status:"error",last_error:O,last_activity_at:new Date});let W=O.slice(0,1000);if(A&&"updateMessage"in G)await G.updateMessage($.chatId,A,W,{threadId:$.threadId}).catch(()=>G.send($.chatId,W,{threadId:$.threadId}));else await G.send($.chatId,W,{threadId:$.threadId}).catch(()=>{});if(D instanceof Error&&/auth|api.key|401/i.test(D.message))await c7(E.id)}}async sendText($,w){let E=this.adapters.get($.platform);if(!E)return;await E.send($.chatId,w,{threadId:$.threadId})}async trySendVoiceReply($,w){if(!G0().tts.enabled)return;let X=this.adapters.get($.platform);if(!X||!("sendAudio"in X))return;try{let G=await AH(w);await X.sendAudio($.chatId,G.audio,G.format,"Voice reply")}catch(G){B1.warn("TTS failed",{err:G})}}async notifyTaskReview($){let w=await y7(),E=`\uD83D\uDC40 <b>Review requested</b>
410
411
 
411
412
  <b>${$.title}</b>
412
- ${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.taskId}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${$.taskId}`}]];await Promise.all(w.map(async(G)=>{let J=this.adapters.get(G.platform);if(!J)return;try{if("sendWithButtons"in J)await J.sendWithButtons(G.chat_id,E,X,{parseMode:"html"});else await J.send(G.chat_id,E,{parseMode:"html"})}catch(A){zE.warn("Failed to send review notification",{err:A,chat:G.id})}}))}async sendToChat($,w,E,X){let G=this.adapters.get($);if(!G)throw Error(`Adapter not available: ${$}`);await G.send(w,E,X)}getStatus(){return{adapters:[...this.adapters.keys()].map(($)=>{let w=this.adapterStatus.get($)?.error;return w?{name:$,error:w}:{name:$}}),startTime:this.startTime}}}async function PN(){if(ww)return;ww=new yL,await ww.start()}async function qN(){if(!ww)return;await ww.stop(),ww=null}function zA(){return ww}async function SN($,w,E,X){await ww?.sendToChat($,w,E,X)}function kN(){if(!ww)return"Gateway not running.";let{adapters:$,startTime:w}=ww.getStatus();return[`Started: ${new Date(w).toISOString()}`,`Adapters: ${$.length>0?$.map((X)=>`${X.name}${X.error?` (ERROR: ${X.error})`:" \u2713"}`).join(", "):"none"}`].join(`
413
- `)}var zE,ab,ww=null;var gL=R(()=>{C$();p$();nw();oJ();yY();gY();aJ();pY();oY();eY();xL();vG();zE=Z0("gateway"),ab=[{command:"help",description:"Show available commands"},{command:"status",description:"System status and sessions"},{command:"tasks",description:"List active tasks"},{command:"task",description:"Task details: /task <id>"},{command:"approve",description:"Approve task or permission"},{command:"reject",description:"Reject task or deny permission"},{command:"assign",description:"Assign task to agent: /assign <id> <agent>"},{command:"jobs",description:"List jobs"},{command:"run",description:"Run a job: /run <name>"},{command:"mem",description:"Search memories: /mem <query>"},{command:"agent",description:"Switch agent: /agent claude|codex|cursor"},{command:"sessions",description:"List agent sessions"},{command:"session",description:"Session lifecycle: new|list|switch|stop"},{command:"mode",description:"Switch routing mode"},{command:"cwd",description:"Set working directory"}]});var bN=R(()=>{gL();vG()});var mN,BX=($,w)=>{let E=new String($);return E.isEscaped=!0,E.callbacks=w,E},$C,z3=async($,w)=>{let E="";w||=[];let X=await Promise.all($);for(let G=X.length-1;;G--){if(E+=X[G],G--,G<0)break;let J=X[G];if(typeof J==="object")w.push(...J.callbacks||[]);let A=J.isEscaped;if(J=await(typeof J==="object"?J.toString():J),typeof J==="object")w.push(...J.callbacks||[]);if(J.isEscaped??A)E+=J;else{let D=[E];qA(J,D),E=D[0]}}return BX(E,w)},qA=($,w)=>{let E=$.search($C);if(E===-1){w[0]+=$;return}let X,G,J=0;for(G=E;G<$.length;G++){switch($.charCodeAt(G)){case 34:X="&quot;";break;case 39:X="&#39;";break;case 38:X="&amp;";break;case 60:X="&lt;";break;case 62:X="&gt;";break;default:continue}w[0]+=$.substring(J,G)+X,J=G+1}w[0]+=$.substring(J,G)},T3=($)=>{let w=$.callbacks;if(!w?.length)return $;let E=[$],X={};return w.forEach((G)=>G({phase:mN.Stringify,buffer:E,context:X})),E[0]},rN=async($,w,E,X,G)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let J=$.callbacks;if(!J?.length)return Promise.resolve($);if(G)G[0]+=$;else G=[$];let A=Promise.all(J.map((D)=>D({phase:w,buffer:G,context:X}))).then((D)=>Promise.all(D.filter(Boolean).map((N)=>rN(N,w,!1,X,G))).then(()=>G[0]));if(E)return BX(await A,J);else return A};var pN=R(()=>{mN={Stringify:1,BeforeStream:2,Stream:3},$C=/[&<>'"]/});var oN=($,...w)=>{let E=[""];for(let X=0,G=$.length-1;X<G;X++){E[0]+=$[X];let J=Array.isArray(w[X])?w[X].flat(1/0):[w[X]];for(let A=0,D=J.length;A<D;A++){let N=J[A];if(typeof N==="string")qA(N,E);else if(typeof N==="number")E[0]+=N;else if(typeof N==="boolean"||N===null||N===void 0)continue;else if(typeof N==="object"&&N.isEscaped)if(N.callbacks)E.unshift("",N);else{let W=N.toString();if(W instanceof Promise)E.unshift("",W);else E[0]+=W}else if(N instanceof Promise)E.unshift("",N);else qA(N.toString(),E)}}return E[0]+=$.at(-1),E.length===1?"callbacks"in E?BX(T3(BX(E[0],E.callbacks))):BX(E[0]):z3(E,E.callbacks)};var B3=R(()=>{pN()});var J0,Q3,wC=($)=>{return Object.entries($).map(([w,E])=>{let X=w;if(!Q3[X]||E===void 0)return"";switch(Q3[X]){case J0.STRING:return`${X}: '${E}'`;case J0.STRING_ARRAY:if(!Array.isArray(E))return"";return`${X}: [${E.map((G)=>`${G}`).join(",")}]`;case J0.JSON_STRING:return`${X}: ${JSON.stringify(E)}`;case J0.RAW:return`${X}: ${E}`;default:return""}}).filter((w)=>w!=="").join(",")},EC=({version:$})=>{let w=`https://cdn.jsdelivr.net/npm/swagger-ui-dist${$!==void 0?`@${$}`:""}`;return{css:[`${w}/swagger-ui.css`],js:[`${w}/swagger-ui-bundle.js`]}},XC=($)=>{let w=EC({version:$?.version});if(delete $.version,$.manuallySwaggerUIHtml)return $.manuallySwaggerUIHtml(w);let E=wC($);return`
413
+ ${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.taskId}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${$.taskId}`}]];await Promise.all(w.map(async(G)=>{let A=this.adapters.get(G.platform);if(!A)return;try{if("sendWithButtons"in A)await A.sendWithButtons(G.chat_id,E,X,{parseMode:"html"});else await A.send(G.chat_id,E,{parseMode:"html"})}catch(N){B1.warn("Failed to send review notification",{err:N,chat:G.id})}}))}async sendToChat($,w,E,X){let G=this.adapters.get($);if(!G)throw Error(`Adapter not available: ${$}`);await G.send(w,E,X)}getStatus(){return{adapters:[...this.adapters.keys()].map(($)=>{let w=this.adapterStatus.get($)?.error;return w?{name:$,error:w}:{name:$}}),startTime:this.startTime}}}async function bJ(){if($E)return;$E=new tL,await $E.start()}async function _J(){if(!$E)return;await $E.stop(),$E=null}function BD(){return $E}async function ZJ($,w,E,X){await $E?.sendToChat($,w,E,X)}function CJ(){if(!$E)return"Gateway not running.";let{adapters:$,startTime:w}=$E.getStatus();return[`Started: ${new Date(w).toISOString()}`,`Adapters: ${$.length>0?$.map((X)=>`${X.name}${X.error?` (ERROR: ${X.error})`:" \u2713"}`).join(", "):"none"}`].join(`
414
+ `)}var B1,N_,$E=null;var oL=T(()=>{R$();z$();cE();lN();t7();o7();$D();a7();e7();NH();rL();uG();B1=B0("gateway"),N_=[{command:"help",description:"Show available commands"},{command:"status",description:"System status and sessions"},{command:"tasks",description:"List active tasks"},{command:"task",description:"Task details: /task <id>"},{command:"approve",description:"Approve task or permission"},{command:"reject",description:"Reject task or deny permission"},{command:"assign",description:"Assign task to agent: /assign <id> <agent>"},{command:"jobs",description:"List jobs"},{command:"run",description:"Run a job: /run <name>"},{command:"mem",description:"Search memories: /mem <query>"},{command:"agent",description:"Switch agent: /agent claude|codex|cursor"},{command:"sessions",description:"List agent sessions"},{command:"session",description:"Session lifecycle: new|list|switch|stop"},{command:"mode",description:"Switch routing mode"},{command:"cwd",description:"Set working directory"}]});var fJ=T(()=>{oL();uG()});async function uJ($,w){gJ.info(`Review notification: task ${$} "${w}" ready for review`);try{let E=G0();if(E.gateway.telegram.enabled&&E.gateway.telegram.default_chat_id){let X=E.gateway.telegram.default_chat_id,G=`\uD83D\uDCCB Task ready for review:
415
+ *${w}*
416
+ ID: \`${$}\`
417
+
418
+ Approve: set status to "done"
419
+ Reject: set status to "changes_requested" with comment`,A=r();W$().query(`INSERT INTO bridge_messages (id, chat_id, direction, role, text, created_at)
420
+ SELECT ?, bc.id, 'out', 'system', ?, unixepoch()
421
+ FROM bridge_chats bc WHERE bc.platform = 'telegram' AND bc.chat_id = ? LIMIT 1`).run(A,G,X),gJ.info(`Review notification queued for Telegram chat ${X}`)}}catch(E){gJ.warn(`Failed to send review notification: ${String(E)}`)}}var gJ;var nJ=T(()=>{R$();B$();z$();J$();gJ=B0("task-service:notify")});var QD,pG,KD,aL,VD,S$0,k$0,b$0,hJ,_$0,Z$0,C$0,eL;var dG=T(()=>{LG();QD=U.enum(["todo","queued","doing","review","changes_requested","blocked","done","paused","cancelled"]),pG=U.enum(["low","normal","high","critical"]),KD=U.enum(["one-shot","cron","watch","webhook","manual","bridge-msg"]),aL=U.enum(["pending","running","success","failed","cancelled","skipped"]),VD=U.enum(["skip","queue","kill"]),S$0=U.enum(["low","normal","high","critical"]),k$0=U.enum(["telegram","slack","discord","feishu"]),b$0=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")),hJ=U.enum(["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]),_$0=U.enum(["active","archived","paused"]),Z$0=U.enum(["solo","pair","parallel","handoff"]),C$0=U.enum(["solo","human_agent","multi_agent"]),eL={todo:["doing","queued","paused","cancelled"],queued:["doing","todo","cancelled"],doing:["review","blocked","paused","cancelled"],blocked:["doing","todo","cancelled"],review:["done","changes_requested"],changes_requested:["doing","queued","paused"],done:[],paused:["todo"],cancelled:[]}});async function oE($,w,E="agent"){let X=f(),G=r();return await X.insert(F$).values({id:G,resource_type:"task",resource_id:$,content:w,author:E,created_at:new Date}),G}async function IX($){let w=f(),E=await w.query.tasks.findFirst({where:V(t.id,$.taskId)});if(!E)return{ok:!1,error:`Task not found: ${$.taskId}`};let X=E.status;if(!eL[X]?.includes($.status))return{ok:!1,error:`Cannot transition from ${X} to ${$.status}`};if($.status==="doing"){let W=W$().query(`SELECT t.id, t.title FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
422
+ WHERE tl.to_task_id = ? AND tl.link_type = 'blocks' AND t.status NOT IN ('done', 'cancelled')
423
+ UNION
424
+ SELECT t.id, t.title FROM task_links tl JOIN tasks t ON t.id = tl.to_task_id
425
+ WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by' AND t.status NOT IN ('done', 'cancelled')`).all($.taskId,$.taskId);if(W.length>0)return{ok:!1,error:`Cannot start: blocked by ${W.map((Y)=>`[${Y.id.slice(-6)}] ${Y.title}`).join(", ")}`}}let A=new Date,N={status:$.status,updated_at:A};if(($.status==="doing"||$.status==="queued")&&$.claimedBy)N.claimed_by=$.claimedBy;if($.status==="todo"&&(X==="doing"||X==="queued"))N.claimed_by=null;if($.status==="paused"||$.status==="blocked")N.claimed_by=null;if(await w.update(t).set(N).where(V(t.id,$.taskId)),$.comment)await oE($.taskId,$.comment,$.author??"agent");if($.status==="review"){if((await w.query.tasks.findFirst({where:V(t.id,$.taskId)}))?.required_review)uJ($.taskId,E.title).catch((W)=>{console.error(`notifyReview failed for task ${$.taskId}: ${String(W)}`)})}if(["done","cancelled"].includes($.status)){let O=W$(),W=O.query(`SELECT DISTINCT dependent_id AS id FROM (
426
+ SELECT tl.to_task_id AS dependent_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'blocks'
427
+ UNION SELECT tl.from_task_id AS dependent_id FROM task_links tl WHERE tl.to_task_id = ? AND tl.link_type = 'blocked_by'
428
+ )`).all($.taskId,$.taskId);for(let Y of W)if(!O.query(`SELECT 1 FROM (
429
+ SELECT tl.from_task_id AS blocker_id FROM task_links tl WHERE tl.to_task_id = ? AND tl.link_type = 'blocks'
430
+ UNION
431
+ SELECT tl.to_task_id AS blocker_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by'
432
+ ) b JOIN tasks t ON t.id = b.blocker_id WHERE t.status NOT IN ('done','cancelled') LIMIT 1`).get(Y.id,Y.id)){if(O.query("SELECT status FROM tasks WHERE id = ?").get(Y.id)?.status==="blocked")O.query("UPDATE tasks SET status = 'todo', updated_at = unixepoch() WHERE id = ?").run(Y.id)}let J=O.query("SELECT tl.to_task_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'subtask_of' LIMIT 1").get($.taskId);if(J){let Y=O.query(`SELECT COUNT(*) as total, SUM(CASE WHEN t.status IN ('done','cancelled') THEN 1 ELSE 0 END) as done
433
+ FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id WHERE tl.to_task_id = ? AND tl.link_type = 'subtask_of'`).get(J.to_task_id);if(Y&&Y.total>0){let H=Math.round(Y.done/Y.total*100);if(O.query("UPDATE tasks SET progress = ?, updated_at = unixepoch() WHERE id = ?").run(H,J.to_task_id),Y.done===Y.total){let L=O.query("SELECT status FROM tasks WHERE id = ?").get(J.to_task_id);if(L&&!["done","cancelled","review"].includes(L.status))O.query("UPDATE tasks SET status = 'review', claimed_by = NULL, updated_at = unixepoch() WHERE id = ?").run(J.to_task_id),await oE(J.to_task_id,"All subtasks complete \u2014 auto-promoted to review","system")}}}}if($.status==="changes_requested"){let O=W$(),W=E.max_review_rounds??3,J=O.query("SELECT id, review_rounds FROM gateway_sessions WHERE task_id = ? ORDER BY updated_at DESC LIMIT 1").get($.taskId);if(J&&W>0){let Y=J.review_rounds+1;if(O.query("UPDATE gateway_sessions SET review_rounds = ? WHERE id = ?").run(Y,J.id),Y>=W)await w.update(t).set({status:"paused",claimed_by:null,updated_at:A}).where(V(t.id,$.taskId)),await oE($.taskId,`Task exceeded max review rounds (${W}). Paused for manual attention.`,"system")}}return{ok:!0,task:await w.query.tasks.findFirst({where:V(t.id,$.taskId)})??void 0}}var $3=T(()=>{B$();dG();J$();Q$();f$();nJ()});var PD=T(()=>{nJ();$3()});var aJ,VX=($,w)=>{let E=new String($);return E.isEscaped=!0,E.callbacks=w,E},OZ,S3=async($,w)=>{let E="";w||=[];let X=await Promise.all($);for(let G=X.length-1;;G--){if(E+=X[G],G--,G<0)break;let A=X[G];if(typeof A==="object")w.push(...A.callbacks||[]);let N=A.isEscaped;if(A=await(typeof A==="object"?A.toString():A),typeof A==="object")w.push(...A.callbacks||[]);if(A.isEscaped??N)E+=A;else{let D=[E];CD(A,D),E=D[0]}}return VX(E,w)},CD=($,w)=>{let E=$.search(OZ);if(E===-1){w[0]+=$;return}let X,G,A=0;for(G=E;G<$.length;G++){switch($.charCodeAt(G)){case 34:X="&quot;";break;case 39:X="&#39;";break;case 38:X="&amp;";break;case 60:X="&lt;";break;case 62:X="&gt;";break;default:continue}w[0]+=$.substring(A,G)+X,A=G+1}w[0]+=$.substring(A,G)},k3=($)=>{let w=$.callbacks;if(!w?.length)return $;let E=[$],X={};return w.forEach((G)=>G({phase:aJ.Stringify,buffer:E,context:X})),E[0]},eJ=async($,w,E,X,G)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let A=$.callbacks;if(!A?.length)return Promise.resolve($);if(G)G[0]+=$;else G=[$];let N=Promise.all(A.map((D)=>D({phase:w,buffer:G,context:X}))).then((D)=>Promise.all(D.filter(Boolean).map((O)=>eJ(O,w,!1,X,G))).then(()=>G[0]));if(E)return VX(await N,A);else return N};var $4=T(()=>{aJ={Stringify:1,BeforeStream:2,Stream:3},OZ=/[&<>'"]/});var w4=($,...w)=>{let E=[""];for(let X=0,G=$.length-1;X<G;X++){E[0]+=$[X];let A=Array.isArray(w[X])?w[X].flat(1/0):[w[X]];for(let N=0,D=A.length;N<D;N++){let O=A[N];if(typeof O==="string")CD(O,E);else if(typeof O==="number")E[0]+=O;else if(typeof O==="boolean"||O===null||O===void 0)continue;else if(typeof O==="object"&&O.isEscaped)if(O.callbacks)E.unshift("",O);else{let W=O.toString();if(W instanceof Promise)E.unshift("",W);else E[0]+=W}else if(O instanceof Promise)E.unshift("",O);else CD(O.toString(),E)}}return E[0]+=$.at(-1),E.length===1?"callbacks"in E?VX(k3(VX(E[0],E.callbacks))):VX(E[0]):S3(E,E.callbacks)};var b3=T(()=>{$4()});var N0,_3,WZ=($)=>{return Object.entries($).map(([w,E])=>{let X=w;if(!_3[X]||E===void 0)return"";switch(_3[X]){case N0.STRING:return`${X}: '${E}'`;case N0.STRING_ARRAY:if(!Array.isArray(E))return"";return`${X}: [${E.map((G)=>`${G}`).join(",")}]`;case N0.JSON_STRING:return`${X}: ${JSON.stringify(E)}`;case N0.RAW:return`${X}: ${E}`;default:return""}}).filter((w)=>w!=="").join(",")},JZ=({version:$})=>{let w=`https://cdn.jsdelivr.net/npm/swagger-ui-dist${$!==void 0?`@${$}`:""}`;return{css:[`${w}/swagger-ui.css`],js:[`${w}/swagger-ui-bundle.js`]}},UZ=($)=>{let w=JZ({version:$?.version});if(delete $.version,$.manuallySwaggerUIHtml)return $.manuallySwaggerUIHtml(w);let E=WZ($);return`
414
434
  <div>
415
435
  <div id="swagger-ui"></div>
416
- ${w.css.map((X)=>oN`<link rel="stylesheet" href="${X}" />`)}
417
- ${w.js.map((X)=>oN`<script src="${X}" crossorigin="anonymous"><\/script>`)}
436
+ ${w.css.map((X)=>w4`<link rel="stylesheet" href="${X}" />`)}
437
+ ${w.js.map((X)=>w4`<script src="${X}" crossorigin="anonymous"><\/script>`)}
418
438
  <script>
419
439
  window.onload = () => {
420
440
  window.ui = SwaggerUIBundle({
@@ -423,7 +443,7 @@ ${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.t
423
443
  }
424
444
  </script>
425
445
  </div>
426
- `},I3=($)=>async(w)=>{let E=$?.title??"SwaggerUI";return w.html(`
446
+ `},Z3=($)=>async(w)=>{let E=$?.title??"SwaggerUI";return w.html(`
427
447
  <!doctype html>
428
448
  <html lang="en">
429
449
  <head>
@@ -433,161 +453,125 @@ ${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.t
433
453
  <title>${E}</title>
434
454
  </head>
435
455
  <body>
436
- ${XC($)}
456
+ ${UZ($)}
437
457
  </body>
438
458
  </html>
439
- `)};var K3=R(()=>{B3();J0={STRING_ARRAY:"string_array",STRING:"string",JSON_STRING:"json_string",RAW:"raw"},Q3={configUrl:J0.STRING,deepLinking:J0.RAW,presets:J0.STRING_ARRAY,plugins:J0.STRING_ARRAY,spec:J0.JSON_STRING,url:J0.STRING,urls:J0.JSON_STRING,layout:J0.STRING,docExpansion:J0.STRING,maxDisplayedTags:J0.RAW,operationsSorter:J0.RAW,requestInterceptor:J0.RAW,responseInterceptor:J0.RAW,persistAuthorization:J0.RAW,defaultModelsExpandDepth:J0.RAW,defaultModelExpandDepth:J0.RAW,defaultModelRendering:J0.STRING,displayRequestDuration:J0.RAW,filter:J0.RAW,showExtensions:J0.RAW,showCommonExtensions:J0.RAW,queryConfigEnabled:J0.RAW,displayOperationId:J0.RAW,tagsSorter:J0.RAW,onComplete:J0.RAW,syntaxHighlight:J0.JSON_STRING,tryItOutEnabled:J0.RAW,requestSnippetsEnabled:J0.RAW,requestSnippets:J0.JSON_STRING,oauth2RedirectUrl:J0.STRING,showMutabledRequest:J0.RAW,request:J0.JSON_STRING,supportedSubmitMethods:J0.JSON_STRING,validatorUrl:J0.STRING,withCredentials:J0.RAW,modelPropertyMacro:J0.RAW,parameterMacro:J0.RAW}});function iG($,w){var E={};for(var X in $)if(Object.prototype.hasOwnProperty.call($,X)&&w.indexOf(X)<0)E[X]=$[X];if($!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var G=0,X=Object.getOwnPropertySymbols($);G<X.length;G++)if(w.indexOf(X[G])<0&&Object.prototype.propertyIsEnumerable.call($,X[G]))E[X[G]]=$[X[G]]}return E}function N0($,w){var E;return((E=$===null||$===void 0?void 0:$._def)===null||E===void 0?void 0:E.typeName)===w}function GC($){return"_def"in $}function oG($,w){let E=$.ZodType.prototype[w];$.ZodType.prototype[w]=function(...X){let G=E.apply(this,X);return G._def.openapi=this._def.openapi,G}}function P3($){if(typeof $.ZodType.prototype.openapi<"u")return;$.ZodType.prototype.openapi=function(G,J){var A,D,N,W,O,Y;let H=typeof G==="string"?J:G,L=H!==null&&H!==void 0?H:{},{param:F}=L,j=iG(L,["param"]),M=Object.assign(Object.assign({},(A=this._def.openapi)===null||A===void 0?void 0:A._internal),typeof G==="string"?{refId:G}:void 0),z=Object.assign(Object.assign(Object.assign({},(D=this._def.openapi)===null||D===void 0?void 0:D.metadata),j),((W=(N=this._def.openapi)===null||N===void 0?void 0:N.metadata)===null||W===void 0?void 0:W.param)||F?{param:Object.assign(Object.assign({},(Y=(O=this._def.openapi)===null||O===void 0?void 0:O.metadata)===null||Y===void 0?void 0:Y.param),F)}:void 0),B=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(M).length>0?{_internal:M}:void 0),Object.keys(z).length>0?{metadata:z}:void 0)}));if(N0(this,"ZodObject")){let Q=this.extend;B.extend=function(...k){var v,C,n,T0,f0,c0,d0;let K0=Q.apply(this,k);return K0._def.openapi={_internal:{extendedFrom:((C=(v=this._def.openapi)===null||v===void 0?void 0:v._internal)===null||C===void 0?void 0:C.refId)?{refId:(T0=(n=this._def.openapi)===null||n===void 0?void 0:n._internal)===null||T0===void 0?void 0:T0.refId,schema:this}:(c0=(f0=this._def.openapi)===null||f0===void 0?void 0:f0._internal)===null||c0===void 0?void 0:c0.extendedFrom},metadata:(d0=K0._def.openapi)===null||d0===void 0?void 0:d0.metadata},K0}}return B},oG($,"optional"),oG($,"nullable"),oG($,"default"),oG($,"transform"),oG($,"refine");let w=$.ZodObject.prototype.deepPartial;$.ZodObject.prototype.deepPartial=function(){let G=this._def.shape(),J=w.apply(this),A=J._def.shape();return Object.entries(A).forEach(([D,N])=>{var W,O;N._def.openapi=(O=(W=G[D])===null||W===void 0?void 0:W._def)===null||O===void 0?void 0:O.openapi}),J._def.openapi=void 0,J};let E=$.ZodObject.prototype.pick;$.ZodObject.prototype.pick=function(...G){let J=E.apply(this,G);return J._def.openapi=void 0,J};let X=$.ZodObject.prototype.omit;$.ZodObject.prototype.omit=function(...G){let J=X.apply(this,G);return J._def.openapi=void 0,J}}function SA($,w){if($===null||$===void 0||w===null||w===void 0)return $===w;if($===w||$.valueOf()===w.valueOf())return!0;if(Array.isArray($)){if(!Array.isArray(w))return!1;if($.length!==w.length)return!1}if(!($ instanceof Object)||!(w instanceof Object))return!1;let E=Object.keys($);return Object.keys(w).every((X)=>E.indexOf(X)!==-1)&&E.every((X)=>SA($[X],w[X]))}class q3{constructor(){this.buckets=new Map}put($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E){this.buckets.set(w,[$]);return}if(!E.some((G)=>SA(G,$)))E.push($)}contains($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E)return!1;return E.some((X)=>SA(X,$))}values(){return[...this.buckets.values()].flat()}stats(){let $=0,w=0,E=0;for(let G of this.buckets.values())if($+=1,w+=G.length,G.length>1)E+=1;let X=$/w;return{totalBuckets:$,collisions:E,totalValues:w,hashEffectiveness:X}}hashCodeOf($){let w=0;if(Array.isArray($)){for(let E=0;E<$.length;E++)w^=this.hashCodeOf($[E])*E;return w}if(typeof $==="string"){for(let E=0;E<$.length;E++)w^=$.charCodeAt(E)*E;return w}if(typeof $==="number")return $;if(typeof $==="object")for(let[E,X]of Object.entries($))w^=this.hashCodeOf(E)+this.hashCodeOf(X!==null&&X!==void 0?X:"");return w}}function dG($){return $===void 0}function lG($,w){let E={};return Object.entries($).forEach(([X,G])=>{E[X]=w(G)}),E}function JC($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w.some((J)=>J===X))E[X]=G}),E}function IX($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w(G,X))E[X]=G}),E}function V3($){return $.filter((w)=>!dG(w))}function AC($){let w=new q3;return $.forEach((E)=>w.put(E)),[...w.values()]}function S3($){return typeof $==="string"}class iN{constructor($){this.parents=$,this._definitions=[]}get definitions(){var $,w;return[...(w=($=this.parents)===null||$===void 0?void 0:$.flatMap((X)=>X.definitions))!==null&&w!==void 0?w:[],...this._definitions]}register($,w){let E=this.schemaWithRefId($,w);return this._definitions.push({type:"schema",schema:E}),E}registerParameter($,w){var E,X,G;let J=this.schemaWithRefId($,w),A=(E=J._def.openapi)===null||E===void 0?void 0:E.metadata,D=J.openapi(Object.assign(Object.assign({},A),{param:Object.assign(Object.assign({},A===null||A===void 0?void 0:A.param),{name:(G=(X=A===null||A===void 0?void 0:A.param)===null||X===void 0?void 0:X.name)!==null&&G!==void 0?G:$})}));return this._definitions.push({type:"parameter",schema:D}),D}registerPath($){this._definitions.push({type:"route",route:$})}registerWebhook($){this._definitions.push({type:"webhook",webhook:$})}registerComponent($,w,E){return this._definitions.push({type:"component",componentType:$,name:w,component:E}),{name:w,ref:{$ref:`#/components/${$}/${w}`}}}schemaWithRefId($,w){return w.openapi($)}}class aG{constructor($){this.message=$}}function tG($,w){try{return $()}catch(E){if(E instanceof sG)throw new sG(Object.assign(Object.assign({},E.data),w));throw E}}class g0{static getMetadata($){var w;let E=this.unwrapChained($),X=$._def.openapi?$._def.openapi:E._def.openapi,G=(w=$.description)!==null&&w!==void 0?w:E.description;return{_internal:X===null||X===void 0?void 0:X._internal,metadata:Object.assign({description:G},X===null||X===void 0?void 0:X.metadata)}}static getInternalMetadata($){let w=this.unwrapChained($),E=$._def.openapi?$._def.openapi:w._def.openapi;return E===null||E===void 0?void 0:E._internal}static getParamMetadata($){var w,E;let X=this.unwrapChained($),G=$._def.openapi?$._def.openapi:X._def.openapi,J=(w=$.description)!==null&&w!==void 0?w:X.description;return{_internal:G===null||G===void 0?void 0:G._internal,metadata:Object.assign(Object.assign({},G===null||G===void 0?void 0:G.metadata),{param:Object.assign({description:J},(E=G===null||G===void 0?void 0:G.metadata)===null||E===void 0?void 0:E.param)})}}static buildSchemaMetadata($){return IX(JC($,["param"]),dG)}static buildParameterMetadata($){return IX($,dG)}static applySchemaMetadata($,w){return IX(Object.assign(Object.assign({},$),this.buildSchemaMetadata(w)),dG)}static getRefId($){var w;return(w=this.getInternalMetadata($))===null||w===void 0?void 0:w.refId}static unwrapChained($){return this.unwrapUntil($)}static getDefaultValue($){let w=this.unwrapUntil($,"ZodDefault");return w===null||w===void 0?void 0:w._def.defaultValue()}static unwrapUntil($,w){if(w&&N0($,w))return $;if(N0($,"ZodOptional")||N0($,"ZodNullable")||N0($,"ZodBranded"))return this.unwrapUntil($.unwrap(),w);if(N0($,"ZodDefault")||N0($,"ZodReadonly"))return this.unwrapUntil($._def.innerType,w);if(N0($,"ZodEffects"))return this.unwrapUntil($._def.schema,w);if(N0($,"ZodPipeline"))return this.unwrapUntil($._def.in,w);return w?void 0:$}static isOptionalSchema($){return $.isOptional()}}class b3{transform($,w,E){var X,G;let J=$._def.type;return Object.assign(Object.assign({},w("array")),{items:E(J),minItems:(X=$._def.minLength)===null||X===void 0?void 0:X.value,maxItems:(G=$._def.maxLength)===null||G===void 0?void 0:G.value})}}class Z3{transform($){return Object.assign(Object.assign({},$("string")),{pattern:"^d+$"})}}class C3{transform($,w,E,X,G){let J=[...$.options.values()],A=J.map(X);if(w)return{oneOf:E(A,w)};return{oneOf:A,discriminator:this.mapDiscriminator(J,$.discriminator,G)}}mapDiscriminator($,w,E){if($.some((G)=>g0.getRefId(G)===void 0))return;let X={};return $.forEach((G)=>{var J;let A=g0.getRefId(G),D=(J=G.shape)===null||J===void 0?void 0:J[w];if(N0(D,"ZodEnum")||N0(D,"ZodNativeEnum")){Object.values(D.enum).filter(S3).forEach((O)=>{X[O]=E(A)});return}let N=D===null||D===void 0?void 0:D._def.value;if(typeof N!=="string")throw Error(`Discriminator ${w} could not be found in one of the values of a discriminated union`);X[N]=E(A)}),{propertyName:w,mapping:X}}}class _3{transform($,w){return Object.assign(Object.assign({},w("string")),{enum:$._def.values})}}class v3{transform($,w,E,X){let J={allOf:this.flattenIntersectionTypes($).map(X)};if(w)return{anyOf:E([J],w)};return J}flattenIntersectionTypes($){if(!N0($,"ZodIntersection"))return[$];let w=this.flattenIntersectionTypes($._def.left),E=this.flattenIntersectionTypes($._def.right);return[...w,...E]}}class f3{transform($,w){return Object.assign(Object.assign({},w(typeof $._def.value)),{enum:[$._def.value]})}}function DC($){let E=Object.keys($).filter((J)=>typeof $[$[J]]!=="number").map((J)=>$[J]),X=E.filter((J)=>typeof J==="number").length,G=X===0?"string":X===E.length?"numeric":"mixed";return{values:E,type:G}}class x3{transform($,w){let{type:E,values:X}=DC($._def.values);if(E==="mixed")throw new aG("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},w(E==="numeric"?"integer":"string")),{enum:X})}}class y3{transform($,w,E){return Object.assign(Object.assign({},w($.isInt?"integer":"number")),E($._def.checks))}}class g3{transform($,w,E,X){var G;let J=(G=g0.getInternalMetadata($))===null||G===void 0?void 0:G.extendedFrom,A=this.requiredKeysOf($),D=lG($._def.shape(),X);if(!J)return Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{properties:D,default:w}),A.length>0?{required:A}:{}),this.generateAdditionalProperties($,X));let N=J.schema;X(N);let W=this.requiredKeysOf(N),O=lG(N===null||N===void 0?void 0:N._def.shape(),X),Y=Object.fromEntries(Object.entries(D).filter(([F,j])=>{return!tN(O[F],j)})),H=A.filter((F)=>!W.includes(F)),L=Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{default:w,properties:Y}),H.length>0?{required:H}:{}),this.generateAdditionalProperties($,X));return{allOf:[{$ref:`#/components/schemas/${J.refId}`},L]}}generateAdditionalProperties($,w){let E=$._def.unknownKeys,X=$._def.catchall;if(N0(X,"ZodNever")){if(E==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:w(X)}}requiredKeysOf($){return Object.entries($._def.shape()).filter(([w,E])=>!g0.isOptionalSchema(E)).map(([w,E])=>w)}}class u3{transform($,w,E){let X=$._def.valueType,G=$._def.keyType,J=E(X);if(N0(G,"ZodEnum")||N0(G,"ZodNativeEnum")){let D=Object.values(G.enum).filter(S3).reduce((N,W)=>Object.assign(Object.assign({},N),{[W]:J}),{});return Object.assign(Object.assign({},w("object")),{properties:D})}return Object.assign(Object.assign({},w("object")),{additionalProperties:J})}}class h3{transform($,w){var E,X,G;let J=this.getZodStringCheck($,"regex"),A=(E=this.getZodStringCheck($,"length"))===null||E===void 0?void 0:E.value,D=Number.isFinite($.minLength)?(X=$.minLength)!==null&&X!==void 0?X:void 0:void 0,N=Number.isFinite($.maxLength)?(G=$.maxLength)!==null&&G!==void 0?G:void 0:void 0;return Object.assign(Object.assign({},w("string")),{minLength:A!==null&&A!==void 0?A:D,maxLength:A!==null&&A!==void 0?A:N,format:this.mapStringFormat($),pattern:J===null||J===void 0?void 0:J.regex.source})}mapStringFormat($){if($.isUUID)return"uuid";if($.isEmail)return"email";if($.isURL)return"uri";if($.isDate)return"date";if($.isDatetime)return"date-time";if($.isCUID)return"cuid";if($.isCUID2)return"cuid2";if($.isULID)return"ulid";if($.isIP)return"ip";if($.isEmoji)return"emoji";return}getZodStringCheck($,w){return $._def.checks.find((E)=>{return E.kind===w})}}class c3{constructor($){this.versionSpecifics=$}transform($,w,E){let{items:X}=$._def,G=X.map(E);return Object.assign(Object.assign({},w("array")),this.versionSpecifics.mapTupleItems(G))}}class n3{transform($,w,E){let G=this.flattenUnionTypes($).map((J)=>{let A=this.unwrapNullable(J);return E(A)});return{anyOf:w(G)}}flattenUnionTypes($){if(!N0($,"ZodUnion"))return[$];return $._def.options.flatMap((E)=>this.flattenUnionTypes(E))}unwrapNullable($){if(N0($,"ZodNullable"))return this.unwrapNullable($.unwrap());return $}}class m3{constructor($){this.versionSpecifics=$,this.objectTransformer=new g3,this.stringTransformer=new h3,this.numberTransformer=new y3,this.bigIntTransformer=new Z3,this.literalTransformer=new f3,this.enumTransformer=new _3,this.nativeEnumTransformer=new x3,this.arrayTransformer=new b3,this.unionTransformer=new n3,this.discriminatedUnionTransformer=new C3,this.intersectionTransformer=new v3,this.recordTransformer=new u3,this.tupleTransformer=new c3($)}transform($,w,E,X,G){if(N0($,"ZodNull"))return this.versionSpecifics.nullType;if(N0($,"ZodUnknown")||N0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(N0($,"ZodObject"))return this.objectTransformer.transform($,G,(A)=>this.versionSpecifics.mapNullableType(A,w),E);let J=this.transformSchemaWithoutDefault($,w,E,X);return Object.assign(Object.assign({},J),{default:G})}transformSchemaWithoutDefault($,w,E,X){if(N0($,"ZodUnknown")||N0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(N0($,"ZodString"))return this.stringTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodNumber"))return this.numberTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),(J)=>this.versionSpecifics.getNumberChecks(J));if(N0($,"ZodBigInt"))return this.bigIntTransformer.transform((J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",w);if(N0($,"ZodLiteral"))return this.literalTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodEnum"))return this.enumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodNativeEnum"))return this.nativeEnumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodArray"))return this.arrayTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodTuple"))return this.tupleTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodUnion"))return this.unionTransformer.transform($,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E);if(N0($,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E,X);if(N0($,"ZodIntersection"))return this.intersectionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E);if(N0($,"ZodRecord"))return this.recordTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodDate"))return this.versionSpecifics.mapNullableType("string",w);let G=g0.getRefId($);throw new k3({currentSchema:$._def,schemaName:G})}}class dN{constructor($,w){this.definitions=$,this.versionSpecifics=w,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new m3(w),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents()}}buildComponents(){var $,w;let E={};return this.rawComponents.forEach(({componentType:X,name:G,component:J})=>{var A;(A=E[X])!==null&&A!==void 0||(E[X]={}),E[X][G]=J}),Object.assign(Object.assign({},E),{schemas:Object.assign(Object.assign({},($=E.schemas)!==null&&$!==void 0?$:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(w=E.parameters)!==null&&w!==void 0?w:{}),this.paramRefs)})}sortDefinitions(){let $=["schema","parameter","component","route"];this.definitions.sort((w,E)=>{if(!("type"in w)){if(!("type"in E))return 0;return-1}if(!("type"in E))return 1;let X=$.findIndex((J)=>J===w.type),G=$.findIndex((J)=>J===E.type);return X-G})}generateSingle($){if(!("type"in $)){this.generateSchemaWithRef($);return}switch($.type){case"parameter":this.generateParameterDefinition($.schema);return;case"schema":this.generateSchemaWithRef($.schema);return;case"route":this.generateSingleRoute($.route);return;case"component":this.rawComponents.push($);return}}generateParameterDefinition($){let w=g0.getRefId($),E=this.generateParameter($);if(w)this.paramRefs[w]=E;return E}getParameterRef($,w){var E,X,G,J,A;let D=(E=$===null||$===void 0?void 0:$.metadata)===null||E===void 0?void 0:E.param,N=((X=$===null||$===void 0?void 0:$._internal)===null||X===void 0?void 0:X.refId)?this.paramRefs[(G=$._internal)===null||G===void 0?void 0:G.refId]:void 0;if(!((J=$===null||$===void 0?void 0:$._internal)===null||J===void 0?void 0:J.refId)||!N)return;if(D&&N.in!==D.in||(w===null||w===void 0?void 0:w.in)&&N.in!==w.in)throw new QX(`Conflicting location for parameter ${N.name}`,{key:"in",values:V3([N.in,w===null||w===void 0?void 0:w.in,D===null||D===void 0?void 0:D.in])});if(D&&N.name!==D.name||(w===null||w===void 0?void 0:w.name)&&N.name!==(w===null||w===void 0?void 0:w.name))throw new QX("Conflicting names for parameter",{key:"name",values:V3([N.name,w===null||w===void 0?void 0:w.name,D===null||D===void 0?void 0:D.name])});return{$ref:`#/components/parameters/${(A=$._internal)===null||A===void 0?void 0:A.refId}`}}generateInlineParameters($,w){var E;let X=g0.getMetadata($),G=(E=X===null||X===void 0?void 0:X.metadata)===null||E===void 0?void 0:E.param,J=this.getParameterRef(X,{in:w});if(J)return[J];if(N0($,"ZodObject")){let A=$._def.shape();return Object.entries(A).map(([N,W])=>{var O,Y;let H=g0.getMetadata(W),L=this.getParameterRef(H,{in:w,name:N});if(L)return L;let F=(O=H===null||H===void 0?void 0:H.metadata)===null||O===void 0?void 0:O.param;if((F===null||F===void 0?void 0:F.name)&&F.name!==N)throw new QX("Conflicting names for parameter",{key:"name",values:[N,F.name]});if((F===null||F===void 0?void 0:F.in)&&F.in!==w)throw new QX(`Conflicting location for parameter ${(Y=F.name)!==null&&Y!==void 0?Y:N}`,{key:"in",values:[w,F.in]});return this.generateParameter(W.openapi({param:{name:N,in:w}}))})}if((G===null||G===void 0?void 0:G.in)&&G.in!==w)throw new QX(`Conflicting location for parameter ${G.name}`,{key:"in",values:[w,G.in]});return[this.generateParameter($.openapi({param:{in:w}}))]}generateSimpleParameter($){var w;let E=g0.getParamMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=!g0.isOptionalSchema($)&&!$.isNullable(),J=this.generateSchemaWithRef($);return Object.assign({schema:J,required:G},X?g0.buildParameterMetadata(X):{})}generateParameter($){var w;let E=g0.getMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=X===null||X===void 0?void 0:X.name,J=X===null||X===void 0?void 0:X.in;if(!G)throw new sG({missingField:"name"});if(!J)throw new sG({missingField:"in",paramName:G});let A=this.generateSimpleParameter($);return Object.assign(Object.assign({},A),{in:J,name:G})}generateSchemaWithMetadata($){var w;let E=g0.unwrapChained($),X=g0.getMetadata($),G=g0.getDefaultValue($),J=((w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.type)?{type:X===null||X===void 0?void 0:X.metadata.type}:this.toOpenAPISchema(E,$.isNullable(),G);return(X===null||X===void 0?void 0:X.metadata)?g0.applySchemaMetadata(J,X.metadata):IX(J,dG)}constructReferencedOpenAPISchema($){var w;let E=g0.getMetadata($),X=g0.unwrapChained($),G=g0.getDefaultValue($),J=$.isNullable();if((w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.type)return this.versionSpecifics.mapNullableType(E.metadata.type,J);return this.toOpenAPISchema(X,J,G)}generateSimpleSchema($){var w;let E=g0.getMetadata($),X=g0.getRefId($);if(!X||!this.schemaRefs[X])return this.generateSchemaWithMetadata($);let G=this.schemaRefs[X],J={$ref:this.generateSchemaRef(X)},A=IX(g0.buildSchemaMetadata((w=E===null||E===void 0?void 0:E.metadata)!==null&&w!==void 0?w:{}),(W,O)=>W===void 0||tN(W,G[O]));if(A.type)return{allOf:[J,A]};let D=IX(this.constructReferencedOpenAPISchema($),(W,O)=>W===void 0||tN(W,G[O])),N=g0.applySchemaMetadata(D,A);if(Object.keys(N).length>0)return{allOf:[J,N]};return J}generateSchemaWithRef($){let w=g0.getRefId($),E=this.generateSimpleSchema($);if(w&&this.schemaRefs[w]===void 0)return this.schemaRefs[w]=E,{$ref:this.generateSchemaRef(w)};return E}generateSchemaRef($){return`#/components/schemas/${$}`}getRequestBody($){if(!$)return;let{content:w}=$,E=iG($,["content"]),X=this.getBodyContent(w);return Object.assign(Object.assign({},E),{content:X})}getParameters($){if(!$)return[];let{headers:w}=$,E=this.cleanParameter($.query),X=this.cleanParameter($.params),G=this.cleanParameter($.cookies),J=tG(()=>E?this.generateInlineParameters(E,"query"):[],{location:"query"}),A=tG(()=>X?this.generateInlineParameters(X,"path"):[],{location:"path"}),D=tG(()=>G?this.generateInlineParameters(G,"cookie"):[],{location:"cookie"}),N=tG(()=>{if(Array.isArray(w))return w.flatMap((O)=>this.generateInlineParameters(O,"header"));let W=this.cleanParameter(w);return W?this.generateInlineParameters(W,"header"):[]},{location:"header"});return[...A,...J,...N,...D]}cleanParameter($){if(!$)return;return N0($,"ZodEffects")?this.cleanParameter($._def.schema):$}generatePath($){let{method:w,path:E,request:X,responses:G}=$,J=iG($,["method","path","request","responses"]),A=lG(G,(O)=>{return this.getResponse(O)}),D=tG(()=>this.getParameters(X),{route:`${w} ${E}`}),N=this.getRequestBody(X===null||X===void 0?void 0:X.body);return{[w]:Object.assign(Object.assign(Object.assign(Object.assign({},J),D.length>0?{parameters:[...J.parameters||[],...D]}:{}),N?{requestBody:N}:{}),{responses:A})}}generateSingleRoute($){let w=this.generatePath($);return this.pathRefs[$.path]=Object.assign(Object.assign({},this.pathRefs[$.path]),w),w}getResponse($){if(this.isReferenceObject($))return $;let{content:w,headers:E}=$,X=iG($,["content","headers"]),G=w?{content:this.getBodyContent(w)}:{};if(!E)return Object.assign(Object.assign({},X),G);let J=N0(E,"ZodObject")?this.getResponseHeaders(E):E;return Object.assign(Object.assign(Object.assign({},X),{headers:J}),G)}isReferenceObject($){return"$ref"in $}getResponseHeaders($){let w=$._def.shape();return lG(w,(X)=>this.generateSimpleParameter(X))}getBodyContent($){return lG($,(w)=>{if(!w||!GC(w.schema))return w;let{schema:E}=w,X=iG(w,["schema"]),G=this.generateSchemaWithRef(E);return Object.assign({schema:G},X)})}toOpenAPISchema($,w,E){return this.openApiTransformer.transform($,w,(X)=>this.generateSchemaWithRef(X),(X)=>this.generateSchemaRef(X),E)}}class r3{get nullType(){return{nullable:!0}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){return Object.assign(Object.assign({},$?{type:$}:void 0),w?this.nullType:void 0)}mapTupleItems($){let w=AC($);return{items:w.length===1?w[0]:{anyOf:w},minItems:$.length,maxItems:$.length}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{minimum:Number(w.value),exclusiveMinimum:!0};case"max":return w.inclusive?{maximum:Number(w.value)}:{maximum:Number(w.value),exclusiveMaximum:!0};default:return{}}}))}}class lN{constructor($){let w=new r3;this.generator=new dN($,w)}generateDocument($){let w=this.generator.generateDocumentData();return Object.assign(Object.assign({},$),w)}generateComponents(){return this.generator.generateComponents()}}class p3{get nullType(){return{type:"null"}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){if(!$)return{};if(w)return{type:Array.isArray($)?[...$,"null"]:[$,"null"]};return{type:$}}mapTupleItems($){return{prefixItems:$}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{exclusiveMinimum:Number(w.value)};case"max":return w.inclusive?{maximum:Number(w.value)}:{exclusiveMaximum:Number(w.value)};default:return{}}}))}}function NC($){return"type"in $&&$.type==="webhook"}class sN{constructor($){this.definitions=$,this.webhookRefs={};let w=new p3;this.generator=new dN(this.definitions,w)}generateDocument($){let w=this.generator.generateDocumentData();return this.definitions.filter(NC).forEach((E)=>this.generateSingleWebhook(E.webhook)),Object.assign(Object.assign(Object.assign({},$),w),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook($){let w=this.generator.generatePath($);return this.webhookRefs[$.path]=Object.assign(Object.assign({},this.webhookRefs[$.path]),w),w}}var tN,QX,sG,k3;var o3=R(()=>{tN=SA;QX=class QX extends aG{constructor($,w){super($);this.data=w}};sG=class sG extends aG{constructor($){super(`Missing parameter data, please specify \`${$.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=$}};k3=class k3 extends aG{constructor($){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=$}}});var eN=($)=>{let w=$.split("/");if(w[0]==="")w.shift();return w},t3=($)=>{let{groups:w,path:E}=WC($),X=eN(E);return OC(X,w)},WC=($)=>{let w=[];return $=$.replace(/\{[^}]+\}/g,(E,X)=>{let G=`@${X}`;return w.push([G,E]),G}),{groups:w,path:$}},OC=($,w)=>{for(let E=w.length-1;E>=0;E--){let[X]=w[E];for(let G=$.length-1;G>=0;G--)if($[G].includes(X)){$[G]=$[G].replace(X,w[E][1]);break}}return $},kA,i3=($,w)=>{if($==="*")return"*";let E=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(E){let X=`${$}#${w}`;if(!kA[X])if(E[2])kA[X]=w&&w[0]!==":"&&w[0]!=="*"?[X,E[1],new RegExp(`^${E[2]}(?=/${w})`)]:[$,E[1],new RegExp(`^${E[2]}$`)];else kA[X]=[$,E[1],!0];return kA[X]}return null},KX=($,w)=>{try{return w($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(E)=>{try{return w(E)}catch{return E}})}},UC=($)=>KX($,decodeURI),$9=($)=>{let w=$.url,E=w.indexOf("/",w.indexOf(":")+4),X=E;for(;X<w.length;X++){let G=w.charCodeAt(X);if(G===37){let J=w.indexOf("?",X),A=w.indexOf("#",X),D=J===-1?A===-1?void 0:A:A===-1?J:Math.min(J,A),N=w.slice(E,D);return UC(N.includes("%25")?N.replace(/%25/g,"%2525"):N)}else if(G===63||G===35)break}return w.slice(E,X)},d3=($)=>{let w=$9($);return w.length>1&&w.at(-1)==="/"?w.slice(0,-1):w},f1=($,w,...E)=>{if(E.length)w=f1(w,...E);return`${$?.[0]==="/"?"":"/"}${$}${w==="/"?"":`${$?.at(-1)==="/"?"":"/"}${w?.[0]==="/"?w.slice(1):w}`}`},bA=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let w=$.split("/"),E=[],X="";return w.forEach((G)=>{if(G!==""&&!/\:/.test(G))X+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(E.length===0&&X==="")E.push("/");else E.push(X);let J=G.replace("?","");X+="/"+J,E.push(X)}else X+="/"+G}),E.filter((G,J,A)=>A.indexOf(G)===J)},aN=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?KX($,eG):$},l3=($,w,E)=>{let X;if(!E&&w&&!/[%+]/.test(w)){let A=$.indexOf("?",8);if(A===-1)return;if(!$.startsWith(w,A+1))A=$.indexOf(`&${w}`,A+1);while(A!==-1){let D=$.charCodeAt(A+w.length+1);if(D===61){let N=A+w.length+2,W=$.indexOf("&",N);return aN($.slice(N,W===-1?void 0:W))}else if(D==38||isNaN(D))return"";A=$.indexOf(`&${w}`,A+1)}if(X=/[%+]/.test($),!X)return}let G={};X??=/[%+]/.test($);let J=$.indexOf("?",8);while(J!==-1){let A=$.indexOf("&",J+1),D=$.indexOf("=",J);if(D>A&&A!==-1)D=-1;let N=$.slice(J+1,D===-1?A===-1?void 0:A:D);if(X)N=aN(N);if(J=A,N==="")continue;let W;if(D===-1)W="";else if(W=$.slice(D+1,A===-1?void 0:A),X)W=aN(W);if(E){if(!(G[N]&&Array.isArray(G[N])))G[N]=[];G[N].push(W)}else G[N]??=W}return w?G[w]:G},s3,a3=($,w)=>{return l3($,w,!0)},eG;var pw=R(()=>{kA={},s3=l3,eG=decodeURIComponent});var YC,HC,w9=($,w)=>{if(w&&$.indexOf(w)===-1)return{};let E=$.trim().split(";"),X={};for(let G of E){G=G.trim();let J=G.indexOf("=");if(J===-1)continue;let A=G.substring(0,J).trim();if(w&&w!==A||!YC.test(A))continue;let D=G.substring(J+1).trim();if(D.startsWith('"')&&D.endsWith('"'))D=D.slice(1,-1);if(HC.test(D)){if(X[A]=D.indexOf("%")!==-1?KX(D,eG):D,w)break}}return X};var e3=R(()=>{pw();YC=/^[\w!#$%&'*.^`|~+-]+$/,HC=/^[ !#-:<-[\]-~]*$/});var $F=($,w,E)=>{let X=$.req.raw.headers.get("Cookie");if(typeof w==="string"){if(!X)return;let J=w;if(E==="secure")J="__Secure-"+w;else if(E==="host")J="__Host-"+w;return w9(X,J)[J]}if(!X)return{};return w9(X)};var wF=R(()=>{e3()});var ZA;var E9=R(()=>{ZA=class extends Error{res;status;constructor($=500,w){super(w?.message,{cause:w?.cause});this.res=w?.res,this.status=$}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var EF=()=>{};var XF=($,w)=>{return new Response($,{headers:{"Content-Type":w}}).formData()};var GF=R(()=>{EF()});var LC,FC,jC,X9=($,w)=>{return async(E,X)=>{let G={},J=E.req.header("Content-Type");switch($){case"json":if(!J||!LC.test(J))break;try{G=await E.req.json()}catch{throw new ZA(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!J||!(FC.test(J)||jC.test(J)))break;let D;if(E.req.bodyCache.formData)D=await E.req.bodyCache.formData;else try{let W=await E.req.arrayBuffer();D=await XF(W,J),E.req.bodyCache.formData=D}catch(W){let O="Malformed FormData request.";throw O+=W instanceof Error?` ${W.message}`:` ${String(W)}`,new ZA(400,{message:O})}let N=Object.create(null);D.forEach((W,O)=>{if(O.endsWith("[]"))(N[O]??=[]).push(W);else if(Array.isArray(N[O]))N[O].push(W);else if(Object.hasOwn(N,O))N[O]=[N[O],W];else N[O]=W}),G=N;break}case"query":G=Object.fromEntries(Object.entries(E.req.queries()).map(([D,N])=>{return N.length===1?[D,N[0]]:[D,N]}));break;case"param":G=E.req.param();break;case"header":G=E.req.header();break;case"cookie":G=$F(E);break}let A=await w(G,E);if(A instanceof Response)return A;return E.req.addValidatedData($,A),await X()}};var JF=R(()=>{wF();E9();GF();LC=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,FC=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,jC=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var AF=R(()=>{JF()});function MC($,w,E,X){return X9($,async(G,J)=>{let A=G;if($==="header"&&"_def"in w||$==="header"&&"_zod"in w){let N=Object.keys("in"in w?w.in.shape:w.shape),W=Object.fromEntries(N.map((O)=>[O.toLowerCase(),O]));A=Object.fromEntries(Object.entries(G).map(([O,Y])=>[W[O]||O,Y]))}let D=X&&X.validationFunction?await X.validationFunction(w,A):await w.safeParseAsync(A);if(E){let N=await E({data:A,...D,target:$},J);if(N){if(N instanceof Response)return N;if("response"in N)return N.response}}if(!D.success)return J.json(D,400);return D.data})}var BE;var DF=R(()=>{AF();BE=MC});var G9=($,w,E)=>{return(X,G)=>{let J=-1;return A(0);async function A(D){if(D<=J)throw Error("next() called multiple times");J=D;let N,W=!1,O;if($[D])O=$[D][0][0],X.req.routeIndex=D;else O=D===$.length&&G||void 0;if(O)try{N=await O(X,()=>A(D+1))}catch(Y){if(Y instanceof Error&&w)X.error=Y,N=await w(Y,X),W=!0;else throw Y}else if(X.finalized===!1&&E)N=await E(X);if(N&&(X.finalized===!1||W))X.res=N;return X}}};var NF=()=>{};var WF;var OF=R(()=>{WF=Symbol()});async function RC($,w){let E=await $.formData();if(E)return zC(E,w);return{}}function zC($,w){let E=Object.create(null);if($.forEach((X,G)=>{if(!(w.all||G.endsWith("[]")))E[G]=X;else TC(E,G,X)}),w.dot)Object.entries(E).forEach(([X,G])=>{if(X.includes("."))BC(E,X,G),delete E[X]});return E}var UF=async($,w=Object.create(null))=>{let{all:E=!1,dot:X=!1}=w,J=($ instanceof CA?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return RC($,{all:E,dot:X});return{}},TC=($,w,E)=>{if($[w]!==void 0)if(Array.isArray($[w]))$[w].push(E);else $[w]=[$[w],E];else if(!w.endsWith("[]"))$[w]=E;else $[w]=[E]},BC=($,w,E)=>{if(/(?:^|\.)__proto__\./.test(w))return;let X=$,G=w.split(".");G.forEach((J,A)=>{if(A===G.length-1)X[J]=E;else{if(!X[J]||typeof X[J]!=="object"||Array.isArray(X[J])||X[J]instanceof File)X[J]=Object.create(null);X=X[J]}})};var YF=R(()=>{J9()});var HF=($)=>KX($,eG),CA;var J9=R(()=>{E9();OF();YF();pw();CA=class{raw;#$;#w;routeIndex=0;path;bodyCache={};constructor($,w="/",E=[[]]){this.raw=$,this.path=w,this.#w=E,this.#$={}}param($){return $?this.#E($):this.#J()}#E($){let w=this.#w[0][this.routeIndex][1][$],E=this.#G(w);return E&&/\%/.test(E)?HF(E):E}#J(){let $={},w=Object.keys(this.#w[0][this.routeIndex][1]);for(let E of w){let X=this.#G(this.#w[0][this.routeIndex][1][E]);if(X!==void 0)$[E]=/\%/.test(X)?HF(X):X}return $}#G($){return this.#w[1]?this.#w[1][$]:$}query($){return s3(this.url,$)}queries($){return a3(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let w={};return this.raw.headers.forEach((E,X)=>{w[X]=E}),w}async parseBody($){return this.bodyCache.parsedBody??=await UF(this,$)}#X=($)=>{let{bodyCache:w,raw:E}=this,X=w[$];if(X)return X;let G=Object.keys(w)[0];if(G)return w[G].then((J)=>{if(G==="json")J=JSON.stringify(J);return new Response(J)[$]()});return w[$]=E[$]()};json(){return this.#X("text").then(($)=>JSON.parse($))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData($,w){this.#$[$]=w}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[WF](){return this.#w}get matchedRoutes(){return this.#w[0].map(([[,$]])=>$)}get routePath(){return this.#w[0].map(([[,$]])=>$)[this.routeIndex].path}}});var QC="text/plain; charset=UTF-8",A9=($,w)=>{return{"Content-Type":$,...w}},$6=($,w)=>new Response($,w),LF=class{#$;#w;env={};#E;finalized=!1;error;#J;#G;#X;#O;#N;#W;#D;#U;#Y;constructor($,w){if(this.#$=$,w)this.#G=w.executionCtx,this.env=w.env,this.#W=w.notFoundHandler,this.#Y=w.path,this.#U=w.matchResult}get req(){return this.#w??=new CA(this.#$,this.#Y,this.#U),this.#w}get event(){if(this.#G&&"respondWith"in this.#G)return this.#G;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#G)return this.#G;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=$6(null,{headers:this.#D??=new Headers})}set res($){if(this.#X&&$){$=$6($.body,$);for(let[w,E]of this.#X.headers.entries()){if(w==="content-type")continue;if(w==="set-cookie"){let X=this.#X.headers.getSetCookie();$.headers.delete("set-cookie");for(let G of X)$.headers.append("set-cookie",G)}else $.headers.set(w,E)}}this.#X=$,this.finalized=!0}render=(...$)=>{return this.#N??=(w)=>this.html(w),this.#N(...$)};setLayout=($)=>this.#O=$;getLayout=()=>this.#O;setRenderer=($)=>{this.#N=$};header=($,w,E)=>{if(this.finalized)this.#X=$6(this.#X.body,this.#X);let X=this.#X?this.#X.headers:this.#D??=new Headers;if(w===void 0)X.delete($);else if(E?.append)X.append($,w);else X.set($,w)};status=($)=>{this.#J=$};set=($,w)=>{this.#E??=new Map,this.#E.set($,w)};get=($)=>{return this.#E?this.#E.get($):void 0};get var(){if(!this.#E)return{};return Object.fromEntries(this.#E)}#A($,w,E){let X=this.#X?new Headers(this.#X.headers):this.#D??new Headers;if(typeof w==="object"&&"headers"in w){let J=w.headers instanceof Headers?w.headers:new Headers(w.headers);for(let[A,D]of J)if(A.toLowerCase()==="set-cookie")X.append(A,D);else X.set(A,D)}if(E)for(let[J,A]of Object.entries(E))if(typeof A==="string")X.set(J,A);else{X.delete(J);for(let D of A)X.append(J,D)}let G=typeof w==="number"?w:w?.status??this.#J;return $6($,{status:G,headers:X})}newResponse=(...$)=>this.#A(...$);body=($,w,E)=>this.#A($,w,E);text=($,w,E)=>{return!this.#D&&!this.#J&&!w&&!E&&!this.finalized?new Response($):this.#A($,w,A9(QC,E))};json=($,w,E)=>{return this.#A(JSON.stringify($),w,A9("application/json",E))};html=($,w,E)=>{let X=(G)=>this.#A(G,w,A9("text/html; charset=UTF-8",E));return typeof $==="object"?rN($,mN.Stringify,!1,{}).then(X):X($)};redirect=($,w)=>{let E=String($);return this.header("Location",!/[^\x00-\xFF]/.test(E)?E:encodeURI(E)),this.newResponse(null,w??302)};notFound=()=>{return this.#W??=()=>$6(),this.#W(this)}};var FF=R(()=>{J9();pN()});var k0="ALL",jF="all",MF,_A="Can not add a route since the matcher is already built.",vA;var QE=R(()=>{MF=["get","post","put","delete","options","patch"],vA=class extends Error{}});var RF="__COMPOSED_HANDLER";var zF=()=>{};var IC=($)=>{return $.text("404 Not Found",404)},TF=($,w)=>{if("getResponse"in $){let E=$.getResponse();return w.newResponse(E.body,E)}return console.error($),w.text("Internal Server Error",500)},BF=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(w={}){[...MF,jF].forEach((J)=>{this[J]=(A,...D)=>{if(typeof A==="string")this.#$=A;else this.#J(J,this.#$,A);return D.forEach((N)=>{this.#J(J,this.#$,N)}),this}}),this.on=(J,A,...D)=>{for(let N of[A].flat()){this.#$=N;for(let W of[J].flat())D.map((O)=>{this.#J(W.toUpperCase(),this.#$,O)})}return this},this.use=(J,...A)=>{if(typeof J==="string")this.#$=J;else this.#$="*",A.unshift(J);return A.forEach((D)=>{this.#J(k0,this.#$,D)}),this};let{strict:X,...G}=w;Object.assign(this,G),this.getPath=X??!0?w.getPath??$9:d3}#w(){let w=new $({router:this.router,getPath:this.getPath});return w.errorHandler=this.errorHandler,w.#E=this.#E,w.routes=this.routes,w}#E=IC;errorHandler=TF;route(w,E){let X=this.basePath(w);return E.routes.map((G)=>{let J;if(E.errorHandler===TF)J=G.handler;else J=async(A,D)=>(await G9([],E.errorHandler)(A,()=>G.handler(A,D))).res,J[RF]=G.handler;X.#J(G.method,G.path,J)}),this}basePath(w){let E=this.#w();return E._basePath=f1(this._basePath,w),E}onError=(w)=>{return this.errorHandler=w,this};notFound=(w)=>{return this.#E=w,this};mount(w,E,X){let G,J;if(X)if(typeof X==="function")J=X;else if(J=X.optionHandler,X.replaceRequest===!1)G=(N)=>N;else G=X.replaceRequest;let A=J?(N)=>{let W=J(N);return Array.isArray(W)?W:[W]}:(N)=>{let W=void 0;try{W=N.executionCtx}catch{}return[N.env,W]};G||=(()=>{let N=f1(this._basePath,w),W=N==="/"?0:N.length;return(O)=>{let Y=new URL(O.url);return Y.pathname=Y.pathname.slice(W)||"/",new Request(Y,O)}})();let D=async(N,W)=>{let O=await E(G(N.req.raw),...A(N));if(O)return O;await W()};return this.#J(k0,f1(w,"*"),D),this}#J(w,E,X){w=w.toUpperCase(),E=f1(this._basePath,E);let G={basePath:this._basePath,path:E,method:w,handler:X};this.router.add(w,E,[X,G]),this.routes.push(G)}#G(w,E){if(w instanceof Error)return this.errorHandler(w,E);throw w}#X(w,E,X,G){if(G==="HEAD")return(async()=>new Response(null,await this.#X(w,E,X,"GET")))();let J=this.getPath(w,{env:X}),A=this.router.match(G,J),D=new LF(w,{path:J,matchResult:A,env:X,executionCtx:E,notFoundHandler:this.#E});if(A[0].length===1){let W;try{W=A[0][0][0][0](D,async()=>{D.res=await this.#E(D)})}catch(O){return this.#G(O,D)}return W instanceof Promise?W.then((O)=>O||(D.finalized?D.res:this.#E(D))).catch((O)=>this.#G(O,D)):W??this.#E(D)}let N=G9(A[0],this.errorHandler,this.#E);return(async()=>{try{let W=await N(D);if(!W.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return W.res}catch(W){return this.#G(W,D)}})()}fetch=(w,...E)=>{return this.#X(w,E[1],E[0],w.method)};request=(w,E,X,G)=>{if(w instanceof Request)return this.fetch(E?new Request(w,E):w,X,G);return w=w.toString(),this.fetch(new Request(/^https?:\/\//.test(w)?w:`http://localhost${f1("/",w)}`,E),X,G)};fire=()=>{addEventListener("fetch",(w)=>{w.respondWith(this.#X(w.request,w,void 0,w.request.method))})}};var QF=R(()=>{NF();FF();QE();zF();pw()});function fA($,w){let E=this.buildAllMatchers(),X=(G,J)=>{let A=E[G]||E[k0],D=A[2][J];if(D)return D;let N=J.match(A[0]);if(!N)return[[],w6];let W=N.indexOf("",1);return[A[1][W],N]};return this.match=X,X($,w)}var w6;var D9=R(()=>{QE();w6=[]});function VC($,w){if($.length===1)return w.length===1?$<w?-1:1:-1;if(w.length===1)return 1;if($===E6||$===X6)return 1;else if(w===E6||w===X6)return-1;if($===xA)return 1;else if(w===xA)return-1;return $.length===w.length?$<w?-1:1:w.length-$.length}var xA="[^/]+",E6=".*",X6="(?:|/.*)",IE,KC,IF=class ${#$;#w;#E=Object.create(null);insert(w,E,X,G,J){if(w.length===0){if(this.#$!==void 0)throw IE;if(J)return;this.#$=E;return}let[A,...D]=w,N=A==="*"?D.length===0?["","",E6]:["","",xA]:A==="/*"?["","",X6]:A.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),W;if(N){let O=N[1],Y=N[2]||xA;if(O&&N[2]){if(Y===".*")throw IE;if(Y=Y.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(Y))throw IE}if(W=this.#E[Y],!W){if(Object.keys(this.#E).some((H)=>H!==E6&&H!==X6))throw IE;if(J)return;if(W=this.#E[Y]=new $,O!=="")W.#w=G.varIndex++}if(!J&&O!=="")X.push([O,W.#w])}else if(W=this.#E[A],!W){if(Object.keys(this.#E).some((O)=>O.length>1&&O!==E6&&O!==X6))throw IE;if(J)return;W=this.#E[A]=new $}W.insert(D,E,X,G,J)}buildRegExpStr(){let E=Object.keys(this.#E).sort(VC).map((X)=>{let G=this.#E[X];return(typeof G.#w==="number"?`(${X})@${G.#w}`:KC.has(X)?`\\${X}`:X)+G.buildRegExpStr()});if(typeof this.#$==="number")E.unshift(`#${this.#$}`);if(E.length===0)return"";if(E.length===1)return E[0];return"(?:"+E.join("|")+")"}};var N9=R(()=>{IE=Symbol(),KC=new Set(".\\+*[^]$()")});var KF=class{#$={varIndex:0};#w=new IF;insert($,w,E){let X=[],G=[];for(let A=0;;){let D=!1;if($=$.replace(/\{[^}]+\}/g,(N)=>{let W=`@\\${A}`;return G[A]=[W,N],A++,D=!0,W}),!D)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let A=G.length-1;A>=0;A--){let[D]=G[A];for(let N=J.length-1;N>=0;N--)if(J[N].indexOf(D)!==-1){J[N]=J[N].replace(D,G[A][1]);break}}return this.#w.insert(J,w,X,this.#$,E),X}buildRegExp(){let $=this.#w.buildRegExpStr();if($==="")return[/^$/,[],[]];let w=0,E=[],X=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,J,A)=>{if(J!==void 0)return E[++w]=Number(J),"$()";if(A!==void 0)return X[Number(A)]=++w,"";return""}),[new RegExp(`^${$}`),E,X]}};var VF=R(()=>{N9()});function qF($){return PF[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(w,E)=>E?`\\${E}`:"(?:|/.*)")}$`)}function qC(){PF=Object.create(null)}function SC($){let w=new KF,E=[];if($.length===0)return PC;let X=$.map((W)=>[!/\*|\/:/.test(W[0]),...W]).sort(([W,O],[Y,H])=>W?1:Y?-1:O.length-H.length),G=Object.create(null);for(let W=0,O=-1,Y=X.length;W<Y;W++){let[H,L,F]=X[W];if(H)G[L]=[F.map(([M])=>[M,Object.create(null)]),w6];else O++;let j;try{j=w.insert(L,O,H)}catch(M){throw M===IE?new vA(L):M}if(H)continue;E[O]=F.map(([M,z])=>{let B=Object.create(null);z-=1;for(;z>=0;z--){let[Q,k]=j[z];B[Q]=k}return[M,B]})}let[J,A,D]=w.buildRegExp();for(let W=0,O=E.length;W<O;W++)for(let Y=0,H=E[W].length;Y<H;Y++){let L=E[W][Y]?.[1];if(!L)continue;let F=Object.keys(L);for(let j=0,M=F.length;j<M;j++)L[F[j]]=D[L[F[j]]]}let N=[];for(let W in A)N[W]=E[A[W]];return[J,N,G]}function VX($,w){if(!$)return;for(let E of Object.keys($).sort((X,G)=>G.length-X.length))if(qF(E).test(w))return[...$[E]];return}var PC,PF,yA=class{name="RegExpRouter";#$;#w;constructor(){this.#$={[k0]:Object.create(null)},this.#w={[k0]:Object.create(null)}}add($,w,E){let X=this.#$,G=this.#w;if(!X||!G)throw Error(_A);if(!X[$])[X,G].forEach((D)=>{D[$]=Object.create(null),Object.keys(D[k0]).forEach((N)=>{D[$][N]=[...D[k0][N]]})});if(w==="/*")w="*";let J=(w.match(/\/:/g)||[]).length;if(/\*$/.test(w)){let D=qF(w);if($===k0)Object.keys(X).forEach((N)=>{X[N][w]||=VX(X[N],w)||VX(X[k0],w)||[]});else X[$][w]||=VX(X[$],w)||VX(X[k0],w)||[];Object.keys(X).forEach((N)=>{if($===k0||$===N)Object.keys(X[N]).forEach((W)=>{D.test(W)&&X[N][W].push([E,J])})}),Object.keys(G).forEach((N)=>{if($===k0||$===N)Object.keys(G[N]).forEach((W)=>D.test(W)&&G[N][W].push([E,J]))});return}let A=bA(w)||[w];for(let D=0,N=A.length;D<N;D++){let W=A[D];Object.keys(G).forEach((O)=>{if($===k0||$===O)G[O][W]||=[...VX(X[O],W)||VX(X[k0],W)||[]],G[O][W].push([E,J-N+D+1])})}}match=fA;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#w).concat(Object.keys(this.#$)).forEach((w)=>{$[w]||=this.#E(w)}),this.#$=this.#w=void 0,qC(),$}#E($){let w=[],E=$===k0;if([this.#$,this.#w].forEach((X)=>{let G=X[$]?Object.keys(X[$]).map((J)=>[J,X[$][J]]):[];if(G.length!==0)E||=!0,w.push(...G);else if($!==k0)w.push(...Object.keys(X[k0]).map((J)=>[J,X[k0][J]]))}),!E)return null;else return SC(w)}};var W9=R(()=>{QE();pw();D9();N9();VF();PC=[/^$/,[],Object.create(null)],PF=Object.create(null)});var kC=class{name="PreparedRegExpRouter";#$;#w;constructor($,w){this.#$=$,this.#w=w}#E($,w){let E=this.#$[$];E[1].forEach((X)=>X&&X.push(w)),Object.values(E[2]).forEach((X)=>X[0].push(w))}#J($,w,E,X,G){let J=this.#$[$];if(!G)J[2][w][0].push([E,{}]);else X.forEach((A)=>{if(typeof A==="number")J[1][A].push([E,G]);else J[2][A||w][0].push([E,G])})}add($,w,E){if(!this.#$[$]){let G=this.#$[k0],J={};for(let A in G[2])J[A]=[G[2][A][0].slice(),w6];this.#$[$]=[G[0],G[1].map((A)=>Array.isArray(A)?A.slice():0),J]}if(w==="/*"||w==="*"){let G=[E,{}];if($===k0)for(let J in this.#$)this.#E(J,G);else this.#E($,G);return}let X=this.#w[w];if(!X)throw Error(`Path ${w} is not registered`);for(let[G,J]of X)if($===k0)for(let A in this.#$)this.#J(A,w,E,G,J);else this.#J($,w,E,G,J)}buildAllMatchers(){return this.#$}match=fA};var SF=R(()=>{QE();D9();W9()});var kF=R(()=>{W9();SF()});var O9=class{name="SmartRouter";#$=[];#w=[];constructor($){this.#$=$.routers}add($,w,E){if(!this.#w)throw Error(_A);this.#w.push([$,w,E])}match($,w){if(!this.#w)throw Error("Fatal error");let E=this.#$,X=this.#w,G=E.length,J=0,A;for(;J<G;J++){let D=E[J];try{for(let N=0,W=X.length;N<W;N++)D.add(...X[N]);A=D.match($,w)}catch(N){if(N instanceof vA)continue;throw N}this.match=D.match.bind(D),this.#$=[D],this.#w=void 0;break}if(J===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,A}get activeRouter(){if(this.#w||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var bF=R(()=>{QE()});var ZF=R(()=>{bF()});var G6,bC=($)=>{for(let w in $)return!0;return!1},CF=class ${#$;#w;#E;#J=0;#G=G6;constructor(w,E,X){if(this.#w=X||Object.create(null),this.#$=[],w&&E){let G=Object.create(null);G[w]={handler:E,possibleKeys:[],score:0},this.#$=[G]}this.#E=[]}insert(w,E,X){this.#J=++this.#J;let G=this,J=t3(E),A=[];for(let D=0,N=J.length;D<N;D++){let W=J[D],O=J[D+1],Y=i3(W,O),H=Array.isArray(Y)?Y[0]:W;if(H in G.#w){if(G=G.#w[H],Y)A.push(Y[1]);continue}if(G.#w[H]=new $,Y)G.#E.push(Y),A.push(Y[1]);G=G.#w[H]}return G.#$.push({[w]:{handler:X,possibleKeys:A.filter((D,N,W)=>W.indexOf(D)===N),score:this.#J}}),G}#X(w,E,X,G,J){for(let A=0,D=E.#$.length;A<D;A++){let N=E.#$[A],W=N[X]||N[k0],O={};if(W!==void 0){if(W.params=Object.create(null),w.push(W),G!==G6||J&&J!==G6)for(let Y=0,H=W.possibleKeys.length;Y<H;Y++){let L=W.possibleKeys[Y],F=O[W.score];W.params[L]=J?.[L]&&!F?J[L]:G[L]??J?.[L],O[W.score]=!0}}}}search(w,E){let X=[];this.#G=G6;let J=[this],A=eN(E),D=[],N=A.length,W=null;for(let O=0;O<N;O++){let Y=A[O],H=O===N-1,L=[];for(let j=0,M=J.length;j<M;j++){let z=J[j],B=z.#w[Y];if(B)if(B.#G=z.#G,H){if(B.#w["*"])this.#X(X,B.#w["*"],w,z.#G);this.#X(X,B,w,z.#G)}else L.push(B);for(let Q=0,k=z.#E.length;Q<k;Q++){let v=z.#E[Q],C=z.#G===G6?{}:{...z.#G};if(v==="*"){let d0=z.#w["*"];if(d0)this.#X(X,d0,w,z.#G),d0.#G=C,L.push(d0);continue}let[n,T0,f0]=v;if(!Y&&!(f0 instanceof RegExp))continue;let c0=z.#w[n];if(f0 instanceof RegExp){if(W===null){W=Array(N);let U$=E[0]==="/"?1:0;for(let O1=0;O1<N;O1++)W[O1]=U$,U$+=A[O1].length+1}let d0=E.substring(W[O]),K0=f0.exec(d0);if(K0){if(C[T0]=K0[0],this.#X(X,c0,w,z.#G,C),bC(c0.#w)){c0.#G=C;let U$=K0[0].match(/\//)?.length??0;(D[U$]||=[]).push(c0)}continue}}if(f0===!0||f0.test(Y))if(C[T0]=Y,H){if(this.#X(X,c0,w,C,z.#G),c0.#w["*"])this.#X(X,c0.#w["*"],w,C,z.#G)}else c0.#G=C,L.push(c0)}}let F=D.shift();J=F?L.concat(F):L}if(X.length>1)X.sort((O,Y)=>{return O.score-Y.score});return[X.map(({handler:O,params:Y})=>[O,Y])]}};var _F=R(()=>{QE();pw();G6=Object.create(null)});var U9=class{name="TrieRouter";#$;constructor(){this.#$=new CF}add($,w,E){let X=bA(w);if(X){for(let G=0,J=X.length;G<J;G++)this.#$.insert($,X[G],E);return}this.#$.insert($,w,E)}match($,w){return this.#$.search($,w)}};var vF=R(()=>{pw();_F()});var fF=R(()=>{vF()});var Y9;var xF=R(()=>{QF();kF();ZF();fF();Y9=class extends BF{constructor($={}){super($);this.router=$.router??new O9({routers:[new yA,new U9]})}}});var yF=R(()=>{xF()});function gF($,w){let E={};return Object.keys($.paths).forEach((X)=>{E[f1(w.replaceAll(/:([^\/]+)/g,"{$1}"),X)]=$.paths[X]}),{...$,paths:E}}function uF($){return/^application\/([a-z-\.]+\+)?json/.test($)}function hF($){return $.startsWith("multipart/form-data")||$.startsWith("application/x-www-form-urlencoded")}var p0,m=($)=>{let w={...$,getRoutingPath(){return $.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(w,"getRoutingPath",{enumerable:!1})};var N1=R(()=>{o3();DF();yF();pw();OG();p0=class $ extends Y9{openAPIRegistry;defaultHook;constructor(w){super(w);this.openAPIRegistry=new iN,this.defaultHook=w?.defaultHook}openapi=({middleware:w,hide:E,...X},G,J=this.defaultHook)=>{if(!E)this.openAPIRegistry.registerPath(X);let A=[];if(X.request?.query){let W=BE("query",X.request.query,J);A.push(W)}if(X.request?.params){let W=BE("param",X.request.params,J);A.push(W)}if(X.request?.headers){let W=BE("header",X.request.headers,J);A.push(W)}if(X.request?.cookies){let W=BE("cookie",X.request.cookies,J);A.push(W)}let D=X.request?.body?.content;if(D)for(let W of Object.keys(D)){if(!D[W])continue;let O=D[W].schema;if(!(O instanceof G0))continue;if(uF(W)){let Y=BE("json",O,J);if(X.request?.body?.required)A.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(uF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("json",{}),await F()};A.push(H)}}if(hF(W)){let Y=BE("form",O,J);if(X.request?.body?.required)A.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(hF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("form",{}),await F()};A.push(H)}}}let N=w?Array.isArray(w)?w:[w]:[];return this.on([X.method],X.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...N,...A,G),this};getOpenAPIDocument=(w)=>{let X=new lN(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?gF(X,this._basePath):X};getOpenAPI31Document=(w)=>{let X=new sN(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?gF(X,this._basePath):X};doc=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let J=this.getOpenAPIDocument(G);return X.json(J)}catch(J){return X.json(J,500)}})};doc31=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let J=this.getOpenAPI31Document(G);return X.json(J)}catch(J){return X.json(J,500)}})};route(w,E){let X=w.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(w,E),!(E instanceof $))return this;return E.openAPIRegistry.definitions.forEach((G)=>{switch(G.type){case"component":return this.openAPIRegistry.registerComponent(G.componentType,G.name,G.component);case"route":{this.openAPIRegistry.registerPath({...G.route,path:f1(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...G.webhook,path:f1(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.webhook.path)});return}case"schema":return this.openAPIRegistry.register(G.schema._def.openapi._internal.refId,G.schema);case"parameter":return this.openAPIRegistry.registerParameter(G.schema._def.openapi._internal.refId,G.schema);default:throw Error(`Unknown registry type: ${G}`)}}),this}basePath(w){return new $({...super.basePath(w),defaultHook:this.defaultHook})}};P3(U)});var PX,U0,Ew,H9;var x1=R(()=>{PX=class PX extends Error{code;statusCode;constructor($,w,E=500){super($);this.code=w;this.statusCode=E;this.name="OrcError"}};U0=class U0 extends PX{constructor($,w){super(`${$} not found: ${w}`,"NOT_FOUND",404);this.name="NotFoundError"}};Ew=class Ew extends PX{constructor($){super($,"VALIDATION_ERROR",400);this.name="ValidationError"}};H9=class H9 extends PX{constructor($="Unauthorized"){super($,"UNAUTHORIZED",401);this.name="UnauthorizedError"}}});function cF($){return async(w,E)=>{if(!$)return E();let X=w.req.header("Authorization");if(!X?.startsWith("Bearer ")||X.slice(7)!==$)throw new H9;return E()}}var nF=R(()=>{x1()});var gA,ZC,CC,_C,vC;var mF=R(()=>{N1();bN();gA=new p0,ZC=U.object({running:U.boolean(),status:U.string()}).openapi("GatewayStatus"),CC=U.object({platform:U.string(),chat_id:U.string(),text:U.string(),thread_id:U.string().optional()}).openapi("GatewaySend"),_C=m({method:"get",path:"/gateway/status",tags:["Gateway"],summary:"Get gateway status",responses:{200:{content:{"application/json":{schema:ZC}},description:"Gateway status"}}}),vC=m({method:"post",path:"/gateway/send",tags:["Gateway"],summary:"Send a message via the gateway",request:{body:{content:{"application/json":{schema:CC}}}},responses:{204:{description:"Message sent"},503:{content:{"application/json":{schema:U.object({error:U.string()})}},description:"Gateway not running"}}});gA.openapi(_C,async($)=>{let w=zA()!==null;return $.json({running:w,status:kN()})});gA.openapi(vC,async($)=>{if(!zA())return $.json({error:"Gateway is not running"},503);let{platform:w,chat_id:E,text:X,thread_id:G}=$.req.valid("json");return await SN(w,E,X,G?{threadId:G}:void 0),$.body(null,204)})});var L9,fC,xC;var rF=R(()=>{FJ();N1();L9=new p0,fC=m({method:"get",path:"/health",tags:["System"],summary:"Health check",responses:{200:{description:"Service is healthy",content:{"application/json":{schema:U.object({status:U.literal("ok"),version:U.string(),uptime:U.number()})}}}}}),xC=Date.now();L9.openapi(fC,($)=>{return $.json({status:"ok",version:lE,uptime:Math.floor((Date.now()-xC)/1000)})})});var uA,J6,hA,pF,cA,_w0,vw0,fw0,F9,xw0,yw0,gw0;var nA=R(()=>{OG();uA=U.enum(["todo","doing","review","changes_requested","blocked","done","cancelled"]),J6=U.enum(["low","normal","high","critical"]),hA=U.enum(["one-shot","cron","watch","webhook","manual","bridge-msg"]),pF=U.enum(["pending","running","success","failed","cancelled","skipped"]),cA=U.enum(["skip","queue","kill"]),_w0=U.enum(["low","normal","high","critical"]),vw0=U.enum(["telegram","slack","discord","feishu"]),fw0=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")),F9=U.enum(["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]),xw0=U.enum(["active","archived","paused"]),yw0=U.enum(["solo","pair","parallel","handoff"]),gw0=U.enum(["solo","human_agent","multi_agent"])});function rA($){return{...$,project_id:$.project_id??null,last_run_at:$.last_run_at?.toISOString()??null,next_run_at:$.next_run_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function lC($){return{...$,started_at:$.started_at?.toISOString()??null,ended_at:$.ended_at?.toISOString()??null,created_at:$.created_at.toISOString()}}var yC,Xw,mA,gC,uC,hC,cC,nC,mC,rC,pC,oC,tC,iC,dC;var oF=R(()=>{N1();x1();X1();p$();nA();y$();d$();nw();i$();yC=Z0("api:jobs"),Xw=new p0,mA=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),command:U.string(),trigger_type:hA,cron_expr:U.string().nullable(),enabled:U.boolean(),timeout_secs:U.number(),max_retries:U.number(),overlap:cA,notify_on:U.enum(["never","failure","always"]),project_id:U.string().nullable(),run_count:U.number(),last_run_at:U.string().datetime().nullable(),next_run_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Job"),gC=U.object({name:U.string().min(1).max(100),description:U.string().optional(),command:U.string().min(1),trigger_type:hA,cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional().default(300),max_retries:U.number().int().min(0).optional().default(0),overlap:cA.optional().default("skip"),notify_on:U.enum(["never","failure","always"]).optional().default("failure"),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("CreateJob"),uC=U.object({id:U.string(),job_id:U.string(),status:pF,trigger_by:U.string().nullable(),started_at:U.string().datetime().nullable(),ended_at:U.string().datetime().nullable(),exit_code:U.number().nullable(),error_msg:U.string().nullable(),retry_num:U.number(),created_at:U.string().datetime()}).openapi("JobRun"),hC=U.object({id:U.number(),run_id:U.string(),ts:U.string().datetime(),stream:U.enum(["stdout","stderr"]),line:U.string()}).openapi("JobRunLog"),cC=m({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:U.object({enabled:U.coerce.boolean().optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Jobs",content:{"application/json":{schema:U.object({jobs:U.array(mA)})}}}}}),nC=m({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get job",request:{params:U.object({id:U.string()})},responses:{200:{description:"Job",content:{"application/json":{schema:mA}}}}}),mC=m({method:"post",path:"/jobs",tags:["Jobs"],summary:"Create job",request:{body:{content:{"application/json":{schema:gC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:mA}}}}}),rC=U.object({name:U.string().min(1).max(100).optional(),description:U.string().optional(),command:U.string().min(1).optional(),trigger_type:hA.optional(),cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional(),max_retries:U.number().int().min(0).optional(),overlap:cA.optional(),notify_on:U.enum(["never","failure","always"]).optional(),enabled:U.boolean().optional(),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("UpdateJob"),pC=m({method:"patch",path:"/jobs/{id}",tags:["Jobs"],summary:"Update job",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:rC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:mA}}}}}),oC=m({method:"delete",path:"/jobs/{id}",tags:["Jobs"],summary:"Delete job",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),tC=m({method:"post",path:"/jobs/{id}/trigger",tags:["Jobs"],summary:"Manually trigger a job",request:{params:U.object({id:U.string()})},responses:{202:{description:"Triggered",content:{"application/json":{schema:U.object({run_id:U.string()})}}}}}),iC=m({method:"get",path:"/jobs/{id}/runs",tags:["Jobs"],summary:"List job runs",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(50).optional().default(20)})},responses:{200:{description:"Runs",content:{"application/json":{schema:U.object({runs:U.array(uC)})}}}}}),dC=m({method:"get",path:"/jobs/{id}/runs/{runId}/logs",tags:["Jobs"],summary:"Stream log lines for a specific run",request:{params:U.object({id:U.string(),runId:U.string()}),query:U.object({stream:U.enum(["stdout","stderr"]).optional(),limit:U.coerce.number().int().min(1).max(5000).optional().default(500)})},responses:{200:{description:"Log lines",content:{"application/json":{schema:U.object({logs:U.array(hC)})}}}}});Xw.openapi(cC,async($)=>{let w=x(),{limit:E,project_id:X}=$.req.valid("query"),G=[];if(X)G.push(V(I0.project_id,X));let J=await w.query.jobs.findMany({where:G.length?S0(...G):void 0,limit:E,orderBy:(A,{asc:D})=>[D(A.name)]});return $.json({jobs:J.map(rA)})});Xw.openapi(nC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!X)throw new U0("Job",E);return $.json(rA(X))});Xw.openapi(mC,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(I0).values({id:G,name:E.name,description:E.description,command:E.command,trigger_type:E.trigger_type,cron_expr:E.cron_expr,watch_path:E.watch_path,timeout_secs:E.timeout_secs,max_retries:E.max_retries,overlap:E.overlap,notify_on:E.notify_on,env_vars:E.env_vars,working_dir:E.working_dir,project_id:E.project_id,created_at:X,updated_at:X});let J=await w.query.jobs.findFirst({where:V(I0.id,G)});if(!J)throw Error("Expected job to exist after write");return $.json(rA(J),201)});Xw.openapi(pC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);await w.update(I0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.command!==void 0?{command:X.command}:{},...X.trigger_type!==void 0?{trigger_type:X.trigger_type}:{},...X.cron_expr!==void 0?{cron_expr:X.cron_expr}:{},...X.watch_path!==void 0?{watch_path:X.watch_path}:{},...X.timeout_secs!==void 0?{timeout_secs:X.timeout_secs}:{},...X.max_retries!==void 0?{max_retries:X.max_retries}:{},...X.overlap!==void 0?{overlap:X.overlap}:{},...X.notify_on!==void 0?{notify_on:X.notify_on}:{},...X.enabled!==void 0?{enabled:X.enabled}:{},...X.env_vars!==void 0?{env_vars:X.env_vars}:{},...X.working_dir!==void 0?{working_dir:X.working_dir}:{},...X.project_id!==void 0?{project_id:X.project_id}:{},updated_at:new Date}).where(V(I0.id,E));let J=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!J)throw Error("Expected job to exist after write");return $.json(rA(J))});Xw.openapi(oC,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);return await w.delete(I0).where(V(I0.id,E)),new Response(null,{status:204})});Xw.openapi(tC,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);let G=i();return await w.insert(E$).values({id:G,job_id:E,status:"pending",trigger_by:"api",created_at:new Date}),A1({jobId:E,runId:G,triggerBy:"api"}).catch((J)=>yC.error(`Background execution failed for run ${G}: ${J instanceof Error?J.message:String(J)}`)),$.json({run_id:G},202)});Xw.openapi(iC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query"),G=await w.query.job_runs.findMany({where:V(E$.job_id,E),limit:X,orderBy:[x0(E$.created_at)]});return $.json({runs:G.map(lC)})});Xw.openapi(dC,async($)=>{let w=x(),{id:E,runId:X}=$.req.valid("param"),{stream:G,limit:J}=$.req.valid("query"),A=await w.query.job_runs.findFirst({where:V(E$.id,X)});if(!A||A.job_id!==E)throw new U0("JobRun",X);let D=await w.query.job_run_logs.findMany({where:G?S0(V(cw.run_id,X),V(cw.stream,G)):V(cw.run_id,X),limit:J,orderBy:[qJ(cw.ts)]});return $.json({logs:D.map((N)=>({...N,ts:N.ts.toISOString()}))})})});function sC($,w=80){return $.length<=w?$:`${$.slice(0,w-1)}\u2026`}function aC($){let w=Date.now()-$*1000,E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function eC($,w,E){return{id:$.id,snippet:sC($.content),scope:$.scope,type:$.type??"fact",importance:$.importance,age:aC($.created_at),rank:w,matchLayer:E}}function iF(){return x().$client}function dF($,w,E){let X=[],G=[];if($)X.push("m.scope = ?"),G.push($);if(w)X.push("m.type = ?"),G.push(w);if(E)X.push("m.project_id = ?"),G.push(E);return{clause:X.length?` AND ${X.join(" AND ")}`:"",params:G}}function pA($,w,E,X,G,J,A){let{clause:D,params:N}=dF(X,G,A),W=`SELECT ${M9}
459
+ `)};var C3=T(()=>{b3();N0={STRING_ARRAY:"string_array",STRING:"string",JSON_STRING:"json_string",RAW:"raw"},_3={configUrl:N0.STRING,deepLinking:N0.RAW,presets:N0.STRING_ARRAY,plugins:N0.STRING_ARRAY,spec:N0.JSON_STRING,url:N0.STRING,urls:N0.JSON_STRING,layout:N0.STRING,docExpansion:N0.STRING,maxDisplayedTags:N0.RAW,operationsSorter:N0.RAW,requestInterceptor:N0.RAW,responseInterceptor:N0.RAW,persistAuthorization:N0.RAW,defaultModelsExpandDepth:N0.RAW,defaultModelExpandDepth:N0.RAW,defaultModelRendering:N0.STRING,displayRequestDuration:N0.RAW,filter:N0.RAW,showExtensions:N0.RAW,showCommonExtensions:N0.RAW,queryConfigEnabled:N0.RAW,displayOperationId:N0.RAW,tagsSorter:N0.RAW,onComplete:N0.RAW,syntaxHighlight:N0.JSON_STRING,tryItOutEnabled:N0.RAW,requestSnippetsEnabled:N0.RAW,requestSnippets:N0.JSON_STRING,oauth2RedirectUrl:N0.STRING,showMutabledRequest:N0.RAW,request:N0.JSON_STRING,supportedSubmitMethods:N0.JSON_STRING,validatorUrl:N0.STRING,withCredentials:N0.RAW,modelPropertyMacro:N0.RAW,parameterMacro:N0.RAW}});function wA($,w){var E={};for(var X in $)if(Object.prototype.hasOwnProperty.call($,X)&&w.indexOf(X)<0)E[X]=$[X];if($!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var G=0,X=Object.getOwnPropertySymbols($);G<X.length;G++)if(w.indexOf(X[G])<0&&Object.prototype.propertyIsEnumerable.call($,X[G]))E[X[G]]=$[X[G]]}return E}function W0($,w){var E;return((E=$===null||$===void 0?void 0:$._def)===null||E===void 0?void 0:E.typeName)===w}function YZ($){return"_def"in $}function eG($,w){let E=$.ZodType.prototype[w];$.ZodType.prototype[w]=function(...X){let G=E.apply(this,X);return G._def.openapi=this._def.openapi,G}}function v3($){if(typeof $.ZodType.prototype.openapi<"u")return;$.ZodType.prototype.openapi=function(G,A){var N,D,O,W,J,Y;let H=typeof G==="string"?A:G,L=H!==null&&H!==void 0?H:{},{param:F}=L,j=wA(L,["param"]),M=Object.assign(Object.assign({},(N=this._def.openapi)===null||N===void 0?void 0:N._internal),typeof G==="string"?{refId:G}:void 0),R=Object.assign(Object.assign(Object.assign({},(D=this._def.openapi)===null||D===void 0?void 0:D.metadata),j),((W=(O=this._def.openapi)===null||O===void 0?void 0:O.metadata)===null||W===void 0?void 0:W.param)||F?{param:Object.assign(Object.assign({},(Y=(J=this._def.openapi)===null||J===void 0?void 0:J.metadata)===null||Y===void 0?void 0:Y.param),F)}:void 0),B=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(M).length>0?{_internal:M}:void 0),Object.keys(R).length>0?{metadata:R}:void 0)}));if(W0(this,"ZodObject")){let I=this.extend;B.extend=function(...C){var v,k,n,H0,b0,c0,l0;let V0=I.apply(this,C);return V0._def.openapi={_internal:{extendedFrom:((k=(v=this._def.openapi)===null||v===void 0?void 0:v._internal)===null||k===void 0?void 0:k.refId)?{refId:(H0=(n=this._def.openapi)===null||n===void 0?void 0:n._internal)===null||H0===void 0?void 0:H0.refId,schema:this}:(c0=(b0=this._def.openapi)===null||b0===void 0?void 0:b0._internal)===null||c0===void 0?void 0:c0.extendedFrom},metadata:(l0=V0._def.openapi)===null||l0===void 0?void 0:l0.metadata},V0}}return B},eG($,"optional"),eG($,"nullable"),eG($,"default"),eG($,"transform"),eG($,"refine");let w=$.ZodObject.prototype.deepPartial;$.ZodObject.prototype.deepPartial=function(){let G=this._def.shape(),A=w.apply(this),N=A._def.shape();return Object.entries(N).forEach(([D,O])=>{var W,J;O._def.openapi=(J=(W=G[D])===null||W===void 0?void 0:W._def)===null||J===void 0?void 0:J.openapi}),A._def.openapi=void 0,A};let E=$.ZodObject.prototype.pick;$.ZodObject.prototype.pick=function(...G){let A=E.apply(this,G);return A._def.openapi=void 0,A};let X=$.ZodObject.prototype.omit;$.ZodObject.prototype.omit=function(...G){let A=X.apply(this,G);return A._def.openapi=void 0,A}}function fD($,w){if($===null||$===void 0||w===null||w===void 0)return $===w;if($===w||$.valueOf()===w.valueOf())return!0;if(Array.isArray($)){if(!Array.isArray(w))return!1;if($.length!==w.length)return!1}if(!($ instanceof Object)||!(w instanceof Object))return!1;let E=Object.keys($);return Object.keys(w).every((X)=>E.indexOf(X)!==-1)&&E.every((X)=>fD($[X],w[X]))}class x3{constructor(){this.buckets=new Map}put($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E){this.buckets.set(w,[$]);return}if(!E.some((G)=>fD(G,$)))E.push($)}contains($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E)return!1;return E.some((X)=>fD(X,$))}values(){return[...this.buckets.values()].flat()}stats(){let $=0,w=0,E=0;for(let G of this.buckets.values())if($+=1,w+=G.length,G.length>1)E+=1;let X=$/w;return{totalBuckets:$,collisions:E,totalValues:w,hashEffectiveness:X}}hashCodeOf($){let w=0;if(Array.isArray($)){for(let E=0;E<$.length;E++)w^=this.hashCodeOf($[E])*E;return w}if(typeof $==="string"){for(let E=0;E<$.length;E++)w^=$.charCodeAt(E)*E;return w}if(typeof $==="number")return $;if(typeof $==="object")for(let[E,X]of Object.entries($))w^=this.hashCodeOf(E)+this.hashCodeOf(X!==null&&X!==void 0?X:"");return w}}function EA($){return $===void 0}function XA($,w){let E={};return Object.entries($).forEach(([X,G])=>{E[X]=w(G)}),E}function HZ($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w.some((A)=>A===X))E[X]=G}),E}function qX($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w(G,X))E[X]=G}),E}function f3($){return $.filter((w)=>!EA(w))}function LZ($){let w=new x3;return $.forEach((E)=>w.put(E)),[...w.values()]}function y3($){return typeof $==="string"}class X4{constructor($){this.parents=$,this._definitions=[]}get definitions(){var $,w;return[...(w=($=this.parents)===null||$===void 0?void 0:$.flatMap((X)=>X.definitions))!==null&&w!==void 0?w:[],...this._definitions]}register($,w){let E=this.schemaWithRefId($,w);return this._definitions.push({type:"schema",schema:E}),E}registerParameter($,w){var E,X,G;let A=this.schemaWithRefId($,w),N=(E=A._def.openapi)===null||E===void 0?void 0:E.metadata,D=A.openapi(Object.assign(Object.assign({},N),{param:Object.assign(Object.assign({},N===null||N===void 0?void 0:N.param),{name:(G=(X=N===null||N===void 0?void 0:N.param)===null||X===void 0?void 0:X.name)!==null&&G!==void 0?G:$})}));return this._definitions.push({type:"parameter",schema:D}),D}registerPath($){this._definitions.push({type:"route",route:$})}registerWebhook($){this._definitions.push({type:"webhook",webhook:$})}registerComponent($,w,E){return this._definitions.push({type:"component",componentType:$,name:w,component:E}),{name:w,ref:{$ref:`#/components/${$}/${w}`}}}schemaWithRefId($,w){return w.openapi($)}}class AA{constructor($){this.message=$}}function $A($,w){try{return $()}catch(E){if(E instanceof GA)throw new GA(Object.assign(Object.assign({},E.data),w));throw E}}class u0{static getMetadata($){var w;let E=this.unwrapChained($),X=$._def.openapi?$._def.openapi:E._def.openapi,G=(w=$.description)!==null&&w!==void 0?w:E.description;return{_internal:X===null||X===void 0?void 0:X._internal,metadata:Object.assign({description:G},X===null||X===void 0?void 0:X.metadata)}}static getInternalMetadata($){let w=this.unwrapChained($),E=$._def.openapi?$._def.openapi:w._def.openapi;return E===null||E===void 0?void 0:E._internal}static getParamMetadata($){var w,E;let X=this.unwrapChained($),G=$._def.openapi?$._def.openapi:X._def.openapi,A=(w=$.description)!==null&&w!==void 0?w:X.description;return{_internal:G===null||G===void 0?void 0:G._internal,metadata:Object.assign(Object.assign({},G===null||G===void 0?void 0:G.metadata),{param:Object.assign({description:A},(E=G===null||G===void 0?void 0:G.metadata)===null||E===void 0?void 0:E.param)})}}static buildSchemaMetadata($){return qX(HZ($,["param"]),EA)}static buildParameterMetadata($){return qX($,EA)}static applySchemaMetadata($,w){return qX(Object.assign(Object.assign({},$),this.buildSchemaMetadata(w)),EA)}static getRefId($){var w;return(w=this.getInternalMetadata($))===null||w===void 0?void 0:w.refId}static unwrapChained($){return this.unwrapUntil($)}static getDefaultValue($){let w=this.unwrapUntil($,"ZodDefault");return w===null||w===void 0?void 0:w._def.defaultValue()}static unwrapUntil($,w){if(w&&W0($,w))return $;if(W0($,"ZodOptional")||W0($,"ZodNullable")||W0($,"ZodBranded"))return this.unwrapUntil($.unwrap(),w);if(W0($,"ZodDefault")||W0($,"ZodReadonly"))return this.unwrapUntil($._def.innerType,w);if(W0($,"ZodEffects"))return this.unwrapUntil($._def.schema,w);if(W0($,"ZodPipeline"))return this.unwrapUntil($._def.in,w);return w?void 0:$}static isOptionalSchema($){return $.isOptional()}}class u3{transform($,w,E){var X,G;let A=$._def.type;return Object.assign(Object.assign({},w("array")),{items:E(A),minItems:(X=$._def.minLength)===null||X===void 0?void 0:X.value,maxItems:(G=$._def.maxLength)===null||G===void 0?void 0:G.value})}}class n3{transform($){return Object.assign(Object.assign({},$("string")),{pattern:"^d+$"})}}class h3{transform($,w,E,X,G){let A=[...$.options.values()],N=A.map(X);if(w)return{oneOf:E(N,w)};return{oneOf:N,discriminator:this.mapDiscriminator(A,$.discriminator,G)}}mapDiscriminator($,w,E){if($.some((G)=>u0.getRefId(G)===void 0))return;let X={};return $.forEach((G)=>{var A;let N=u0.getRefId(G),D=(A=G.shape)===null||A===void 0?void 0:A[w];if(W0(D,"ZodEnum")||W0(D,"ZodNativeEnum")){Object.values(D.enum).filter(y3).forEach((J)=>{X[J]=E(N)});return}let O=D===null||D===void 0?void 0:D._def.value;if(typeof O!=="string")throw Error(`Discriminator ${w} could not be found in one of the values of a discriminated union`);X[O]=E(N)}),{propertyName:w,mapping:X}}}class c3{transform($,w){return Object.assign(Object.assign({},w("string")),{enum:$._def.values})}}class r3{transform($,w,E,X){let A={allOf:this.flattenIntersectionTypes($).map(X)};if(w)return{anyOf:E([A],w)};return A}flattenIntersectionTypes($){if(!W0($,"ZodIntersection"))return[$];let w=this.flattenIntersectionTypes($._def.left),E=this.flattenIntersectionTypes($._def.right);return[...w,...E]}}class t3{transform($,w){return Object.assign(Object.assign({},w(typeof $._def.value)),{enum:[$._def.value]})}}function FZ($){let E=Object.keys($).filter((A)=>typeof $[$[A]]!=="number").map((A)=>$[A]),X=E.filter((A)=>typeof A==="number").length,G=X===0?"string":X===E.length?"numeric":"mixed";return{values:E,type:G}}class o3{transform($,w){let{type:E,values:X}=FZ($._def.values);if(E==="mixed")throw new AA("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},w(E==="numeric"?"integer":"string")),{enum:X})}}class m3{transform($,w,E){return Object.assign(Object.assign({},w($.isInt?"integer":"number")),E($._def.checks))}}class i3{transform($,w,E,X){var G;let A=(G=u0.getInternalMetadata($))===null||G===void 0?void 0:G.extendedFrom,N=this.requiredKeysOf($),D=XA($._def.shape(),X);if(!A)return Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{properties:D,default:w}),N.length>0?{required:N}:{}),this.generateAdditionalProperties($,X));let O=A.schema;X(O);let W=this.requiredKeysOf(O),J=XA(O===null||O===void 0?void 0:O._def.shape(),X),Y=Object.fromEntries(Object.entries(D).filter(([F,j])=>{return!E4(J[F],j)})),H=N.filter((F)=>!W.includes(F)),L=Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{default:w,properties:Y}),H.length>0?{required:H}:{}),this.generateAdditionalProperties($,X));return{allOf:[{$ref:`#/components/schemas/${A.refId}`},L]}}generateAdditionalProperties($,w){let E=$._def.unknownKeys,X=$._def.catchall;if(W0(X,"ZodNever")){if(E==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:w(X)}}requiredKeysOf($){return Object.entries($._def.shape()).filter(([w,E])=>!u0.isOptionalSchema(E)).map(([w,E])=>w)}}class p3{transform($,w,E){let X=$._def.valueType,G=$._def.keyType,A=E(X);if(W0(G,"ZodEnum")||W0(G,"ZodNativeEnum")){let D=Object.values(G.enum).filter(y3).reduce((O,W)=>Object.assign(Object.assign({},O),{[W]:A}),{});return Object.assign(Object.assign({},w("object")),{properties:D})}return Object.assign(Object.assign({},w("object")),{additionalProperties:A})}}class d3{transform($,w){var E,X,G;let A=this.getZodStringCheck($,"regex"),N=(E=this.getZodStringCheck($,"length"))===null||E===void 0?void 0:E.value,D=Number.isFinite($.minLength)?(X=$.minLength)!==null&&X!==void 0?X:void 0:void 0,O=Number.isFinite($.maxLength)?(G=$.maxLength)!==null&&G!==void 0?G:void 0:void 0;return Object.assign(Object.assign({},w("string")),{minLength:N!==null&&N!==void 0?N:D,maxLength:N!==null&&N!==void 0?N:O,format:this.mapStringFormat($),pattern:A===null||A===void 0?void 0:A.regex.source})}mapStringFormat($){if($.isUUID)return"uuid";if($.isEmail)return"email";if($.isURL)return"uri";if($.isDate)return"date";if($.isDatetime)return"date-time";if($.isCUID)return"cuid";if($.isCUID2)return"cuid2";if($.isULID)return"ulid";if($.isIP)return"ip";if($.isEmoji)return"emoji";return}getZodStringCheck($,w){return $._def.checks.find((E)=>{return E.kind===w})}}class l3{constructor($){this.versionSpecifics=$}transform($,w,E){let{items:X}=$._def,G=X.map(E);return Object.assign(Object.assign({},w("array")),this.versionSpecifics.mapTupleItems(G))}}class s3{transform($,w,E){let G=this.flattenUnionTypes($).map((A)=>{let N=this.unwrapNullable(A);return E(N)});return{anyOf:w(G)}}flattenUnionTypes($){if(!W0($,"ZodUnion"))return[$];return $._def.options.flatMap((E)=>this.flattenUnionTypes(E))}unwrapNullable($){if(W0($,"ZodNullable"))return this.unwrapNullable($.unwrap());return $}}class a3{constructor($){this.versionSpecifics=$,this.objectTransformer=new i3,this.stringTransformer=new d3,this.numberTransformer=new m3,this.bigIntTransformer=new n3,this.literalTransformer=new t3,this.enumTransformer=new c3,this.nativeEnumTransformer=new o3,this.arrayTransformer=new u3,this.unionTransformer=new s3,this.discriminatedUnionTransformer=new h3,this.intersectionTransformer=new r3,this.recordTransformer=new p3,this.tupleTransformer=new l3($)}transform($,w,E,X,G){if(W0($,"ZodNull"))return this.versionSpecifics.nullType;if(W0($,"ZodUnknown")||W0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(W0($,"ZodObject"))return this.objectTransformer.transform($,G,(N)=>this.versionSpecifics.mapNullableType(N,w),E);let A=this.transformSchemaWithoutDefault($,w,E,X);return Object.assign(Object.assign({},A),{default:G})}transformSchemaWithoutDefault($,w,E,X){if(W0($,"ZodUnknown")||W0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(W0($,"ZodString"))return this.stringTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w));if(W0($,"ZodNumber"))return this.numberTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w),(A)=>this.versionSpecifics.getNumberChecks(A));if(W0($,"ZodBigInt"))return this.bigIntTransformer.transform((A)=>this.versionSpecifics.mapNullableType(A,w));if(W0($,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",w);if(W0($,"ZodLiteral"))return this.literalTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w));if(W0($,"ZodEnum"))return this.enumTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w));if(W0($,"ZodNativeEnum"))return this.nativeEnumTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w));if(W0($,"ZodArray"))return this.arrayTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w),E);if(W0($,"ZodTuple"))return this.tupleTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w),E);if(W0($,"ZodUnion"))return this.unionTransformer.transform($,(A)=>this.versionSpecifics.mapNullableOfArray(A,w),E);if(W0($,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform($,w,(A)=>this.versionSpecifics.mapNullableOfArray(A,w),E,X);if(W0($,"ZodIntersection"))return this.intersectionTransformer.transform($,w,(A)=>this.versionSpecifics.mapNullableOfArray(A,w),E);if(W0($,"ZodRecord"))return this.recordTransformer.transform($,(A)=>this.versionSpecifics.mapNullableType(A,w),E);if(W0($,"ZodDate"))return this.versionSpecifics.mapNullableType("string",w);let G=u0.getRefId($);throw new g3({currentSchema:$._def,schemaName:G})}}class G4{constructor($,w){this.definitions=$,this.versionSpecifics=w,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new a3(w),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents()}}buildComponents(){var $,w;let E={};return this.rawComponents.forEach(({componentType:X,name:G,component:A})=>{var N;(N=E[X])!==null&&N!==void 0||(E[X]={}),E[X][G]=A}),Object.assign(Object.assign({},E),{schemas:Object.assign(Object.assign({},($=E.schemas)!==null&&$!==void 0?$:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(w=E.parameters)!==null&&w!==void 0?w:{}),this.paramRefs)})}sortDefinitions(){let $=["schema","parameter","component","route"];this.definitions.sort((w,E)=>{if(!("type"in w)){if(!("type"in E))return 0;return-1}if(!("type"in E))return 1;let X=$.findIndex((A)=>A===w.type),G=$.findIndex((A)=>A===E.type);return X-G})}generateSingle($){if(!("type"in $)){this.generateSchemaWithRef($);return}switch($.type){case"parameter":this.generateParameterDefinition($.schema);return;case"schema":this.generateSchemaWithRef($.schema);return;case"route":this.generateSingleRoute($.route);return;case"component":this.rawComponents.push($);return}}generateParameterDefinition($){let w=u0.getRefId($),E=this.generateParameter($);if(w)this.paramRefs[w]=E;return E}getParameterRef($,w){var E,X,G,A,N;let D=(E=$===null||$===void 0?void 0:$.metadata)===null||E===void 0?void 0:E.param,O=((X=$===null||$===void 0?void 0:$._internal)===null||X===void 0?void 0:X.refId)?this.paramRefs[(G=$._internal)===null||G===void 0?void 0:G.refId]:void 0;if(!((A=$===null||$===void 0?void 0:$._internal)===null||A===void 0?void 0:A.refId)||!O)return;if(D&&O.in!==D.in||(w===null||w===void 0?void 0:w.in)&&O.in!==w.in)throw new PX(`Conflicting location for parameter ${O.name}`,{key:"in",values:f3([O.in,w===null||w===void 0?void 0:w.in,D===null||D===void 0?void 0:D.in])});if(D&&O.name!==D.name||(w===null||w===void 0?void 0:w.name)&&O.name!==(w===null||w===void 0?void 0:w.name))throw new PX("Conflicting names for parameter",{key:"name",values:f3([O.name,w===null||w===void 0?void 0:w.name,D===null||D===void 0?void 0:D.name])});return{$ref:`#/components/parameters/${(N=$._internal)===null||N===void 0?void 0:N.refId}`}}generateInlineParameters($,w){var E;let X=u0.getMetadata($),G=(E=X===null||X===void 0?void 0:X.metadata)===null||E===void 0?void 0:E.param,A=this.getParameterRef(X,{in:w});if(A)return[A];if(W0($,"ZodObject")){let N=$._def.shape();return Object.entries(N).map(([O,W])=>{var J,Y;let H=u0.getMetadata(W),L=this.getParameterRef(H,{in:w,name:O});if(L)return L;let F=(J=H===null||H===void 0?void 0:H.metadata)===null||J===void 0?void 0:J.param;if((F===null||F===void 0?void 0:F.name)&&F.name!==O)throw new PX("Conflicting names for parameter",{key:"name",values:[O,F.name]});if((F===null||F===void 0?void 0:F.in)&&F.in!==w)throw new PX(`Conflicting location for parameter ${(Y=F.name)!==null&&Y!==void 0?Y:O}`,{key:"in",values:[w,F.in]});return this.generateParameter(W.openapi({param:{name:O,in:w}}))})}if((G===null||G===void 0?void 0:G.in)&&G.in!==w)throw new PX(`Conflicting location for parameter ${G.name}`,{key:"in",values:[w,G.in]});return[this.generateParameter($.openapi({param:{in:w}}))]}generateSimpleParameter($){var w;let E=u0.getParamMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=!u0.isOptionalSchema($)&&!$.isNullable(),A=this.generateSchemaWithRef($);return Object.assign({schema:A,required:G},X?u0.buildParameterMetadata(X):{})}generateParameter($){var w;let E=u0.getMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=X===null||X===void 0?void 0:X.name,A=X===null||X===void 0?void 0:X.in;if(!G)throw new GA({missingField:"name"});if(!A)throw new GA({missingField:"in",paramName:G});let N=this.generateSimpleParameter($);return Object.assign(Object.assign({},N),{in:A,name:G})}generateSchemaWithMetadata($){var w;let E=u0.unwrapChained($),X=u0.getMetadata($),G=u0.getDefaultValue($),A=((w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.type)?{type:X===null||X===void 0?void 0:X.metadata.type}:this.toOpenAPISchema(E,$.isNullable(),G);return(X===null||X===void 0?void 0:X.metadata)?u0.applySchemaMetadata(A,X.metadata):qX(A,EA)}constructReferencedOpenAPISchema($){var w;let E=u0.getMetadata($),X=u0.unwrapChained($),G=u0.getDefaultValue($),A=$.isNullable();if((w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.type)return this.versionSpecifics.mapNullableType(E.metadata.type,A);return this.toOpenAPISchema(X,A,G)}generateSimpleSchema($){var w;let E=u0.getMetadata($),X=u0.getRefId($);if(!X||!this.schemaRefs[X])return this.generateSchemaWithMetadata($);let G=this.schemaRefs[X],A={$ref:this.generateSchemaRef(X)},N=qX(u0.buildSchemaMetadata((w=E===null||E===void 0?void 0:E.metadata)!==null&&w!==void 0?w:{}),(W,J)=>W===void 0||E4(W,G[J]));if(N.type)return{allOf:[A,N]};let D=qX(this.constructReferencedOpenAPISchema($),(W,J)=>W===void 0||E4(W,G[J])),O=u0.applySchemaMetadata(D,N);if(Object.keys(O).length>0)return{allOf:[A,O]};return A}generateSchemaWithRef($){let w=u0.getRefId($),E=this.generateSimpleSchema($);if(w&&this.schemaRefs[w]===void 0)return this.schemaRefs[w]=E,{$ref:this.generateSchemaRef(w)};return E}generateSchemaRef($){return`#/components/schemas/${$}`}getRequestBody($){if(!$)return;let{content:w}=$,E=wA($,["content"]),X=this.getBodyContent(w);return Object.assign(Object.assign({},E),{content:X})}getParameters($){if(!$)return[];let{headers:w}=$,E=this.cleanParameter($.query),X=this.cleanParameter($.params),G=this.cleanParameter($.cookies),A=$A(()=>E?this.generateInlineParameters(E,"query"):[],{location:"query"}),N=$A(()=>X?this.generateInlineParameters(X,"path"):[],{location:"path"}),D=$A(()=>G?this.generateInlineParameters(G,"cookie"):[],{location:"cookie"}),O=$A(()=>{if(Array.isArray(w))return w.flatMap((J)=>this.generateInlineParameters(J,"header"));let W=this.cleanParameter(w);return W?this.generateInlineParameters(W,"header"):[]},{location:"header"});return[...N,...A,...O,...D]}cleanParameter($){if(!$)return;return W0($,"ZodEffects")?this.cleanParameter($._def.schema):$}generatePath($){let{method:w,path:E,request:X,responses:G}=$,A=wA($,["method","path","request","responses"]),N=XA(G,(J)=>{return this.getResponse(J)}),D=$A(()=>this.getParameters(X),{route:`${w} ${E}`}),O=this.getRequestBody(X===null||X===void 0?void 0:X.body);return{[w]:Object.assign(Object.assign(Object.assign(Object.assign({},A),D.length>0?{parameters:[...A.parameters||[],...D]}:{}),O?{requestBody:O}:{}),{responses:N})}}generateSingleRoute($){let w=this.generatePath($);return this.pathRefs[$.path]=Object.assign(Object.assign({},this.pathRefs[$.path]),w),w}getResponse($){if(this.isReferenceObject($))return $;let{content:w,headers:E}=$,X=wA($,["content","headers"]),G=w?{content:this.getBodyContent(w)}:{};if(!E)return Object.assign(Object.assign({},X),G);let A=W0(E,"ZodObject")?this.getResponseHeaders(E):E;return Object.assign(Object.assign(Object.assign({},X),{headers:A}),G)}isReferenceObject($){return"$ref"in $}getResponseHeaders($){let w=$._def.shape();return XA(w,(X)=>this.generateSimpleParameter(X))}getBodyContent($){return XA($,(w)=>{if(!w||!YZ(w.schema))return w;let{schema:E}=w,X=wA(w,["schema"]),G=this.generateSchemaWithRef(E);return Object.assign({schema:G},X)})}toOpenAPISchema($,w,E){return this.openApiTransformer.transform($,w,(X)=>this.generateSchemaWithRef(X),(X)=>this.generateSchemaRef(X),E)}}class e3{get nullType(){return{nullable:!0}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){return Object.assign(Object.assign({},$?{type:$}:void 0),w?this.nullType:void 0)}mapTupleItems($){let w=LZ($);return{items:w.length===1?w[0]:{anyOf:w},minItems:$.length,maxItems:$.length}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{minimum:Number(w.value),exclusiveMinimum:!0};case"max":return w.inclusive?{maximum:Number(w.value)}:{maximum:Number(w.value),exclusiveMaximum:!0};default:return{}}}))}}class A4{constructor($){let w=new e3;this.generator=new G4($,w)}generateDocument($){let w=this.generator.generateDocumentData();return Object.assign(Object.assign({},$),w)}generateComponents(){return this.generator.generateComponents()}}class $F{get nullType(){return{type:"null"}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){if(!$)return{};if(w)return{type:Array.isArray($)?[...$,"null"]:[$,"null"]};return{type:$}}mapTupleItems($){return{prefixItems:$}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{exclusiveMinimum:Number(w.value)};case"max":return w.inclusive?{maximum:Number(w.value)}:{exclusiveMaximum:Number(w.value)};default:return{}}}))}}function jZ($){return"type"in $&&$.type==="webhook"}class N4{constructor($){this.definitions=$,this.webhookRefs={};let w=new $F;this.generator=new G4(this.definitions,w)}generateDocument($){let w=this.generator.generateDocumentData();return this.definitions.filter(jZ).forEach((E)=>this.generateSingleWebhook(E.webhook)),Object.assign(Object.assign(Object.assign({},$),w),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook($){let w=this.generator.generatePath($);return this.webhookRefs[$.path]=Object.assign(Object.assign({},this.webhookRefs[$.path]),w),w}}var E4,PX,GA,g3;var wF=T(()=>{E4=fD;PX=class PX extends AA{constructor($,w){super($);this.data=w}};GA=class GA extends AA{constructor($){super(`Missing parameter data, please specify \`${$.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=$}};g3=class g3 extends AA{constructor($){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=$}}});var O4=($)=>{let w=$.split("/");if(w[0]==="")w.shift();return w},EF=($)=>{let{groups:w,path:E}=MZ($),X=O4(E);return TZ(X,w)},MZ=($)=>{let w=[];return $=$.replace(/\{[^}]+\}/g,(E,X)=>{let G=`@${X}`;return w.push([G,E]),G}),{groups:w,path:$}},TZ=($,w)=>{for(let E=w.length-1;E>=0;E--){let[X]=w[E];for(let G=$.length-1;G>=0;G--)if($[G].includes(X)){$[G]=$[G].replace(X,w[E][1]);break}}return $},vD,XF=($,w)=>{if($==="*")return"*";let E=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(E){let X=`${$}#${w}`;if(!vD[X])if(E[2])vD[X]=w&&w[0]!==":"&&w[0]!=="*"?[X,E[1],new RegExp(`^${E[2]}(?=/${w})`)]:[$,E[1],new RegExp(`^${E[2]}$`)];else vD[X]=[$,E[1],!0];return vD[X]}return null},SX=($,w)=>{try{return w($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(E)=>{try{return w(E)}catch{return E}})}},RZ=($)=>SX($,decodeURI),W4=($)=>{let w=$.url,E=w.indexOf("/",w.indexOf(":")+4),X=E;for(;X<w.length;X++){let G=w.charCodeAt(X);if(G===37){let A=w.indexOf("?",X),N=w.indexOf("#",X),D=A===-1?N===-1?void 0:N:N===-1?A:Math.min(A,N),O=w.slice(E,D);return RZ(O.includes("%25")?O.replace(/%25/g,"%2525"):O)}else if(G===63||G===35)break}return w.slice(E,X)},GF=($)=>{let w=W4($);return w.length>1&&w.at(-1)==="/"?w.slice(0,-1):w},fw=($,w,...E)=>{if(E.length)w=fw(w,...E);return`${$?.[0]==="/"?"":"/"}${$}${w==="/"?"":`${$?.at(-1)==="/"?"":"/"}${w?.[0]==="/"?w.slice(1):w}`}`},xD=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let w=$.split("/"),E=[],X="";return w.forEach((G)=>{if(G!==""&&!/\:/.test(G))X+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(E.length===0&&X==="")E.push("/");else E.push(X);let A=G.replace("?","");X+="/"+A,E.push(X)}else X+="/"+G}),E.filter((G,A,N)=>N.indexOf(G)===A)},D4=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?SX($,NA):$},AF=($,w,E)=>{let X;if(!E&&w&&!/[%+]/.test(w)){let N=$.indexOf("?",8);if(N===-1)return;if(!$.startsWith(w,N+1))N=$.indexOf(`&${w}`,N+1);while(N!==-1){let D=$.charCodeAt(N+w.length+1);if(D===61){let O=N+w.length+2,W=$.indexOf("&",O);return D4($.slice(O,W===-1?void 0:W))}else if(D==38||isNaN(D))return"";N=$.indexOf(`&${w}`,N+1)}if(X=/[%+]/.test($),!X)return}let G={};X??=/[%+]/.test($);let A=$.indexOf("?",8);while(A!==-1){let N=$.indexOf("&",A+1),D=$.indexOf("=",A);if(D>N&&N!==-1)D=-1;let O=$.slice(A+1,D===-1?N===-1?void 0:N:D);if(X)O=D4(O);if(A=N,O==="")continue;let W;if(D===-1)W="";else if(W=$.slice(D+1,N===-1?void 0:N),X)W=D4(W);if(E){if(!(G[O]&&Array.isArray(G[O])))G[O]=[];G[O].push(W)}else G[O]??=W}return w?G[w]:G},NF,DF=($,w)=>{return AF($,w,!0)},NA;var mE=T(()=>{vD={},NF=AF,NA=decodeURIComponent});var zZ,BZ,J4=($,w)=>{if(w&&$.indexOf(w)===-1)return{};let E=$.trim().split(";"),X={};for(let G of E){G=G.trim();let A=G.indexOf("=");if(A===-1)continue;let N=G.substring(0,A).trim();if(w&&w!==N||!zZ.test(N))continue;let D=G.substring(A+1).trim();if(D.startsWith('"')&&D.endsWith('"'))D=D.slice(1,-1);if(BZ.test(D)){if(X[N]=D.indexOf("%")!==-1?SX(D,NA):D,w)break}}return X};var OF=T(()=>{mE();zZ=/^[\w!#$%&'*.^`|~+-]+$/,BZ=/^[ !#-:<-[\]-~]*$/});var WF=($,w,E)=>{let X=$.req.raw.headers.get("Cookie");if(typeof w==="string"){if(!X)return;let A=w;if(E==="secure")A="__Secure-"+w;else if(E==="host")A="__Host-"+w;return J4(X,A)[A]}if(!X)return{};return J4(X)};var JF=T(()=>{OF()});var yD;var U4=T(()=>{yD=class extends Error{res;status;constructor($=500,w){super(w?.message,{cause:w?.cause});this.res=w?.res,this.status=$}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var UF=()=>{};var YF=($,w)=>{return new Response($,{headers:{"Content-Type":w}}).formData()};var HF=T(()=>{UF()});var IZ,QZ,KZ,Y4=($,w)=>{return async(E,X)=>{let G={},A=E.req.header("Content-Type");switch($){case"json":if(!A||!IZ.test(A))break;try{G=await E.req.json()}catch{throw new yD(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!A||!(QZ.test(A)||KZ.test(A)))break;let D;if(E.req.bodyCache.formData)D=await E.req.bodyCache.formData;else try{let W=await E.req.arrayBuffer();D=await YF(W,A),E.req.bodyCache.formData=D}catch(W){let J="Malformed FormData request.";throw J+=W instanceof Error?` ${W.message}`:` ${String(W)}`,new yD(400,{message:J})}let O=Object.create(null);D.forEach((W,J)=>{if(J.endsWith("[]"))(O[J]??=[]).push(W);else if(Array.isArray(O[J]))O[J].push(W);else if(Object.hasOwn(O,J))O[J]=[O[J],W];else O[J]=W}),G=O;break}case"query":G=Object.fromEntries(Object.entries(E.req.queries()).map(([D,O])=>{return O.length===1?[D,O[0]]:[D,O]}));break;case"param":G=E.req.param();break;case"header":G=E.req.header();break;case"cookie":G=WF(E);break}let N=await w(G,E);if(N instanceof Response)return N;return E.req.addValidatedData($,N),await X()}};var LF=T(()=>{JF();U4();HF();IZ=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,QZ=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,KZ=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var FF=T(()=>{LF()});function VZ($,w,E,X){return Y4($,async(G,A)=>{let N=G;if($==="header"&&"_def"in w||$==="header"&&"_zod"in w){let O=Object.keys("in"in w?w.in.shape:w.shape),W=Object.fromEntries(O.map((J)=>[J.toLowerCase(),J]));N=Object.fromEntries(Object.entries(G).map(([J,Y])=>[W[J]||J,Y]))}let D=X&&X.validationFunction?await X.validationFunction(w,N):await w.safeParseAsync(N);if(E){let O=await E({data:N,...D,target:$},A);if(O){if(O instanceof Response)return O;if("response"in O)return O.response}}if(!D.success)return A.json(D,400);return D.data})}var Q1;var jF=T(()=>{FF();Q1=VZ});var H4=($,w,E)=>{return(X,G)=>{let A=-1;return N(0);async function N(D){if(D<=A)throw Error("next() called multiple times");A=D;let O,W=!1,J;if($[D])J=$[D][0][0],X.req.routeIndex=D;else J=D===$.length&&G||void 0;if(J)try{O=await J(X,()=>N(D+1))}catch(Y){if(Y instanceof Error&&w)X.error=Y,O=await w(Y,X),W=!0;else throw Y}else if(X.finalized===!1&&E)O=await E(X);if(O&&(X.finalized===!1||W))X.res=O;return X}}};var MF=()=>{};var TF;var RF=T(()=>{TF=Symbol()});async function PZ($,w){let E=await $.formData();if(E)return qZ(E,w);return{}}function qZ($,w){let E=Object.create(null);if($.forEach((X,G)=>{if(!(w.all||G.endsWith("[]")))E[G]=X;else SZ(E,G,X)}),w.dot)Object.entries(E).forEach(([X,G])=>{if(X.includes("."))kZ(E,X,G),delete E[X]});return E}var zF=async($,w=Object.create(null))=>{let{all:E=!1,dot:X=!1}=w,A=($ instanceof gD?$.raw.headers:$.headers).get("Content-Type");if(A?.startsWith("multipart/form-data")||A?.startsWith("application/x-www-form-urlencoded"))return PZ($,{all:E,dot:X});return{}},SZ=($,w,E)=>{if($[w]!==void 0)if(Array.isArray($[w]))$[w].push(E);else $[w]=[$[w],E];else if(!w.endsWith("[]"))$[w]=E;else $[w]=[E]},kZ=($,w,E)=>{if(/(?:^|\.)__proto__\./.test(w))return;let X=$,G=w.split(".");G.forEach((A,N)=>{if(N===G.length-1)X[A]=E;else{if(!X[A]||typeof X[A]!=="object"||Array.isArray(X[A])||X[A]instanceof File)X[A]=Object.create(null);X=X[A]}})};var BF=T(()=>{L4()});var IF=($)=>SX($,NA),gD;var L4=T(()=>{U4();RF();BF();mE();gD=class{raw;#$;#w;routeIndex=0;path;bodyCache={};constructor($,w="/",E=[[]]){this.raw=$,this.path=w,this.#w=E,this.#$={}}param($){return $?this.#E($):this.#A()}#E($){let w=this.#w[0][this.routeIndex][1][$],E=this.#G(w);return E&&/\%/.test(E)?IF(E):E}#A(){let $={},w=Object.keys(this.#w[0][this.routeIndex][1]);for(let E of w){let X=this.#G(this.#w[0][this.routeIndex][1][E]);if(X!==void 0)$[E]=/\%/.test(X)?IF(X):X}return $}#G($){return this.#w[1]?this.#w[1][$]:$}query($){return NF(this.url,$)}queries($){return DF(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let w={};return this.raw.headers.forEach((E,X)=>{w[X]=E}),w}async parseBody($){return this.bodyCache.parsedBody??=await zF(this,$)}#X=($)=>{let{bodyCache:w,raw:E}=this,X=w[$];if(X)return X;let G=Object.keys(w)[0];if(G)return w[G].then((A)=>{if(G==="json")A=JSON.stringify(A);return new Response(A)[$]()});return w[$]=E[$]()};json(){return this.#X("text").then(($)=>JSON.parse($))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData($,w){this.#$[$]=w}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[TF](){return this.#w}get matchedRoutes(){return this.#w[0].map(([[,$]])=>$)}get routePath(){return this.#w[0].map(([[,$]])=>$)[this.routeIndex].path}}});var bZ="text/plain; charset=UTF-8",F4=($,w)=>{return{"Content-Type":$,...w}},DA=($,w)=>new Response($,w),QF=class{#$;#w;env={};#E;finalized=!1;error;#A;#G;#X;#J;#O;#W;#D;#U;#Y;constructor($,w){if(this.#$=$,w)this.#G=w.executionCtx,this.env=w.env,this.#W=w.notFoundHandler,this.#Y=w.path,this.#U=w.matchResult}get req(){return this.#w??=new gD(this.#$,this.#Y,this.#U),this.#w}get event(){if(this.#G&&"respondWith"in this.#G)return this.#G;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#G)return this.#G;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=DA(null,{headers:this.#D??=new Headers})}set res($){if(this.#X&&$){$=DA($.body,$);for(let[w,E]of this.#X.headers.entries()){if(w==="content-type")continue;if(w==="set-cookie"){let X=this.#X.headers.getSetCookie();$.headers.delete("set-cookie");for(let G of X)$.headers.append("set-cookie",G)}else $.headers.set(w,E)}}this.#X=$,this.finalized=!0}render=(...$)=>{return this.#O??=(w)=>this.html(w),this.#O(...$)};setLayout=($)=>this.#J=$;getLayout=()=>this.#J;setRenderer=($)=>{this.#O=$};header=($,w,E)=>{if(this.finalized)this.#X=DA(this.#X.body,this.#X);let X=this.#X?this.#X.headers:this.#D??=new Headers;if(w===void 0)X.delete($);else if(E?.append)X.append($,w);else X.set($,w)};status=($)=>{this.#A=$};set=($,w)=>{this.#E??=new Map,this.#E.set($,w)};get=($)=>{return this.#E?this.#E.get($):void 0};get var(){if(!this.#E)return{};return Object.fromEntries(this.#E)}#N($,w,E){let X=this.#X?new Headers(this.#X.headers):this.#D??new Headers;if(typeof w==="object"&&"headers"in w){let A=w.headers instanceof Headers?w.headers:new Headers(w.headers);for(let[N,D]of A)if(N.toLowerCase()==="set-cookie")X.append(N,D);else X.set(N,D)}if(E)for(let[A,N]of Object.entries(E))if(typeof N==="string")X.set(A,N);else{X.delete(A);for(let D of N)X.append(A,D)}let G=typeof w==="number"?w:w?.status??this.#A;return DA($,{status:G,headers:X})}newResponse=(...$)=>this.#N(...$);body=($,w,E)=>this.#N($,w,E);text=($,w,E)=>{return!this.#D&&!this.#A&&!w&&!E&&!this.finalized?new Response($):this.#N($,w,F4(bZ,E))};json=($,w,E)=>{return this.#N(JSON.stringify($),w,F4("application/json",E))};html=($,w,E)=>{let X=(G)=>this.#N(G,w,F4("text/html; charset=UTF-8",E));return typeof $==="object"?eJ($,aJ.Stringify,!1,{}).then(X):X($)};redirect=($,w)=>{let E=String($);return this.header("Location",!/[^\x00-\xFF]/.test(E)?E:encodeURI(E)),this.newResponse(null,w??302)};notFound=()=>{return this.#W??=()=>DA(),this.#W(this)}};var KF=T(()=>{L4();$4()});var Z0="ALL",VF="all",PF,uD="Can not add a route since the matcher is already built.",nD;var K1=T(()=>{PF=["get","post","put","delete","options","patch"],nD=class extends Error{}});var qF="__COMPOSED_HANDLER";var SF=()=>{};var _Z=($)=>{return $.text("404 Not Found",404)},kF=($,w)=>{if("getResponse"in $){let E=$.getResponse();return w.newResponse(E.body,E)}return console.error($),w.text("Internal Server Error",500)},bF=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(w={}){[...PF,VF].forEach((A)=>{this[A]=(N,...D)=>{if(typeof N==="string")this.#$=N;else this.#A(A,this.#$,N);return D.forEach((O)=>{this.#A(A,this.#$,O)}),this}}),this.on=(A,N,...D)=>{for(let O of[N].flat()){this.#$=O;for(let W of[A].flat())D.map((J)=>{this.#A(W.toUpperCase(),this.#$,J)})}return this},this.use=(A,...N)=>{if(typeof A==="string")this.#$=A;else this.#$="*",N.unshift(A);return N.forEach((D)=>{this.#A(Z0,this.#$,D)}),this};let{strict:X,...G}=w;Object.assign(this,G),this.getPath=X??!0?w.getPath??W4:GF}#w(){let w=new $({router:this.router,getPath:this.getPath});return w.errorHandler=this.errorHandler,w.#E=this.#E,w.routes=this.routes,w}#E=_Z;errorHandler=kF;route(w,E){let X=this.basePath(w);return E.routes.map((G)=>{let A;if(E.errorHandler===kF)A=G.handler;else A=async(N,D)=>(await H4([],E.errorHandler)(N,()=>G.handler(N,D))).res,A[qF]=G.handler;X.#A(G.method,G.path,A)}),this}basePath(w){let E=this.#w();return E._basePath=fw(this._basePath,w),E}onError=(w)=>{return this.errorHandler=w,this};notFound=(w)=>{return this.#E=w,this};mount(w,E,X){let G,A;if(X)if(typeof X==="function")A=X;else if(A=X.optionHandler,X.replaceRequest===!1)G=(O)=>O;else G=X.replaceRequest;let N=A?(O)=>{let W=A(O);return Array.isArray(W)?W:[W]}:(O)=>{let W=void 0;try{W=O.executionCtx}catch{}return[O.env,W]};G||=(()=>{let O=fw(this._basePath,w),W=O==="/"?0:O.length;return(J)=>{let Y=new URL(J.url);return Y.pathname=Y.pathname.slice(W)||"/",new Request(Y,J)}})();let D=async(O,W)=>{let J=await E(G(O.req.raw),...N(O));if(J)return J;await W()};return this.#A(Z0,fw(w,"*"),D),this}#A(w,E,X){w=w.toUpperCase(),E=fw(this._basePath,E);let G={basePath:this._basePath,path:E,method:w,handler:X};this.router.add(w,E,[X,G]),this.routes.push(G)}#G(w,E){if(w instanceof Error)return this.errorHandler(w,E);throw w}#X(w,E,X,G){if(G==="HEAD")return(async()=>new Response(null,await this.#X(w,E,X,"GET")))();let A=this.getPath(w,{env:X}),N=this.router.match(G,A),D=new QF(w,{path:A,matchResult:N,env:X,executionCtx:E,notFoundHandler:this.#E});if(N[0].length===1){let W;try{W=N[0][0][0][0](D,async()=>{D.res=await this.#E(D)})}catch(J){return this.#G(J,D)}return W instanceof Promise?W.then((J)=>J||(D.finalized?D.res:this.#E(D))).catch((J)=>this.#G(J,D)):W??this.#E(D)}let O=H4(N[0],this.errorHandler,this.#E);return(async()=>{try{let W=await O(D);if(!W.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return W.res}catch(W){return this.#G(W,D)}})()}fetch=(w,...E)=>{return this.#X(w,E[1],E[0],w.method)};request=(w,E,X,G)=>{if(w instanceof Request)return this.fetch(E?new Request(w,E):w,X,G);return w=w.toString(),this.fetch(new Request(/^https?:\/\//.test(w)?w:`http://localhost${fw("/",w)}`,E),X,G)};fire=()=>{addEventListener("fetch",(w)=>{w.respondWith(this.#X(w.request,w,void 0,w.request.method))})}};var _F=T(()=>{MF();KF();K1();SF();mE()});function hD($,w){let E=this.buildAllMatchers(),X=(G,A)=>{let N=E[G]||E[Z0],D=N[2][A];if(D)return D;let O=A.match(N[0]);if(!O)return[[],OA];let W=O.indexOf("",1);return[N[1][W],O]};return this.match=X,X($,w)}var OA;var j4=T(()=>{K1();OA=[]});function CZ($,w){if($.length===1)return w.length===1?$<w?-1:1:-1;if(w.length===1)return 1;if($===WA||$===JA)return 1;else if(w===WA||w===JA)return-1;if($===cD)return 1;else if(w===cD)return-1;return $.length===w.length?$<w?-1:1:w.length-$.length}var cD="[^/]+",WA=".*",JA="(?:|/.*)",V1,ZZ,ZF=class ${#$;#w;#E=Object.create(null);insert(w,E,X,G,A){if(w.length===0){if(this.#$!==void 0)throw V1;if(A)return;this.#$=E;return}let[N,...D]=w,O=N==="*"?D.length===0?["","",WA]:["","",cD]:N==="/*"?["","",JA]:N.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),W;if(O){let J=O[1],Y=O[2]||cD;if(J&&O[2]){if(Y===".*")throw V1;if(Y=Y.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(Y))throw V1}if(W=this.#E[Y],!W){if(Object.keys(this.#E).some((H)=>H!==WA&&H!==JA))throw V1;if(A)return;if(W=this.#E[Y]=new $,J!=="")W.#w=G.varIndex++}if(!A&&J!=="")X.push([J,W.#w])}else if(W=this.#E[N],!W){if(Object.keys(this.#E).some((J)=>J.length>1&&J!==WA&&J!==JA))throw V1;if(A)return;W=this.#E[N]=new $}W.insert(D,E,X,G,A)}buildRegExpStr(){let E=Object.keys(this.#E).sort(CZ).map((X)=>{let G=this.#E[X];return(typeof G.#w==="number"?`(${X})@${G.#w}`:ZZ.has(X)?`\\${X}`:X)+G.buildRegExpStr()});if(typeof this.#$==="number")E.unshift(`#${this.#$}`);if(E.length===0)return"";if(E.length===1)return E[0];return"(?:"+E.join("|")+")"}};var M4=T(()=>{V1=Symbol(),ZZ=new Set(".\\+*[^]$()")});var CF=class{#$={varIndex:0};#w=new ZF;insert($,w,E){let X=[],G=[];for(let N=0;;){let D=!1;if($=$.replace(/\{[^}]+\}/g,(O)=>{let W=`@\\${N}`;return G[N]=[W,O],N++,D=!0,W}),!D)break}let A=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let N=G.length-1;N>=0;N--){let[D]=G[N];for(let O=A.length-1;O>=0;O--)if(A[O].indexOf(D)!==-1){A[O]=A[O].replace(D,G[N][1]);break}}return this.#w.insert(A,w,X,this.#$,E),X}buildRegExp(){let $=this.#w.buildRegExpStr();if($==="")return[/^$/,[],[]];let w=0,E=[],X=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,A,N)=>{if(A!==void 0)return E[++w]=Number(A),"$()";if(N!==void 0)return X[Number(N)]=++w,"";return""}),[new RegExp(`^${$}`),E,X]}};var fF=T(()=>{M4()});function xF($){return vF[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(w,E)=>E?`\\${E}`:"(?:|/.*)")}$`)}function vZ(){vF=Object.create(null)}function xZ($){let w=new CF,E=[];if($.length===0)return fZ;let X=$.map((W)=>[!/\*|\/:/.test(W[0]),...W]).sort(([W,J],[Y,H])=>W?1:Y?-1:J.length-H.length),G=Object.create(null);for(let W=0,J=-1,Y=X.length;W<Y;W++){let[H,L,F]=X[W];if(H)G[L]=[F.map(([M])=>[M,Object.create(null)]),OA];else J++;let j;try{j=w.insert(L,J,H)}catch(M){throw M===V1?new nD(L):M}if(H)continue;E[J]=F.map(([M,R])=>{let B=Object.create(null);R-=1;for(;R>=0;R--){let[I,C]=j[R];B[I]=C}return[M,B]})}let[A,N,D]=w.buildRegExp();for(let W=0,J=E.length;W<J;W++)for(let Y=0,H=E[W].length;Y<H;Y++){let L=E[W][Y]?.[1];if(!L)continue;let F=Object.keys(L);for(let j=0,M=F.length;j<M;j++)L[F[j]]=D[L[F[j]]]}let O=[];for(let W in N)O[W]=E[N[W]];return[A,O,G]}function kX($,w){if(!$)return;for(let E of Object.keys($).sort((X,G)=>G.length-X.length))if(xF(E).test(w))return[...$[E]];return}var fZ,vF,rD=class{name="RegExpRouter";#$;#w;constructor(){this.#$={[Z0]:Object.create(null)},this.#w={[Z0]:Object.create(null)}}add($,w,E){let X=this.#$,G=this.#w;if(!X||!G)throw Error(uD);if(!X[$])[X,G].forEach((D)=>{D[$]=Object.create(null),Object.keys(D[Z0]).forEach((O)=>{D[$][O]=[...D[Z0][O]]})});if(w==="/*")w="*";let A=(w.match(/\/:/g)||[]).length;if(/\*$/.test(w)){let D=xF(w);if($===Z0)Object.keys(X).forEach((O)=>{X[O][w]||=kX(X[O],w)||kX(X[Z0],w)||[]});else X[$][w]||=kX(X[$],w)||kX(X[Z0],w)||[];Object.keys(X).forEach((O)=>{if($===Z0||$===O)Object.keys(X[O]).forEach((W)=>{D.test(W)&&X[O][W].push([E,A])})}),Object.keys(G).forEach((O)=>{if($===Z0||$===O)Object.keys(G[O]).forEach((W)=>D.test(W)&&G[O][W].push([E,A]))});return}let N=xD(w)||[w];for(let D=0,O=N.length;D<O;D++){let W=N[D];Object.keys(G).forEach((J)=>{if($===Z0||$===J)G[J][W]||=[...kX(X[J],W)||kX(X[Z0],W)||[]],G[J][W].push([E,A-O+D+1])})}}match=hD;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#w).concat(Object.keys(this.#$)).forEach((w)=>{$[w]||=this.#E(w)}),this.#$=this.#w=void 0,vZ(),$}#E($){let w=[],E=$===Z0;if([this.#$,this.#w].forEach((X)=>{let G=X[$]?Object.keys(X[$]).map((A)=>[A,X[$][A]]):[];if(G.length!==0)E||=!0,w.push(...G);else if($!==Z0)w.push(...Object.keys(X[Z0]).map((A)=>[A,X[Z0][A]]))}),!E)return null;else return xZ(w)}};var T4=T(()=>{K1();mE();j4();M4();fF();fZ=[/^$/,[],Object.create(null)],vF=Object.create(null)});var yZ=class{name="PreparedRegExpRouter";#$;#w;constructor($,w){this.#$=$,this.#w=w}#E($,w){let E=this.#$[$];E[1].forEach((X)=>X&&X.push(w)),Object.values(E[2]).forEach((X)=>X[0].push(w))}#A($,w,E,X,G){let A=this.#$[$];if(!G)A[2][w][0].push([E,{}]);else X.forEach((N)=>{if(typeof N==="number")A[1][N].push([E,G]);else A[2][N||w][0].push([E,G])})}add($,w,E){if(!this.#$[$]){let G=this.#$[Z0],A={};for(let N in G[2])A[N]=[G[2][N][0].slice(),OA];this.#$[$]=[G[0],G[1].map((N)=>Array.isArray(N)?N.slice():0),A]}if(w==="/*"||w==="*"){let G=[E,{}];if($===Z0)for(let A in this.#$)this.#E(A,G);else this.#E($,G);return}let X=this.#w[w];if(!X)throw Error(`Path ${w} is not registered`);for(let[G,A]of X)if($===Z0)for(let N in this.#$)this.#A(N,w,E,G,A);else this.#A($,w,E,G,A)}buildAllMatchers(){return this.#$}match=hD};var yF=T(()=>{K1();j4();T4()});var gF=T(()=>{T4();yF()});var R4=class{name="SmartRouter";#$=[];#w=[];constructor($){this.#$=$.routers}add($,w,E){if(!this.#w)throw Error(uD);this.#w.push([$,w,E])}match($,w){if(!this.#w)throw Error("Fatal error");let E=this.#$,X=this.#w,G=E.length,A=0,N;for(;A<G;A++){let D=E[A];try{for(let O=0,W=X.length;O<W;O++)D.add(...X[O]);N=D.match($,w)}catch(O){if(O instanceof nD)continue;throw O}this.match=D.match.bind(D),this.#$=[D],this.#w=void 0;break}if(A===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,N}get activeRouter(){if(this.#w||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var uF=T(()=>{K1()});var nF=T(()=>{uF()});var UA,gZ=($)=>{for(let w in $)return!0;return!1},hF=class ${#$;#w;#E;#A=0;#G=UA;constructor(w,E,X){if(this.#w=X||Object.create(null),this.#$=[],w&&E){let G=Object.create(null);G[w]={handler:E,possibleKeys:[],score:0},this.#$=[G]}this.#E=[]}insert(w,E,X){this.#A=++this.#A;let G=this,A=EF(E),N=[];for(let D=0,O=A.length;D<O;D++){let W=A[D],J=A[D+1],Y=XF(W,J),H=Array.isArray(Y)?Y[0]:W;if(H in G.#w){if(G=G.#w[H],Y)N.push(Y[1]);continue}if(G.#w[H]=new $,Y)G.#E.push(Y),N.push(Y[1]);G=G.#w[H]}return G.#$.push({[w]:{handler:X,possibleKeys:N.filter((D,O,W)=>W.indexOf(D)===O),score:this.#A}}),G}#X(w,E,X,G,A){for(let N=0,D=E.#$.length;N<D;N++){let O=E.#$[N],W=O[X]||O[Z0],J={};if(W!==void 0){if(W.params=Object.create(null),w.push(W),G!==UA||A&&A!==UA)for(let Y=0,H=W.possibleKeys.length;Y<H;Y++){let L=W.possibleKeys[Y],F=J[W.score];W.params[L]=A?.[L]&&!F?A[L]:G[L]??A?.[L],J[W.score]=!0}}}}search(w,E){let X=[];this.#G=UA;let A=[this],N=O4(E),D=[],O=N.length,W=null;for(let J=0;J<O;J++){let Y=N[J],H=J===O-1,L=[];for(let j=0,M=A.length;j<M;j++){let R=A[j],B=R.#w[Y];if(B)if(B.#G=R.#G,H){if(B.#w["*"])this.#X(X,B.#w["*"],w,R.#G);this.#X(X,B,w,R.#G)}else L.push(B);for(let I=0,C=R.#E.length;I<C;I++){let v=R.#E[I],k=R.#G===UA?{}:{...R.#G};if(v==="*"){let l0=R.#w["*"];if(l0)this.#X(X,l0,w,R.#G),l0.#G=k,L.push(l0);continue}let[n,H0,b0]=v;if(!Y&&!(b0 instanceof RegExp))continue;let c0=R.#w[n];if(b0 instanceof RegExp){if(W===null){W=Array(O);let Y$=E[0]==="/"?1:0;for(let Jw=0;Jw<O;Jw++)W[Jw]=Y$,Y$+=N[Jw].length+1}let l0=E.substring(W[J]),V0=b0.exec(l0);if(V0){if(k[H0]=V0[0],this.#X(X,c0,w,R.#G,k),gZ(c0.#w)){c0.#G=k;let Y$=V0[0].match(/\//)?.length??0;(D[Y$]||=[]).push(c0)}continue}}if(b0===!0||b0.test(Y))if(k[H0]=Y,H){if(this.#X(X,c0,w,k,R.#G),c0.#w["*"])this.#X(X,c0.#w["*"],w,k,R.#G)}else c0.#G=k,L.push(c0)}}let F=D.shift();A=F?L.concat(F):L}if(X.length>1)X.sort((J,Y)=>{return J.score-Y.score});return[X.map(({handler:J,params:Y})=>[J,Y])]}};var cF=T(()=>{K1();mE();UA=Object.create(null)});var z4=class{name="TrieRouter";#$;constructor(){this.#$=new hF}add($,w,E){let X=xD(w);if(X){for(let G=0,A=X.length;G<A;G++)this.#$.insert($,X[G],E);return}this.#$.insert($,w,E)}match($,w){return this.#$.search($,w)}};var rF=T(()=>{mE();cF()});var tF=T(()=>{rF()});var B4;var oF=T(()=>{_F();gF();nF();tF();B4=class extends bF{constructor($={}){super($);this.router=$.router??new R4({routers:[new rD,new z4]})}}});var mF=T(()=>{oF()});function iF($,w){let E={};return Object.keys($.paths).forEach((X)=>{E[fw(w.replaceAll(/:([^\/]+)/g,"{$1}"),X)]=$.paths[X]}),{...$,paths:E}}function pF($){return/^application\/([a-z-\.]+\+)?json/.test($)}function dF($){return $.startsWith("multipart/form-data")||$.startsWith("application/x-www-form-urlencoded")}var m0,i=($)=>{let w={...$,getRoutingPath(){return $.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(w,"getRoutingPath",{enumerable:!1})};var Ow=T(()=>{wF();jF();mF();mE();LG();m0=class $ extends B4{openAPIRegistry;defaultHook;constructor(w){super(w);this.openAPIRegistry=new X4,this.defaultHook=w?.defaultHook}openapi=({middleware:w,hide:E,...X},G,A=this.defaultHook)=>{if(!E)this.openAPIRegistry.registerPath(X);let N=[];if(X.request?.query){let W=Q1("query",X.request.query,A);N.push(W)}if(X.request?.params){let W=Q1("param",X.request.params,A);N.push(W)}if(X.request?.headers){let W=Q1("header",X.request.headers,A);N.push(W)}if(X.request?.cookies){let W=Q1("cookie",X.request.cookies,A);N.push(W)}let D=X.request?.body?.content;if(D)for(let W of Object.keys(D)){if(!D[W])continue;let J=D[W].schema;if(!(J instanceof A0))continue;if(pF(W)){let Y=Q1("json",J,A);if(X.request?.body?.required)N.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(pF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("json",{}),await F()};N.push(H)}}if(dF(W)){let Y=Q1("form",J,A);if(X.request?.body?.required)N.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(dF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("form",{}),await F()};N.push(H)}}}let O=w?Array.isArray(w)?w:[w]:[];return this.on([X.method],X.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...O,...N,G),this};getOpenAPIDocument=(w)=>{let X=new A4(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?iF(X,this._basePath):X};getOpenAPI31Document=(w)=>{let X=new N4(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?iF(X,this._basePath):X};doc=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let A=this.getOpenAPIDocument(G);return X.json(A)}catch(A){return X.json(A,500)}})};doc31=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let A=this.getOpenAPI31Document(G);return X.json(A)}catch(A){return X.json(A,500)}})};route(w,E){let X=w.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(w,E),!(E instanceof $))return this;return E.openAPIRegistry.definitions.forEach((G)=>{switch(G.type){case"component":return this.openAPIRegistry.registerComponent(G.componentType,G.name,G.component);case"route":{this.openAPIRegistry.registerPath({...G.route,path:fw(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...G.webhook,path:fw(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.webhook.path)});return}case"schema":return this.openAPIRegistry.register(G.schema._def.openapi._internal.refId,G.schema);case"parameter":return this.openAPIRegistry.registerParameter(G.schema._def.openapi._internal.refId,G.schema);default:throw Error(`Unknown registry type: ${G}`)}}),this}basePath(w){return new $({...super.basePath(w),defaultHook:this.defaultHook})}};v3(U)});var bX,L0,zE,I4;var vw=T(()=>{bX=class bX extends Error{code;statusCode;constructor($,w,E=500){super($);this.code=w;this.statusCode=E;this.name="OrcError"}};L0=class L0 extends bX{constructor($,w){super(`${$} not found: ${w}`,"NOT_FOUND",404);this.name="NotFoundError"}};zE=class zE extends bX{constructor($){super($,"VALIDATION_ERROR",400);this.name="ValidationError"}};I4=class I4 extends bX{constructor($="Unauthorized"){super($,"UNAUTHORIZED",401);this.name="UnauthorizedError"}}});import{readFileSync as uZ}from"fs";import{basename as nZ,dirname as hZ,join as cZ,resolve as rZ}from"path";var{Glob:tZ}=globalThis.Bun;function mZ($){let w=$.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!w)throw Error("Invalid SKILL.md: missing frontmatter");let E=w[1],X=w[2].trim(),G={};for(let N of E.split(`
460
+ `)){let D=N.indexOf(":");if(D===-1)continue;G[N.slice(0,D).trim()]=N.slice(D+1).trim()}let A=(G.tags??"").replace(/^\[/,"").replace(/\]$/,"").split(",").map((N)=>N.trim()).filter(Boolean);return{frontmatter:{name:G.name??"unknown",description:G.description??"",is_skill:G.is_skill==="true",tags:A},template:X}}async function lF(){let $=f(),w=rZ(import.meta.dirname,"../../../skills/prompts"),E=new tZ("*/SKILL.md"),X=0;for await(let G of E.scan(w)){let A=cZ(w,G),N=uZ(A,"utf-8"),{frontmatter:D,template:O}=mZ(N);if(await $.query.prompts.findFirst({where:V(S0.name,D.name)}))continue;let J=new Date;await $.insert(S0).values({id:r(),name:D.name,description:D.description,template:O,is_skill:D.is_skill,tags:D.tags,skill_dir:`skills/prompts/${nZ(hZ(A))}`,version:1,pinned:!0,created_at:J,updated_at:J}),X++}if(X>0)oZ.info(`Seeded ${X} built-in prompts`)}var oZ;var sF=T(()=>{B$();z$();J$();Q$();f$();oZ=B0("runner:seed-prompts")});function aF($){return async(w,E)=>{if(!$)return E();let X=w.req.header("Authorization");if(!X?.startsWith("Bearer ")||X.slice(7)!==$)throw new I4;return E()}}var eF=T(()=>{vw()});var tD,iZ,pZ,dZ,lZ;var $j=T(()=>{Ow();fJ();tD=new m0,iZ=U.object({running:U.boolean(),status:U.string()}).openapi("GatewayStatus"),pZ=U.object({platform:U.string(),chat_id:U.string(),text:U.string(),thread_id:U.string().optional()}).openapi("GatewaySend"),dZ=i({method:"get",path:"/gateway/status",tags:["Gateway"],summary:"Get gateway status",responses:{200:{content:{"application/json":{schema:iZ}},description:"Gateway status"}}}),lZ=i({method:"post",path:"/gateway/send",tags:["Gateway"],summary:"Send a message via the gateway",request:{body:{content:{"application/json":{schema:pZ}}}},responses:{204:{description:"Message sent"},503:{content:{"application/json":{schema:U.object({error:U.string()})}},description:"Gateway not running"}}});tD.openapi(dZ,async($)=>{let w=BD()!==null;return $.json({running:w,status:CJ()})});tD.openapi(lZ,async($)=>{if(!BD())return $.json({error:"Gateway is not running"},503);let{platform:w,chat_id:E,text:X,thread_id:G}=$.req.valid("json");return await ZJ(w,E,X,G?{threadId:G}:void 0),$.body(null,204)})});var Q4,sZ,aZ;var wj=T(()=>{Ow();RN();Q4=new m0,sZ=i({method:"get",path:"/health",tags:["System"],summary:"Health check",responses:{200:{description:"Service is healthy",content:{"application/json":{schema:U.object({status:U.literal("ok"),version:U.string(),uptime:U.number()})}}}}}),aZ=Date.now();Q4.openapi(sZ,($)=>{return $.json({status:"ok",version:a1,uptime:Math.floor((Date.now()-aZ)/1000)})})});function mD($){return{...$,project_id:$.project_id??null,last_run_at:$.last_run_at?.toISOString()??null,next_run_at:$.next_run_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function YC($){return{...$,started_at:$.started_at?.toISOString()??null,ended_at:$.ended_at?.toISOString()??null,created_at:$.created_at.toISOString()}}var eZ,wE,oD,$C,wC,EC,XC,GC,AC,NC,DC,OC,WC,JC,UC;var Ej=T(()=>{Ow();vw();B$();z$();dG();J$();Q$();cE();f$();eZ=B0("api:jobs"),wE=new m0,oD=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),command:U.string(),trigger_type:KD,cron_expr:U.string().nullable(),enabled:U.boolean(),timeout_secs:U.number(),max_retries:U.number(),overlap:VD,notify_on:U.enum(["never","failure","always"]),project_id:U.string().nullable(),run_count:U.number(),last_run_at:U.string().datetime().nullable(),next_run_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Job"),$C=U.object({name:U.string().min(1).max(100),description:U.string().optional(),command:U.string().min(1),trigger_type:KD,cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional().default(300),max_retries:U.number().int().min(0).optional().default(0),overlap:VD.optional().default("skip"),notify_on:U.enum(["never","failure","always"]).optional().default("failure"),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("CreateJob"),wC=U.object({id:U.string(),job_id:U.string(),status:aL,trigger_by:U.string().nullable(),started_at:U.string().datetime().nullable(),ended_at:U.string().datetime().nullable(),exit_code:U.number().nullable(),error_msg:U.string().nullable(),retry_num:U.number(),created_at:U.string().datetime()}).openapi("JobRun"),EC=U.object({id:U.number(),run_id:U.string(),ts:U.string().datetime(),stream:U.enum(["stdout","stderr"]),line:U.string()}).openapi("JobRunLog"),XC=i({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:U.object({enabled:U.coerce.boolean().optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Jobs",content:{"application/json":{schema:U.object({jobs:U.array(oD)})}}}}}),GC=i({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get job",request:{params:U.object({id:U.string()})},responses:{200:{description:"Job",content:{"application/json":{schema:oD}}}}}),AC=i({method:"post",path:"/jobs",tags:["Jobs"],summary:"Create job",request:{body:{content:{"application/json":{schema:$C}}}},responses:{201:{description:"Created",content:{"application/json":{schema:oD}}}}}),NC=U.object({name:U.string().min(1).max(100).optional(),description:U.string().optional(),command:U.string().min(1).optional(),trigger_type:KD.optional(),cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional(),max_retries:U.number().int().min(0).optional(),overlap:VD.optional(),notify_on:U.enum(["never","failure","always"]).optional(),enabled:U.boolean().optional(),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("UpdateJob"),DC=i({method:"patch",path:"/jobs/{id}",tags:["Jobs"],summary:"Update job",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:NC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:oD}}}}}),OC=i({method:"delete",path:"/jobs/{id}",tags:["Jobs"],summary:"Delete job",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),WC=i({method:"post",path:"/jobs/{id}/trigger",tags:["Jobs"],summary:"Manually trigger a job",request:{params:U.object({id:U.string()})},responses:{202:{description:"Triggered",content:{"application/json":{schema:U.object({run_id:U.string()})}}}}}),JC=i({method:"get",path:"/jobs/{id}/runs",tags:["Jobs"],summary:"List job runs",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(50).optional().default(20)})},responses:{200:{description:"Runs",content:{"application/json":{schema:U.object({runs:U.array(wC)})}}}}}),UC=i({method:"get",path:"/jobs/{id}/runs/{runId}/logs",tags:["Jobs"],summary:"Stream log lines for a specific run",request:{params:U.object({id:U.string(),runId:U.string()}),query:U.object({stream:U.enum(["stdout","stderr"]).optional(),limit:U.coerce.number().int().min(1).max(5000).optional().default(500)})},responses:{200:{description:"Log lines",content:{"application/json":{schema:U.object({logs:U.array(EC)})}}}}});wE.openapi(XC,async($)=>{let w=f(),{limit:E,project_id:X}=$.req.valid("query"),G=[];if(X)G.push(V(I0.project_id,X));let A=await w.query.jobs.findMany({where:G.length?_0(...G):void 0,limit:E,orderBy:(N,{asc:D})=>[D(N.name)]});return $.json({jobs:A.map(mD)})});wE.openapi(GC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!X)throw new L0("Job",E);return $.json(mD(X))});wE.openapi(AC,async($)=>{let w=f(),E=$.req.valid("json"),X=new Date,G=r();await w.insert(I0).values({id:G,name:E.name,description:E.description,command:E.command,trigger_type:E.trigger_type,cron_expr:E.cron_expr,watch_path:E.watch_path,timeout_secs:E.timeout_secs,max_retries:E.max_retries,overlap:E.overlap,notify_on:E.notify_on,env_vars:E.env_vars,working_dir:E.working_dir,project_id:E.project_id,created_at:X,updated_at:X});let A=await w.query.jobs.findFirst({where:V(I0.id,G)});if(!A)throw Error("Expected job to exist after write");return $.json(mD(A),201)});wE.openapi(DC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new L0("Job",E);await w.update(I0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.command!==void 0?{command:X.command}:{},...X.trigger_type!==void 0?{trigger_type:X.trigger_type}:{},...X.cron_expr!==void 0?{cron_expr:X.cron_expr}:{},...X.watch_path!==void 0?{watch_path:X.watch_path}:{},...X.timeout_secs!==void 0?{timeout_secs:X.timeout_secs}:{},...X.max_retries!==void 0?{max_retries:X.max_retries}:{},...X.overlap!==void 0?{overlap:X.overlap}:{},...X.notify_on!==void 0?{notify_on:X.notify_on}:{},...X.enabled!==void 0?{enabled:X.enabled}:{},...X.env_vars!==void 0?{env_vars:X.env_vars}:{},...X.working_dir!==void 0?{working_dir:X.working_dir}:{},...X.project_id!==void 0?{project_id:X.project_id}:{},updated_at:new Date}).where(V(I0.id,E));let A=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!A)throw Error("Expected job to exist after write");return $.json(mD(A))});wE.openapi(OC,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new L0("Job",E);return await w.delete(I0).where(V(I0.id,E)),new Response(null,{status:204})});wE.openapi(WC,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new L0("Job",E);let G=r();return await w.insert(e0).values({id:G,job_id:E,status:"pending",trigger_by:"api",created_at:new Date}),Nw({jobId:E,runId:G,triggerBy:"api"}).catch((A)=>eZ.error(`Background execution failed for run ${G}: ${A instanceof Error?A.message:String(A)}`)),$.json({run_id:G},202)});wE.openapi(JC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query"),G=await w.query.job_runs.findMany({where:V(e0.job_id,E),limit:X,orderBy:[r0(e0.created_at)]});return $.json({runs:G.map(YC)})});wE.openapi(UC,async($)=>{let w=f(),{id:E,runId:X}=$.req.valid("param"),{stream:G,limit:A}=$.req.valid("query"),N=await w.query.job_runs.findFirst({where:V(e0.id,X)});if(!N||N.job_id!==E)throw new L0("JobRun",X);let D=await w.query.job_run_logs.findMany({where:G?_0(V(hE.run_id,X),V(hE.stream,G)):V(hE.run_id,X),limit:A,orderBy:[_N(hE.ts)]});return $.json({logs:D.map((O)=>({...O,ts:O.ts.toISOString()}))})})});function HC($,w=80){return $.length<=w?$:`${$.slice(0,w-1)}\u2026`}function LC($){let w=Date.now()-$*1000,E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function FC($,w,E){return{id:$.id,snippet:HC($.content),scope:$.scope,type:$.type??"fact",importance:$.importance,age:LC($.created_at),rank:w,matchLayer:E}}function Gj(){return f().$client}function Aj($,w,E){let X=[],G=[];if($)X.push("m.scope = ?"),G.push($);if(w)X.push("m.type = ?"),G.push(w);if(E)X.push("m.project_id = ?"),G.push(E);return{clause:X.length?` AND ${X.join(" AND ")}`:"",params:G}}function iD($,w,E,X,G,A,N){let{clause:D,params:O}=Aj(X,G,N),W=`SELECT ${V4}
440
461
  FROM ${w} f JOIN memories m ON m.id = f.id
441
462
  WHERE f.${w} MATCH ?${D}
442
- ORDER BY bm25(${w}, 0, 1.0, 3.0, 1.5, 0) LIMIT ?`;try{return $.query(W).all(E,...N,J)}catch{return[]}}function j9($,w){let E=[],X=[],G=[],J=$.replace(/"([^"]+)"/g,(N,W)=>{return E.push(`"${W}"`),""});J=J.replace(/-(\S+)/g,(N,W)=>{return X.push(W),""}),G.push(...J.trim().split(/\s+/).filter((N)=>N.length>0));let A=[...E,...G].join(` ${w} `),D=X.map((N)=>`NOT ${N}`).join(" ");return[A,D].filter(Boolean).join(" ")}function tF($,w){return j9($,w)}function R9($,w,E=10,X,G){let J=iF(),A=$.trim();if(!A)return[];let D=new Set;function N(j,M){let z=[];for(let B of j)if(!D.has(B.id))D.add(B.id),z.push(eC(B,D.size,M));return z}let W=[],O=pA(J,"memories_fts",j9(A,"AND"),w,X,E,G);if(W.push(...N(O,"porter")),W.length>=E)return A6(W.slice(0,E));let Y=pA(J,"memories_fts",j9(A,"OR"),w,X,E,G);if(W.push(...N(Y,"porter")),W.length>=E)return A6(W.slice(0,E));let H=pA(J,"memories_fts_trigram",tF(A,"AND"),w,X,E,G);if(W.push(...N(H,"trigram")),W.length>=E)return A6(W.slice(0,E));let L=pA(J,"memories_fts_trigram",tF(A,"OR"),w,X,E,G);if(W.push(...N(L,"trigram")),W.length>=E)return A6(W.slice(0,E));if(W.length===0){let{clause:j,params:M}=dF(w,X,G),z=[`%${A.toLowerCase()}%`,...M,E],B=J.query(`SELECT ${M9} FROM memories m
463
+ ORDER BY bm25(${w}, 0, 1.0, 3.0, 1.5, 0) LIMIT ?`;try{return $.query(W).all(E,...O,A)}catch{return[]}}function K4($,w){let E=[],X=[],G=[],A=$.replace(/"([^"]+)"/g,(O,W)=>{return E.push(`"${W}"`),""});A=A.replace(/-(\S+)/g,(O,W)=>{return X.push(W),""}),G.push(...A.trim().split(/\s+/).filter((O)=>O.length>0));let N=[...E,...G].join(` ${w} `),D=X.map((O)=>`NOT ${O}`).join(" ");return[N,D].filter(Boolean).join(" ")}function Xj($,w){return K4($,w)}function P4($,w,E=10,X,G){let A=Gj(),N=$.trim();if(!N)return[];let D=new Set;function O(j,M){let R=[];for(let B of j)if(!D.has(B.id))D.add(B.id),R.push(FC(B,D.size,M));return R}let W=[],J=iD(A,"memories_fts",K4(N,"AND"),w,X,E,G);if(W.push(...O(J,"porter")),W.length>=E)return YA(W.slice(0,E));let Y=iD(A,"memories_fts",K4(N,"OR"),w,X,E,G);if(W.push(...O(Y,"porter")),W.length>=E)return YA(W.slice(0,E));let H=iD(A,"memories_fts_trigram",Xj(N,"AND"),w,X,E,G);if(W.push(...O(H,"trigram")),W.length>=E)return YA(W.slice(0,E));let L=iD(A,"memories_fts_trigram",Xj(N,"OR"),w,X,E,G);if(W.push(...O(L,"trigram")),W.length>=E)return YA(W.slice(0,E));if(W.length===0){let{clause:j,params:M}=Aj(w,X,G),R=[`%${N.toLowerCase()}%`,...M,E],B=A.query(`SELECT ${V4} FROM memories m
443
464
  WHERE m.content LIKE ?${j}
444
- ORDER BY m.created_at DESC LIMIT ?`).all(...z);W.push(...N(B,"fallback"))}let F=A6(W.slice(0,E));if(F.length>0){let j=F.map((z)=>z.id),M=j.map(()=>"?").join(",");try{J.query(`UPDATE memories SET access_count = access_count + 1, last_accessed_at = unixepoch() WHERE id IN (${M})`).run(...j)}catch{}}return F}function A6($){return $.map((w,E)=>({...w,rank:E+1}))}function lF($){if($.length===0)return[];let w=iF(),E=$.map(()=>"?").join(",");return w.query(`SELECT ${M9} FROM memories m WHERE m.id IN (${E})`).all(...$).map((G)=>({id:G.id,title:G.title,type:G.type??"fact",content:G.content,source:G.source,scope:G.scope,tags:G.tags?JSON.parse(G.tags):null,importance:G.importance,created_at:new Date(G.created_at*1000).toISOString(),updated_at:new Date(G.updated_at*1000).toISOString()}))}var M9=`m.id, m.title, m.type, m.content, m.scope, m.importance,
445
- m.created_at, m.updated_at, m.source, m.tags, m.expires_at`;var sF=R(()=>{y$()});import{createHash as $_}from"crypto";function Qw($,w){let E=w||O0().activeProject;if(!E)return null;return $.query("SELECT id, name FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(E)??null}async function D6($,w){let E=x();switch($){case"memory_search":{let{query:X,scope:G,type:J,limit:A,project:D}=w,N=Qw(z$(E),D),W=R9(X,G,A,J,N?.id);if(W.length===0)return"No memories found.";let O=[`Found ${W.length} results:`];for(let Y of W){let H=Y.type!=="fact"?` [${Y.type}]`:"";O.push(`[${Y.rank}] ${Y.id}${H} "${Y.snippet}" scope:${Y.scope??"\u2014"} ${Y.age} (${Y.matchLayer})`)}return O.push(`
446
- Use memory_timeline(id) for context, memory_get([ids]) for full content.`),O.join(`
447
- `)}case"memory_get":{let{ids:X}=w,G=lF(X);if(G.length===0)return"No memories found.";return G.map((J)=>{return`${J.title?`[${J.id}] [${J.type}] "${J.title}" (${J.importance})`:`[${J.id}] [${J.type}] (${J.importance})`}
448
- ${J.content}`}).join(`
465
+ ORDER BY m.created_at DESC LIMIT ?`).all(...R);W.push(...O(B,"fallback"))}let F=YA(W.slice(0,E));if(F.length>0){let j=F.map((R)=>R.id),M=j.map(()=>"?").join(",");try{A.query(`UPDATE memories SET access_count = access_count + 1, last_accessed_at = unixepoch() WHERE id IN (${M})`).run(...j)}catch{}}return F}function YA($){return $.map((w,E)=>({...w,rank:E+1}))}function Nj($){if($.length===0)return[];let w=Gj(),E=$.map(()=>"?").join(",");return w.query(`SELECT ${V4} FROM memories m WHERE m.id IN (${E})`).all(...$).map((G)=>({id:G.id,title:G.title,type:G.type??"fact",content:G.content,source:G.source,scope:G.scope,tags:G.tags?JSON.parse(G.tags):null,importance:G.importance,created_at:new Date(G.created_at*1000).toISOString(),updated_at:new Date(G.updated_at*1000).toISOString()}))}var V4=`m.id, m.title, m.type, m.content, m.scope, m.importance,
466
+ m.created_at, m.updated_at, m.source, m.tags, m.expires_at`;var Dj=T(()=>{J$()});import{createHash as jC}from"crypto";function IE($){let w=$||G0().activeProject;if(!w)return null;return W$().query("SELECT id, name FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(w)??null}async function HA($,w){let E=f();switch($){case"memory_search":{let{query:X,scope:G,type:A,limit:N,project:D}=w,O=IE(D),W=P4(X,G,N,A,O?.id);if(W.length===0)return"No memories found.";let J=[`Found ${W.length} results:`];for(let Y of W){let H=Y.type!=="fact"?` [${Y.type}]`:"";J.push(`[${Y.rank}] ${Y.id}${H} "${Y.snippet}" scope:${Y.scope??"\u2014"} ${Y.age} (${Y.matchLayer})`)}return J.push(`
467
+ Use memory_timeline(id) for context, memory_get([ids]) for full content.`),J.join(`
468
+ `)}case"memory_get":{let{ids:X}=w,G=Nj(X);if(G.length===0)return"No memories found.";return G.map((A)=>{return`${A.title?`[${A.id}] [${A.type}] "${A.title}" (${A.importance})`:`[${A.id}] [${A.type}] (${A.importance})`}
469
+ ${A.content}`}).join(`
449
470
 
450
471
  ---
451
472
 
452
- `)}case"memory_store":{let{content:X,title:G,type:J,scope:A,tags:D,importance:N,project:W}=w,O=Qw(z$(E),W),Y=i(),H=new Date;await E.insert(H1).values({id:Y,title:G,type:J??"fact",content:X,scope:A,tags:D,importance:N??"normal",project_id:O?.id,created_at:H,updated_at:H});let L=G?` "${G}"`:"",F=O?` (${O.name})`:"";return`Stored: ${Y}${L} [${J??"fact"}]${F}`}case"task_list":{let{project:X,status:G,limit:J}=w,A=Qw(z$(E),X),D=[];if(G)D.push(V(r.status,G));if(A)D.push(V(r.project_id,A.id));let N=await E.query.tasks.findMany({where:D.length>0?S0(...D):void 0,limit:J??20,orderBy:(O,{desc:Y})=>[Y(O.updated_at)]}),W=G?N:N.filter((O)=>!["done","cancelled"].includes(O.status));if(W.length===0)return"No active tasks.";return W.map((O)=>`[${O.id}] ${O.status.padEnd(18)} ${O.priority.padEnd(8)} ${O.title}`).join(`
453
- `)}case"task_get":{let{ids:X}=w;return(await Promise.all(X.map((J)=>E.query.tasks.findFirst({where:V(r.id,J)})))).filter(Boolean).map((J)=>`[${J?.id}] ${J?.status} \u2014 ${J?.title}
454
- ${J?.body??""}`).join(`
455
-
456
- `)}case"task_create":{let{title:X,body:G,project:J,priority:A,author:D}=w,N=Qw(z$(E),J),W=i(),O=new Date;await E.insert(r).values({id:W,title:X,body:G,project_id:N?.id,priority:A??"normal",author:D??"agent",status:"todo",created_at:O,updated_at:O});let Y=N?` (${N.name})`:"";return`Created: ${W} \u2014 ${X}${Y}`}case"task_update":{let{id:X,status:G,body:J,priority:A}=w;if(G==="doing"){let N=z$(E).query(`SELECT t.id, t.title FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
457
- WHERE tl.to_task_id = ? AND tl.link_type = 'blocks' AND t.status NOT IN ('done', 'cancelled')
458
- UNION
459
- SELECT t.id, t.title FROM task_links tl JOIN tasks t ON t.id = tl.to_task_id
460
- WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by' AND t.status NOT IN ('done', 'cancelled')`).all(X,X);if(N.length>0)return`Cannot start: blocked by ${N.map((O)=>`[${O.id.slice(-6)}] ${O.title}`).join(", ")}`}if(await E.update(r).set({...G?{status:G}:{},...J!==void 0?{body:J}:{},...A?{priority:A}:{},updated_at:new Date}).where(V(r.id,X)),G&&["done","cancelled"].includes(G)){let D=z$(E),N=D.query(`SELECT DISTINCT dependent_id AS id FROM (
461
- SELECT tl.to_task_id AS dependent_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'blocks'
462
- UNION SELECT tl.from_task_id AS dependent_id FROM task_links tl WHERE tl.to_task_id = ? AND tl.link_type = 'blocked_by'
463
- )`).all(X,X);for(let O of N)if(!D.query(`SELECT 1 FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
464
- WHERE tl.to_task_id = ? AND tl.link_type = 'blocks' AND t.status NOT IN ('done','cancelled')
465
- LIMIT 1`).get(O.id)){if(D.query("SELECT status FROM tasks WHERE id = ?").get(O.id)?.status==="blocked")D.query("UPDATE tasks SET status = 'todo', updated_at = unixepoch() WHERE id = ?").run(O.id)}let W=D.query("SELECT tl.to_task_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'subtask_of' LIMIT 1").get(X);if(W){let O=D.query(`SELECT COUNT(*) as total, SUM(CASE WHEN t.status IN ('done','cancelled') THEN 1 ELSE 0 END) as done
466
- FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
467
- WHERE tl.to_task_id = ? AND tl.link_type = 'subtask_of'`).get(W.to_task_id);if(!O||O.total===0)return`Updated: ${X}`;let Y=Math.round(O.done/O.total*100);if(D.query("UPDATE tasks SET progress = ?, updated_at = unixepoch() WHERE id = ?").run(Y,W.to_task_id),O.done===O.total){let H=D.query("SELECT status FROM tasks WHERE id = ?").get(W.to_task_id);if(H&&!["done","cancelled","review"].includes(H.status))D.query("UPDATE tasks SET status = 'review', updated_at = unixepoch() WHERE id = ?").run(W.to_task_id)}}}return`Updated: ${X}`}case"task_submit_review":{let{id:X,summary:G}=w,J=await E.query.tasks.findFirst({where:V(r.id,X)}),A=J?.body?`${J.body}
468
-
469
- ---
470
- ## Review Summary
471
- ${G}`:`## Review Summary
472
- ${G}`;return await E.update(r).set({status:"review",body:A,updated_at:new Date}).where(V(r.id,X)),`Task ${X} in review. Reviewer notified if bridge configured.`}case"task_check_review":{let{id:X}=w,G=await E.query.tasks.findFirst({where:V(r.id,X)});if(!G)return`Task not found: ${X}`;return`Review status: ${{review:"pending",done:"approved",changes_requested:"changes_requested"}[G.status]??G.status}
473
- Task: ${G.title} [${G.status}]`}case"job_list":{let{limit:X,project:G}=w,J=Qw(z$(E),G),A=J?[V(I0.project_id,J.id)]:[],D=await E.query.jobs.findMany({where:A.length>0?S0(...A):void 0,limit:X??20});if(D.length===0)return"No jobs defined.";return D.map((N)=>`${N.enabled?"\u25CF":"\u25CB"} ${N.name.padEnd(24)} ${N.trigger_type.padEnd(12)} runs:${N.run_count}`).join(`
474
- `)}case"job_run":{let{name:X}=w,G=await E.query.jobs.findFirst({where:V(I0.name,X)});if(!G)return`Job not found: ${X}`;let J=i();return await E.insert(E$).values({id:J,job_id:G.id,status:"pending",trigger_by:"mcp",created_at:new Date}),A1({jobId:G.id,runId:J,triggerBy:"mcp"}).catch(()=>{}),`Triggered: ${X} \u2192 run_id: ${J}`}case"job_status":{let{run_id:X}=w,G=await E.query.job_runs.findFirst({where:V(E$.id,X)});if(!G)return`Run not found: ${X}`;return JSON.stringify({status:G.status,exit_code:G.exit_code,error:G.error_msg})}case"context":{let{project:X}=w,G=O0(),J=G.context.layer1_task_limit,A=G.context.layer1_memory_limit,D=Qw(z$(E),X),N=[];if(D)N.push(V(r.project_id,D.id));let O=(await E.query.tasks.findMany({where:N.length>0?S0(...N):void 0,limit:J,orderBy:(k,{desc:v})=>[v(k.updated_at)]})).filter((k)=>!["done","cancelled"].includes(k.status)),Y=[];if(D)Y.push(V(H1.project_id,D.id));let H=await E.query.memories.findMany({where:Y.length>0?S0(...Y):void 0,limit:A*3,orderBy:(k,{desc:v})=>[v(k.created_at)]}),L={critical:4,high:3,normal:2,low:1},F={rule:3,decision:3,discovery:2,fact:1,event:1},j=Date.now(),M=H.map((k)=>{let v=(j-k.created_at.getTime())/3600000,C=Math.max(0,1-v/720),n=(L[k.importance]??1)*2+(F[k.type??"fact"]??1)+C*2;return{m:k,score:n}});M.sort((k,v)=>v.score-k.score);let z=M.slice(0,A).map((k)=>k.m),B=await E.query.sessions.findFirst({orderBy:[x0(C1.created_at)]}),Q=[];if(D)Q.push(`## Project: ${D.name}`);if(Q.push(D?`
475
- ## Active Tasks`:"## Active Tasks"),O.length===0)Q.push(" (none)");for(let k of O)Q.push(` [${k.id}] ${k.status.padEnd(10)} ${k.title}`);if(Q.push(`
476
- ## Key Memory`),z.length===0)Q.push(" (none)");for(let k of z){let v=k.type!=="fact"?` [${k.type}]`:"",C=k.title?` "${k.title}"`:"";Q.push(` [${k.id}]${v}${C} ${k.content.slice(0,60)} (${E_(k.created_at)})`)}if(B?.summary)Q.push(`
477
- ## Last Session (${B.agent})`),Q.push(` ${B.summary}`);return Q.push(`
478
- Use task_get([ids]) or memory_get([ids]) for full content.`),Q.join(`
479
- `)}case"session_event":{let{session_id:X,type:G,priority:J,data:A}=w,D=z$(E),N=X??process.env.ORC_SESSION_ID??"default",W=JSON.stringify(A),O=$_("sha256").update(W).digest("hex").slice(0,16);if(D.query(`SELECT data_hash FROM session_events
473
+ `)}case"memory_store":{let{content:X,title:G,type:A,scope:N,tags:D,importance:O,project:W}=w,J=IE(W),Y=r(),H=new Date;await E.insert(Hw).values({id:Y,title:G,type:A??"fact",content:X,scope:N,tags:D,importance:O??"normal",project_id:J?.id,created_at:H,updated_at:H});let L=G?` "${G}"`:"",F=J?` (${J.name})`:"";return`Stored: ${Y}${L} [${A??"fact"}]${F}`}case"task_list":{let{project:X,status:G,limit:A}=w,N=IE(X),D=[];if(G)D.push(V(t.status,G));if(N)D.push(V(t.project_id,N.id));let O=await E.query.tasks.findMany({where:D.length>0?_0(...D):void 0,limit:A??20,orderBy:(J,{desc:Y})=>[Y(J.updated_at)]}),W=G?O:O.filter((J)=>!["done","cancelled"].includes(J.status));if(W.length===0)return"No active tasks.";return W.map((J)=>`[${J.id}] ${J.status.padEnd(18)} ${J.priority.padEnd(8)} ${J.title}`).join(`
474
+ `)}case"task_get":{let{ids:X}=w;return(await Promise.all(X.map((A)=>E.query.tasks.findFirst({where:V(t.id,A)})))).filter(Boolean).map((A)=>`[${A?.id}] ${A?.status} \u2014 ${A?.title}
475
+ ${A?.body??""}`).join(`
476
+
477
+ `)}case"task_create":{let{title:X,body:G,project:A,priority:N,author:D,tags:O,prompt_id:W,required_review:J,agent_backend:Y,max_review_rounds:H}=w,L=IE(A),F=r(),j=new Date;await E.insert(t).values({id:F,title:X,body:G,project_id:L?.id,priority:N??"normal",author:D??"agent",status:"todo",tags:O,prompt_id:W,required_review:J??!0,agent_backend:Y,max_review_rounds:H??3,created_at:j,updated_at:j});let M=L?` (${L.name})`:"";return`Created: ${F} \u2014 ${X}${M}`}case"task_update":{let{id:X,status:G,body:A,priority:N,comment:D}=w;if(G){let O=await IX({taskId:X,status:G,comment:D,author:"agent"});if(!O.ok)return O.error??"Transition failed"}else if(D)await oE(X,D,"agent");if(A!==void 0||N)await E.update(t).set({...A!==void 0?{body:A}:{},...N?{priority:N}:{},updated_at:new Date}).where(V(t.id,X));return`Updated: ${X}`}case"job_list":{let{limit:X,project:G}=w,A=IE(G),N=A?[V(I0.project_id,A.id)]:[],D=await E.query.jobs.findMany({where:N.length>0?_0(...N):void 0,limit:X??20});if(D.length===0)return"No jobs defined.";return D.map((O)=>`${O.enabled?"\u25CF":"\u25CB"} ${O.name.padEnd(24)} ${O.trigger_type.padEnd(12)} runs:${O.run_count}`).join(`
478
+ `)}case"job_run":{let{name:X}=w,G=await E.query.jobs.findFirst({where:V(I0.name,X)});if(!G)return`Job not found: ${X}`;let A=r();return await E.insert(e0).values({id:A,job_id:G.id,status:"pending",trigger_by:"mcp",created_at:new Date}),Nw({jobId:G.id,runId:A,triggerBy:"mcp"}).catch(()=>{}),`Triggered: ${X} \u2192 run_id: ${A}`}case"job_status":{let{run_id:X}=w,G=await E.query.job_runs.findFirst({where:V(e0.id,X)});if(!G)return`Run not found: ${X}`;return JSON.stringify({status:G.status,exit_code:G.exit_code,error:G.error_msg})}case"context":{let{project:X}=w,G=G0(),A=G.context.layer1_task_limit,N=G.context.layer1_memory_limit,D=IE(X),O=[];if(D)O.push(V(t.project_id,D.id));let J=(await E.query.tasks.findMany({where:O.length>0?_0(...O):void 0,limit:A,orderBy:(k,{desc:n})=>[n(k.updated_at)]})).filter((k)=>!["done","cancelled"].includes(k.status)),Y=[];if(D)Y.push(V(Hw.project_id,D.id));let H=await E.query.memories.findMany({where:Y.length>0?_0(...Y):void 0,limit:N*3,orderBy:(k,{desc:n})=>[n(k.created_at)]}),L={critical:4,high:3,normal:2,low:1},F={rule:3,decision:3,discovery:2,fact:1,event:1},j=Date.now(),M=H.map((k)=>{let n=(j-k.created_at.getTime())/3600000,H0=Math.max(0,1-n/720),b0=(L[k.importance]??1)*2+(F[k.type??"fact"]??1)+H0*2;return{m:k,score:b0}});M.sort((k,n)=>n.score-k.score);let R=M.slice(0,N).map((k)=>k.m),B=await E.query.sessions.findFirst({orderBy:[r0(_w.created_at)]}),I=[];if(D)I.push(`## Project: ${D.name}`);if(I.push(D?`
479
+ ## Active Tasks`:"## Active Tasks"),J.length===0)I.push(" (none)");for(let k of J)I.push(` [${k.id}] ${k.status.padEnd(10)} ${k.title}`);if(I.push(`
480
+ ## Key Memory`),R.length===0)I.push(" (none)");for(let k of R){let n=k.type!=="fact"?` [${k.type}]`:"",H0=k.title?` "${k.title}"`:"";I.push(` [${k.id}]${n}${H0} ${k.content.slice(0,60)} (${TC(k.created_at)})`)}if(B?.summary)I.push(`
481
+ ## Last Session (${B.agent})`),I.push(` ${B.summary}`);let v=W$().query("SELECT COUNT(*) as count FROM gateway_sessions WHERE role = 'worker' AND status = 'running'").get();if(v&&v.count>0)I.push(`
482
+ ## Agent Loop: ${v.count} active worker(s)`);return I.push(`
483
+ Use task_get([ids]) or memory_get([ids]) for full content.`),I.join(`
484
+ `)}case"session_event":{let{session_id:X,type:G,priority:A,data:N}=w,D=W$(),O=X??process.env.ORC_SESSION_ID??"default",W=JSON.stringify(N),J=jC("sha256").update(W).digest("hex").slice(0,16);if(D.query(`SELECT data_hash FROM session_events
480
485
  WHERE session_id = ? AND type = ?
481
- ORDER BY created_at DESC LIMIT ?`).all(N,G,5).some((F)=>F.data_hash===O))return"Duplicate event skipped.";let{n:H}=D.query("SELECT COUNT(*) as n FROM session_events WHERE session_id = ?").get(N)??{n:0};if(H>=1000)D.query(`DELETE FROM session_events WHERE id = (
486
+ ORDER BY created_at DESC LIMIT ?`).all(O,G,5).some((F)=>F.data_hash===J))return"Duplicate event skipped.";let{n:H}=D.query("SELECT COUNT(*) as n FROM session_events WHERE session_id = ?").get(O)??{n:0};if(H>=1000)D.query(`DELETE FROM session_events WHERE id = (
482
487
  SELECT id FROM session_events WHERE session_id = ?
483
488
  ORDER BY priority ASC, created_at ASC LIMIT 1
484
- )`).run(N);let L=i();return D.query("INSERT INTO session_events(id, session_id, type, priority, data, data_hash) VALUES (?,?,?,?,?,?)").run(L,N,G,J??3,W,O),`Event recorded: ${L}`}case"session_snapshot":{let{session_id:X}=w,J=O0().context.snapshot_max_bytes,A=X??process.env.ORC_SESSION_ID??"default",N=(await E.query.tasks.findMany({limit:10,orderBy:(L,{desc:F})=>[F(L.updated_at)]})).filter((L)=>!["done","cancelled"].includes(L.status)),W=z$(E),O=W.query(`SELECT type, priority, data FROM session_events
489
+ )`).run(O);let L=r();return D.query("INSERT INTO session_events(id, session_id, type, priority, data, data_hash) VALUES (?,?,?,?,?,?)").run(L,O,G,A??3,W,J),`Event recorded: ${L}`}case"session_snapshot":{let{session_id:X}=w,A=G0().context.snapshot_max_bytes,N=X??process.env.ORC_SESSION_ID??"default",O=(await E.query.tasks.findMany({limit:10,orderBy:(L,{desc:F})=>[F(L.updated_at)]})).filter((L)=>!["done","cancelled"].includes(L.status)),W=W$(),J=W.query(`SELECT type, priority, data FROM session_events
485
490
  WHERE session_id = ?
486
- ORDER BY priority ASC, created_at DESC LIMIT 100`).all(A),Y=w_(N,O,J),H=i();return W.query("INSERT INTO session_snapshots(id, session_id, xml) VALUES (?,?,?)").run(H,A,Y),Y}case"session_restore":{let{session_id:X}=w,G=X??process.env.ORC_SESSION_ID??"default",A=z$(E).query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(G);if(!A)return"No session snapshot found. Starting fresh.";return`## Session Restored
487
-
488
- ${A.xml}`}case"session_log":{let{agent:X,agent_version:G,summary:J,session_id:A,project:D}=w,N=Qw(z$(E),D),W=A??process.env.ORC_SESSION_ID??"default",O=process.env.ORC_JOB_RUN_ID,H=z$(E).query("SELECT type, data FROM session_events WHERE session_id = ? ORDER BY created_at ASC").all(W),L=new Set,F=new Set,j=new Set;for(let Q of H)try{let k=JSON.parse(Q.data);if(Q.type==="file"&&k.path)L.add(k.path);if(Q.type==="task"&&k.id)F.add(k.id);if(Q.type==="memory"&&k.id)j.add(k.id)}catch{}let M=[J];if(L.size>0)M.push(`Files: ${[...L].join(", ")}`);if(F.size>0)M.push(`Tasks: ${[...F].join(", ")}`);if(j.size>0)M.push(`Memories: ${[...j].join(", ")}`);let z=M.join(`
489
- `),B=i();return await E.insert(C1).values({id:B,agent:X,agent_version:G,summary:z,project_id:N?.id,job_run_id:O,created_at:new Date}),`Session logged: ${B}`}case"project_list":{let{status:X}=w,G=X?[V(n0.status,X)]:[],J=await E.query.projects.findMany({where:G.length>0?S0(...G):void 0,orderBy:(A,{asc:D})=>[D(A.name)]});if(J.length===0)return"No projects found.";return J.map((A)=>{let D=A.description?` ${A.description.slice(0,60)}`:"";return`${A.name.padEnd(24)} ${A.status}${D}`}).join(`
490
- `)}case"task_batch_create":{let{tasks:X,project:G,author:J}=w,A=Qw(z$(E),G),D=new Date,N={};for(let Y of X){let H=i();N[Y.ref]=H,await E.insert(r).values({id:H,title:Y.title,body:Y.body,project_id:A?.id,priority:Y.priority??"normal",author:J??"agent",status:"todo",created_at:D,updated_at:D})}let W=z$(E);for(let Y of X){let H=N[Y.ref];if(Y.depends_on)for(let L of Y.depends_on){let F=N[L];if(!F)continue;W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'blocks', unixepoch())").run(i(),F,H)}if(Y.subtask_of){let L=N[Y.subtask_of];if(L)W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'subtask_of', unixepoch())").run(i(),H,L),W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'parent_of', unixepoch())").run(i(),L,H)}}let O=X.map((Y)=>` ${Y.ref} \u2192 ${N[Y.ref]} \u2014 ${Y.title}`);return`Created ${X.length} tasks:
491
- ${O.join(`
492
- `)}`}case"search":{let{query:X,resources:G,project:J,limit:A}=w,D=Qw(z$(E),J),N=A??10,W=[];if(!G||G.includes("memories")){let O=R9(X,void 0,Math.ceil(N/2),void 0,D?.id);if(O.length>0){W.push("## Memories");for(let Y of O)W.push(` [memory] ${Y.id} [${Y.type}] ${Y.snippet} (${Y.age})`)}}if(!G||G.includes("tasks")){let O=z$(E),Y=X.trim().split(/\s+/).filter((F)=>F.length>0),H=Math.ceil(N/2),L=[];if(Y.length>0)try{let F=Y.join(" AND "),j="SELECT t.id, t.title, t.status FROM tasks_fts f JOIN tasks t ON t.id = f.id WHERE f.tasks_fts MATCH ?",M=[F];if(D)j+=" AND t.project_id = ?",M.push(D.id);j+=" ORDER BY rank LIMIT ?",M.push(H),L=O.query(j).all(...M)}catch{let F=`SELECT id, title, status FROM tasks WHERE (title LIKE ? OR body LIKE ?)${D?" AND project_id = ?":""} ORDER BY updated_at DESC LIMIT ?`,j=[`%${X}%`,`%${X}%`];if(D)j.push(D.id);j.push(H),L=O.query(F).all(...j)}if(L.length>0){W.push("## Tasks");for(let F of L)W.push(` [task] ${F.id} ${F.status} \u2014 ${F.title}`)}}return W.length>0?W.join(`
493
- `):"No results found."}default:return`Unknown tool: ${$}`}}function z$($){return $.$client}function w_($,w,E){let X=$.map((O)=>` <task id="${O.id.slice(-6)}" status="${O.status}" priority="${O.priority}">${$j(O.title)}</task>`).join(`
494
- `),G=w.filter((O)=>aF.has(O.type)),J=w.filter((O)=>eF.has(O.type)),A=w.filter((O)=>!aF.has(O.type)&&!eF.has(O.type));function D(O,Y=5){let H={};for(let L of O.slice(0,Y*3)){if(!H[L.type])H[L.type]=[];let F=H[L.type]??[];if(F.length>=Y)continue;try{let j=JSON.parse(L.data);F.push(Object.entries(j).map(([M,z])=>`${M}=${String(z).slice(0,80)}`).join(" "))}catch{F.push(String(L.data).slice(0,120))}}return Object.entries(H).map(([L,F])=>` <${L}s>${F.map((j)=>`<item>${$j(j)}</item>`).join("")}</${L}s>`).join(`
495
- `)}function N(O,Y){let H=[`<tasks>
491
+ ORDER BY priority ASC, created_at DESC LIMIT 100`).all(N),Y=MC(O,J,A),H=r();return W.query("INSERT INTO session_snapshots(id, session_id, xml) VALUES (?,?,?)").run(H,N,Y),Y}case"session_restore":{let{session_id:X}=w,G=X??process.env.ORC_SESSION_ID??"default",N=W$().query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(G);if(!N)return"No session snapshot found. Starting fresh.";return`## Session Restored
492
+
493
+ ${N.xml}`}case"session_log":{let{agent:X,agent_version:G,summary:A,session_id:N,project:D}=w,O=IE(D),W=N??process.env.ORC_SESSION_ID??"default",J=process.env.ORC_JOB_RUN_ID,H=W$().query("SELECT type, data FROM session_events WHERE session_id = ? ORDER BY created_at ASC").all(W),L=new Set,F=new Set,j=new Set;for(let I of H)try{let C=JSON.parse(I.data);if(I.type==="file"&&C.path)L.add(C.path);if(I.type==="task"&&C.id)F.add(C.id);if(I.type==="memory"&&C.id)j.add(C.id)}catch{}let M=[A];if(L.size>0)M.push(`Files: ${[...L].join(", ")}`);if(F.size>0)M.push(`Tasks: ${[...F].join(", ")}`);if(j.size>0)M.push(`Memories: ${[...j].join(", ")}`);let R=M.join(`
494
+ `),B=r();return await E.insert(_w).values({id:B,agent:X,agent_version:G,summary:R,project_id:O?.id,job_run_id:J,created_at:new Date}),`Session logged: ${B}`}case"project_list":{let{status:X}=w,G=X?[V(y0.status,X)]:[],A=await E.query.projects.findMany({where:G.length>0?_0(...G):void 0,orderBy:(N,{asc:D})=>[D(N.name)]});if(A.length===0)return"No projects found.";return A.map((N)=>{let D=N.description?` ${N.description.slice(0,60)}`:"";return`${N.name.padEnd(24)} ${N.status}${D}`}).join(`
495
+ `)}case"task_batch_create":{let{tasks:X,project:G,author:A}=w,N=IE(G),D=new Date,O={};for(let Y of X){let H=r();O[Y.ref]=H,await E.insert(t).values({id:H,title:Y.title,body:Y.body,project_id:N?.id,priority:Y.priority??"normal",author:A??"agent",status:"todo",tags:Y.tags,prompt_id:Y.prompt_id,required_review:Y.required_review??!0,agent_backend:Y.agent_backend,max_review_rounds:Y.max_review_rounds??3,created_at:D,updated_at:D})}let W=W$();for(let Y of X){let H=O[Y.ref];if(Y.depends_on)for(let L of Y.depends_on){let F=O[L];if(!F)continue;W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'blocks', unixepoch())").run(r(),F,H)}if(Y.subtask_of){let L=O[Y.subtask_of];if(L)W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'subtask_of', unixepoch())").run(r(),H,L),W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'parent_of', unixepoch())").run(r(),L,H)}}let J=X.map((Y)=>` ${Y.ref} \u2192 ${O[Y.ref]} \u2014 ${Y.title}`);return`Created ${X.length} tasks:
496
+ ${J.join(`
497
+ `)}`}case"search":{let{query:X,resources:G,project:A,limit:N}=w,D=IE(A),O=N??10,W=[];if(!G||G.includes("memories")){let J=P4(X,void 0,Math.ceil(O/2),void 0,D?.id);if(J.length>0){W.push("## Memories");for(let Y of J)W.push(` [memory] ${Y.id} [${Y.type}] ${Y.snippet} (${Y.age})`)}}if(!G||G.includes("tasks")){let J=W$(),Y=X.trim().split(/\s+/).filter((F)=>F.length>0),H=Math.ceil(O/2),L=[];if(Y.length>0)try{let F=Y.join(" AND "),j="SELECT t.id, t.title, t.status FROM tasks_fts f JOIN tasks t ON t.id = f.id WHERE f.tasks_fts MATCH ?",M=[F];if(D)j+=" AND t.project_id = ?",M.push(D.id);j+=" ORDER BY rank LIMIT ?",M.push(H),L=J.query(j).all(...M)}catch{let F=`SELECT id, title, status FROM tasks WHERE (title LIKE ? OR body LIKE ?)${D?" AND project_id = ?":""} ORDER BY updated_at DESC LIMIT ?`,j=[`%${X}%`,`%${X}%`];if(D)j.push(D.id);j.push(H),L=J.query(F).all(...j)}if(L.length>0){W.push("## Tasks");for(let F of L)W.push(` [task] ${F.id} ${F.status} \u2014 ${F.title}`)}}return W.length>0?W.join(`
498
+ `):"No results found."}case"prompt_list":{let{tags:X,is_skill:G}=w,A=[];if(G!==void 0)A.push(V(S0.is_skill,G));let N=await E.query.prompts.findMany({where:A.length>0?_0(...A):void 0,orderBy:(O,{asc:W})=>[W(O.name)]}),D=N;if(X&&X.length>0)D=N.filter((O)=>{let W=O.tags??[];return X.some((J)=>W.includes(J))});if(D.length===0)return"No prompts found.";return D.map((O)=>{let W=O.is_skill?" [skill]":"",J=O.description?` \u2014 ${O.description.slice(0,60)}`:"";return`${O.name.padEnd(28)}${W}${J}`}).join(`
499
+ `)}case"prompt_get":{let{name:X,id:G}=w,A;if(G)A=await E.query.prompts.findFirst({where:V(S0.id,G)});else if(X)A=await E.query.prompts.findFirst({where:V(S0.name,X)});else return"Provide either name or id.";if(!A)return`Prompt not found: ${X??G}`;return`# ${A.name}
500
+ ${A.description??""}
501
+
502
+ ${A.template}`}default:return`Unknown tool: ${$}`}}function MC($,w,E){let X=$.map((J)=>` <task id="${J.id.slice(-6)}" status="${J.status}" priority="${J.priority}">${Jj(J.title)}</task>`).join(`
503
+ `),G=w.filter((J)=>Oj.has(J.type)),A=w.filter((J)=>Wj.has(J.type)),N=w.filter((J)=>!Oj.has(J.type)&&!Wj.has(J.type));function D(J,Y=5){let H={};for(let L of J.slice(0,Y*3)){if(!H[L.type])H[L.type]=[];let F=H[L.type]??[];if(F.length>=Y)continue;try{let j=JSON.parse(L.data);F.push(Object.entries(j).map(([M,R])=>`${M}=${String(R).slice(0,80)}`).join(" "))}catch{F.push(String(L.data).slice(0,120))}}return Object.entries(H).map(([L,F])=>` <${L}s>${F.map((j)=>`<item>${Jj(j)}</item>`).join("")}</${L}s>`).join(`
504
+ `)}function O(J,Y){let H=[`<tasks>
496
505
  ${X}
497
506
  </tasks>`],L=D(G);if(L)H.push(`<context priority="high">
498
507
  ${L}
499
- </context>`);if(O){let F=D(J);if(F)H.push(`<context priority="normal">
508
+ </context>`);if(J){let F=D(A);if(F)H.push(`<context priority="normal">
500
509
  ${F}
501
- </context>`)}if(Y){let F=D(A,3);if(F)H.push(`<context priority="low">
510
+ </context>`)}if(Y){let F=D(N,3);if(F)H.push(`<context priority="low">
502
511
  ${F}
503
512
  </context>`)}return`<session>
504
513
  ${H.join(`
505
514
  `)}
506
- </session>`}let W=[[!0,!0],[!0,!1],[!1,!1]];for(let[O,Y]of W){let H=N(O,Y);if(Buffer.byteLength(H)<=E)return H}return`<session>
515
+ </session>`}let W=[[!0,!0],[!0,!1],[!1,!1]];for(let[J,Y]of W){let H=O(J,Y);if(Buffer.byteLength(H)<=E)return H}return`<session>
507
516
  <tasks>
508
517
  ${X}
509
518
  </tasks>
510
- </session>`}function $j($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function E_($){let w=Date.now()-$.getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}var Bw,qX,aF,eF;var oA=R(()=>{C$();X1();y$();d$();nw();i$();OG();sF();Bw=U.string().optional().describe("Project name (e.g. 'orc'). Defaults to activeProject from config if not set."),qX=[{name:"memory_search",description:"Search memories (3-layer BM25: porter \u2192 trigram \u2192 fallback). Returns compact index: IDs + snippets. "+"Filter by type (fact|decision|event|rule|discovery) or scope. Use memory_get for full content.",inputSchema:U.object({query:U.string().describe("Search query \u2014 keywords, phrases, or natural language"),scope:U.string().optional().describe("Scope filter (e.g. domain area)"),type:U.enum(["fact","decision","event","rule","discovery"]).optional().describe("Filter by memory type"),project:Bw,limit:U.number().int().min(1).max(20).optional().default(10)})},{name:"memory_get",description:"Fetch full content of specific memories by IDs. Always batch multiple IDs in one call. "+"~10x more token-expensive than memory_search \u2014 only call after filtering by ID.",inputSchema:U.object({ids:U.array(U.string()).min(1).max(20).describe("Memory IDs to fetch")})},{name:"memory_store",description:"Store a fact, decision, or context entry. Use type to classify: 'decision' for choices made, 'rule' for conventions/constraints, 'discovery' for findings, 'event' for things that happened, 'fact' for general knowledge.",inputSchema:U.object({content:U.string().describe("Content to remember"),title:U.string().optional().describe("Short label (\u226460 chars) for quick scanning"),type:U.enum(["fact","decision","event","rule","discovery"]).optional().default("fact"),scope:U.string().optional().describe("Scope (e.g. domain area)"),tags:U.array(U.string()).optional(),importance:U.enum(["low","normal","high","critical"]).optional().default("normal"),project:Bw})},{name:"task_list",description:"List active tasks \u2014 compact layer-1 index. Does NOT include body/comments.",inputSchema:U.object({project:Bw,status:U.enum(["todo","doing","review","changes_requested","blocked"]).optional(),limit:U.number().int().min(1).max(50).optional().default(20)})},{name:"task_get",description:"Fetch full details of specific tasks by IDs (body, comments, full history).",inputSchema:U.object({ids:U.array(U.string()).min(1).max(10)})},{name:"task_create",description:"Create a new task.",inputSchema:U.object({title:U.string(),body:U.string().optional(),project:Bw,priority:U.enum(["low","normal","high","critical"]).optional().default("normal"),author:U.string().optional().default("agent")})},{name:"task_update",description:"Update task status, priority, or body.",inputSchema:U.object({id:U.string(),status:U.enum(["todo","doing","review","changes_requested","blocked","done","cancelled"]).optional(),body:U.string().optional(),priority:U.enum(["low","normal","high","critical"]).optional()})},{name:"task_submit_review",description:"Submit task for human review (HITL checkpoint). Sets status=review, sends Telegram card if configured.",inputSchema:U.object({id:U.string(),summary:U.string().describe("Summary of work done for the reviewer")})},{name:"task_check_review",description:"Poll HITL review result. Returns: pending | approved | changes_requested + comment.",inputSchema:U.object({id:U.string()})},{name:"task_batch_create",description:"Create multiple tasks with dependency links atomically. Use for PRD-to-task workflows. Each task has a 'ref' (temporary ID like 'T1') used to express dependencies between tasks in the batch.",inputSchema:U.object({tasks:U.array(U.object({ref:U.string().describe("Temporary reference ID, e.g. 'T1'"),title:U.string(),body:U.string().optional(),priority:U.enum(["low","normal","high","critical"]).optional().default("normal"),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")})).min(1).max(100),project:Bw,author:U.string().optional().default("agent")})},{name:"search",description:"Unified search across tasks and memories. Returns mixed results with resource_type indicator. Use instead of separate memory_search + task_search calls.",inputSchema:U.object({query:U.string().describe("Search query"),resources:U.array(U.enum(["tasks","memories"])).optional().default(["tasks","memories"]),project:Bw,limit:U.number().int().min(1).max(20).optional().default(10)})},{name:"job_list",description:"List all jobs with last run status.",inputSchema:U.object({limit:U.number().int().optional().default(20),project:Bw})},{name:"job_run",description:"Trigger a job by name.",inputSchema:U.object({name:U.string()})},{name:"job_status",description:"Get run status + exit code + error for a specific run ID.",inputSchema:U.object({run_id:U.string()})},{name:"context",description:"Compact context index \u2014 active tasks + important memories. ~200 tokens. Call at session start. "+"Pass project name to scope, or omit to use activeProject from config. Use task_get or memory_get to drill into specific items.",inputSchema:U.object({project:Bw})},{name:"session_event",description:"Record a session event (file edit, decision, error, git op) for continuity across compaction. Duplicate events are silently deduped. Priority: 1=critical (file/task/rule), 2=high (git/env/error/decision), 3=normal, 4=low.",inputSchema:U.object({session_id:U.string().optional(),type:U.enum(["file","task","decision","error","git","env","intent","rule","plan","subagent"]),priority:U.number().int().min(1).max(4).optional().default(3),data:U.record(U.string()).describe("Event payload \u2014 tool, path, content, etc.")})},{name:"session_snapshot",description:"Build \u22642KB XML snapshot of current session state. Call from PreCompact hook before context window compacts.",inputSchema:U.object({session_id:U.string().optional()})},{name:"session_restore",description:"Restore session state after compaction or agent restart. Returns structured Session Guide.",inputSchema:U.object({session_id:U.string().optional()})},{name:"session_log",description:"Log a session summary after completing a unit of work. Auto-derives touched files, task changes, and stored memories from session events.",inputSchema:U.object({agent:U.string(),agent_version:U.string().optional().describe("Agent version string, e.g. 'claude-code/1.x'"),summary:U.string(),session_id:U.string().optional(),project:Bw})},{name:"project_list",description:"List all projects. Returns name, status, and description for each.",inputSchema:U.object({status:U.enum(["active","archived","paused"]).optional()})}];aF=new Set(["file","task","rule"]),eF=new Set(["decision","git","env","error","plan"])});var z9,X_;var wj=R(()=>{N1();x1();oA();z9=new p0,X_=m({method:"post",path:"/mcp/tool",tags:["MCP"],summary:"Execute an MCP tool by name \u2014 used by hook scripts",request:{body:{content:{"application/json":{schema:U.object({name:U.string().min(1),args:U.record(U.unknown()).optional().default({})}).openapi("McpToolCall")}}}},responses:{200:{description:"Tool result",content:{"application/json":{schema:U.object({result:U.string()}).openapi("McpToolResult")}}}}});z9.openapi(X_,async($)=>{let{name:w,args:E}=$.req.valid("json"),X=qX.find((A)=>A.name===w);if(!X)throw new Ew(`Unknown MCP tool: ${w}`);let G=X.inputSchema.safeParse(E??{});if(!G.success)throw new Ew(`Invalid args: ${G.error.message}`);let J=await D6(w,G.data);return $.json({result:J})})});function Ej($){return{id:$.id,title:$.title??null,type:$.type??"fact",content:$.content,source:$.source,scope:$.scope,project_id:$.project_id??null,tags:$.tags?JSON.parse($.tags):null,importance:$.importance,expires_at:$.expires_at?new Date($.expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function W_($){return{id:$.id,title:$.title??null,type:$.type??"fact",content:$.content,source:$.source??null,scope:$.scope??null,project_id:$.project_id??null,tags:$.tags??null,importance:$.importance,expires_at:$.expires_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}var SX,tA,B9,G_,J_,A_,D_,N_,T9=`m.id, m.title, m.type, m.content, m.source, m.scope, m.project_id, m.tags,
511
- m.importance, m.expires_at, m.created_at, m.updated_at`;var Xj=R(()=>{N1();x1();X1();y$();d$();i$();SX=new p0,tA=U.enum(["fact","decision","event","rule","discovery"]),B9=U.object({id:U.string(),title:U.string().nullable(),type:tA,content:U.string(),source:U.string().nullable(),scope:U.string().nullable(),project_id:U.string().nullable(),tags:U.array(U.string()).nullable(),importance:U.enum(["low","normal","high","critical"]),expires_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Memory"),G_=U.object({content:U.string().min(1),title:U.string().optional(),type:tA.optional().default("fact"),source:U.string().optional(),scope:U.string().optional(),project_id:U.string().optional(),tags:U.array(U.string()).optional(),importance:U.enum(["low","normal","high","critical"]).optional().default("normal"),expires_at:U.string().datetime().optional()}).openapi("CreateMemory"),J_=m({method:"get",path:"/memories/search",tags:["Memory"],summary:"Search memories (3-layer BM25: porter \u2192 trigram \u2192 fallback)",request:{query:U.object({q:U.string().min(1),scope:U.string().optional(),type:tA.optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(50).optional().default(10)})},responses:{200:{description:"Search results",content:{"application/json":{schema:U.object({results:U.array(B9)})}}}}}),A_=m({method:"get",path:"/memories",tags:["Memory"],summary:"List memories",request:{query:U.object({scope:U.string().optional(),type:tA.optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Memory list",content:{"application/json":{schema:U.object({memories:U.array(B9)})}}}}}),D_=m({method:"post",path:"/memories",tags:["Memory"],summary:"Store a memory",request:{body:{content:{"application/json":{schema:G_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:B9}}}}}),N_=m({method:"delete",path:"/memories/{id}",tags:["Memory"],summary:"Delete memory",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}});SX.openapi(J_,async($)=>{let w=x(),{q:E,scope:X,type:G,project_id:J,limit:A}=$.req.valid("query"),D=w.$client,N=E.replace(/["]/g," ").trim(),W=X?" AND m.scope = ?":"",O=G?" AND m.type = ?":"",Y=J?" AND m.project_id = ?":"",H=[...X?[X]:[],...G?[G]:[],...J?[J]:[]],L=[],F=(B,Q)=>{try{return D.query(`SELECT ${T9} FROM ${B} f JOIN memories m ON m.id = f.id
512
- WHERE f.${B} MATCH ?${W}${O}${Y} ORDER BY rank LIMIT ?`).all(Q,...H,A)}catch{return[]}},j=N.split(/\s+/).filter(Boolean),M=j.join(" AND "),z=j.join(" OR ");if(L=F("memories_fts",M),L.length===0)L=F("memories_fts",z);if(L.length===0)L=F("memories_fts_trigram",M);if(L.length===0)L=F("memories_fts_trigram",z);if(L.length===0){let B=[`%${N.toLowerCase()}%`,...H,A];L=D.query(`SELECT ${T9} FROM memories m
513
- WHERE m.content LIKE ?${W}${O}${Y}
514
- ORDER BY m.created_at DESC LIMIT ?`).all(...B)}return $.json({results:L.map(Ej)})});SX.openapi(A_,async($)=>{let w=x(),{scope:E,type:X,project_id:G,limit:J}=$.req.valid("query"),A=w.$client,D=[],N=[];if(E)D.push("scope = ?"),N.push(E);if(X)D.push("type = ?"),N.push(X);if(G)D.push("project_id = ?"),N.push(G);N.push(J);let W=D.length?`WHERE ${D.join(" AND ")}`:"",O=A.query(`SELECT ${T9} FROM memories m ${W} ORDER BY m.created_at DESC LIMIT ?`).all(...N);return $.json({memories:O.map(Ej)})});SX.openapi(D_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(H1).values({id:G,title:E.title,type:E.type??"fact",content:E.content,source:E.source,scope:E.scope,project_id:E.project_id,tags:E.tags,importance:E.importance,expires_at:E.expires_at?new Date(E.expires_at):void 0,created_at:X,updated_at:X});let J=await w.query.memories.findFirst({where:V(H1.id,G)});return $.json(W_(J),201)});SX.openapi(N_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.memories.findFirst({where:V(H1.id,E)}))throw new U0("Memory",E);return await w.delete(H1).where(V(H1.id,E)),new Response(null,{status:204})})});function N6($){return{...$,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function Gj($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Aj($){return{...$,created_at:$.created_at.toISOString()}}var y1,kX,O_,U_,Y_,H_,L_,F_,j_,M_,R_,Jj,z_,T_;var Dj=R(()=>{N1();x1();X1();y$();d$();i$();y1=new p0,kX=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),status:U.enum(["active","archived","paused"]),scope:U.string().nullable(),tags:U.array(U.string()).nullable(),obsidian_path:U.string().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Project"),O_=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional().default("active"),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional()}).openapi("CreateProject"),U_=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100).optional(),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional(),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional()}).openapi("UpdateProject"),Y_=m({method:"get",path:"/projects",tags:["Projects"],summary:"List projects",request:{query:U.object({status:U.enum(["active","archived","paused"]).optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Projects",content:{"application/json":{schema:U.object({projects:U.array(kX)})}}}}}),H_=m({method:"get",path:"/projects/{id}",tags:["Projects"],summary:"Get project by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:kX}}}}}),L_=m({method:"post",path:"/projects",tags:["Projects"],summary:"Create project",request:{body:{content:{"application/json":{schema:O_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:kX}}}}}),F_=m({method:"patch",path:"/projects/{id}",tags:["Projects"],summary:"Update project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:kX}}}}}),j_=m({method:"delete",path:"/projects/{id}",tags:["Projects"],summary:"Delete project",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),M_=m({method:"get",path:"/projects/by-name/{name}",tags:["Projects"],summary:"Get project by name (case-insensitive)",request:{params:U.object({name:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:kX}}}}}),R_=m({method:"get",path:"/projects/{id}/summary",tags:["Projects"],summary:"Get project summary with task/memory/job counts",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project summary",content:{"application/json":{schema:U.object({project:kX,tasks:U.object({total:U.number(),by_status:U.record(U.number())}),memories:U.number(),jobs:U.number()})}}}}});y1.openapi(Y_,async($)=>{let w=x(),{status:E,tag:X,limit:G}=$.req.valid("query");if(X){let D=w.$client,N="SELECT DISTINCT p.* FROM projects p, json_each(p.tags) AS j WHERE j.value = ?",W=[X];if(E)N+=" AND p.status = ?",W.push(E);N+=" ORDER BY p.name ASC LIMIT ?",W.push(G);let Y=D.query(N).all(...W).map(Gj);return $.json({projects:Y})}let J=E?[V(n0.status,E)]:[],A=await w.query.projects.findMany({where:J.length>0?S0(...J):void 0,limit:G,orderBy:(D,{asc:N})=>[N(D.name)]});return $.json({projects:A.map(N6)})});y1.openapi(M_,async($)=>{let w=x(),{name:E}=$.req.valid("param"),G=w.$client.query("SELECT * FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(E);if(!G)throw new U0("Project",E);return $.json(Gj(G))});y1.openapi(R_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(n0.id,E)});if(!X)throw new U0("Project",E);let G=w.$client,J=G.query("SELECT status, COUNT(*) as count FROM tasks WHERE project_id = ? GROUP BY status").all(E),A={},D=0;for(let O of J)A[O.status]=O.count,D+=O.count;let N=G.query("SELECT COUNT(*) as count FROM memories WHERE project_id = ?").get(E)?.count??0,W=G.query("SELECT COUNT(*) as count FROM jobs WHERE project_id = ?").get(E)?.count??0;return $.json({project:N6(X),tasks:{total:D,by_status:A},memories:N,jobs:W})});y1.openapi(H_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(n0.id,E)});if(!X)throw new U0("Project",E);return $.json(N6(X))});y1.openapi(L_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(n0).values({id:G,name:E.name,description:E.description,status:E.status,scope:E.scope,tags:E.tags,obsidian_path:E.obsidian_path,created_at:X,updated_at:X});let J=await w.query.projects.findFirst({where:V(n0.id,G)});if(!J)throw Error("Expected project to exist after write");return $.json(N6(J),201)});y1.openapi(F_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);await w.update(n0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.status!==void 0?{status:X.status}:{},...X.scope!==void 0?{scope:X.scope}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.obsidian_path!==void 0?{obsidian_path:X.obsidian_path}:{},updated_at:new Date}).where(V(n0.id,E));let J=await w.query.projects.findFirst({where:V(n0.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(N6(J))});y1.openapi(j_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);return await w.delete(n0).where(V(n0.id,E)),new Response(null,{status:204})});Jj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("ProjectComment"),z_=m({method:"get",path:"/projects/{id}/comments",tags:["Projects"],summary:"List project comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(Jj)})}}}}}),T_=m({method:"post",path:"/projects/{id}/comments",tags:["Projects"],summary:"Add a comment to a project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddProjectComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:Jj}}}}});y1.openapi(z_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);let G=await w.query.comments.findMany({where:S0(V(G$.resource_type,"project"),V(G$.resource_id,E)),orderBy:[x0(G$.created_at)]});return $.json({comments:G.map(Aj)})});y1.openapi(T_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);let A=i(),D=new Date;await w.insert(G$).values({id:A,resource_type:"project",resource_id:E,content:X,author:G,created_at:D});let N=await w.query.comments.findFirst({where:V(G$.id,A)});if(!N)throw Error("Expected comment to exist after write");return $.json(Aj(N),201)})});function dA($){return{...$,last_used_at:$.last_used_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function C_($,w){return $.replace(/\{\{(\w+)\}\}/g,(E,X)=>w[X]??`{{${X}}}`)}function __($){return{...$,changed_at:$.changed_at.toISOString()}}var Iw,iA,B_,Q_,I_,K_,V_,P_,q_,S_,k_,b_,Z_;var Nj=R(()=>{N1();x1();X1();y$();d$();i$();Iw=new p0,iA=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),template:U.string(),is_skill:U.boolean(),skill_dir:U.string().nullable(),skill_version:U.string().nullable(),tags:U.array(U.string()).nullable(),version:U.number(),pinned:U.boolean(),last_used_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Prompt"),B_=U.object({name:U.string().min(1).max(200),description:U.string().optional(),template:U.string().min(1),is_skill:U.boolean().optional().default(!1),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional().default(!1)}).openapi("CreatePrompt"),Q_=U.object({name:U.string().min(1).max(200).optional(),description:U.string().optional(),template:U.string().min(1).optional(),is_skill:U.boolean().optional(),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional()}).openapi("UpdatePrompt"),I_=U.object({vars:U.record(U.string()).optional().default({})}).openapi("RenderPrompt"),K_=m({method:"get",path:"/prompts",tags:["Prompts"],summary:"List prompts",request:{query:U.object({is_skill:U.coerce.boolean().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Prompts",content:{"application/json":{schema:U.object({prompts:U.array(iA)})}}}}}),V_=m({method:"get",path:"/prompts/{id}",tags:["Prompts"],summary:"Get prompt by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Prompt",content:{"application/json":{schema:iA}}}}}),P_=m({method:"post",path:"/prompts",tags:["Prompts"],summary:"Create prompt",request:{body:{content:{"application/json":{schema:B_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:iA}}}}}),q_=m({method:"patch",path:"/prompts/{id}",tags:["Prompts"],summary:"Update prompt (bumps version)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:Q_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:iA}}}}}),S_=m({method:"delete",path:"/prompts/{id}",tags:["Prompts"],summary:"Delete prompt",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),k_=m({method:"post",path:"/prompts/{id}/render",tags:["Prompts"],summary:"Render prompt with variable interpolation",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:I_}}}},responses:{200:{description:"Rendered",content:{"application/json":{schema:U.object({rendered:U.string(),prompt_id:U.string(),version:U.number()}).openapi("RenderedPrompt")}}}}}),b_=U.object({id:U.string(),prompt_id:U.string(),version:U.number(),name:U.string(),description:U.string().nullable(),template:U.string(),tags:U.array(U.string()).nullable(),changed_by:U.string(),changed_at:U.string().datetime()}).openapi("PromptHistoryEntry"),Z_=m({method:"get",path:"/prompts/{id}/history",tags:["Prompts"],summary:"List prompt version history (newest first)",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"History",content:{"application/json":{schema:U.object({history:U.array(b_)})}}}}});Iw.openapi(K_,async($)=>{let w=x(),{is_skill:E,limit:X}=$.req.valid("query"),G=await w.query.prompts.findMany({where:E!==void 0?V(D$.is_skill,E):void 0,limit:X,orderBy:(J,{asc:A})=>[A(J.name)]});return $.json({prompts:G.map(dA)})});Iw.openapi(V_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!X)throw new U0("Prompt",E);return $.json(dA(X))});Iw.openapi(P_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(D$).values({id:G,name:E.name,description:E.description,template:E.template,is_skill:E.is_skill,skill_dir:E.skill_dir,skill_version:E.skill_version,tags:E.tags,pinned:E.pinned,created_at:X,updated_at:X});let J=await w.query.prompts.findFirst({where:V(D$.id,G)});if(!J)throw Error("Expected prompt to exist after write");return $.json(dA(J),201)});Iw.openapi(q_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!G)throw new U0("Prompt",E);await w.insert(ZG).values({id:i(),prompt_id:G.id,version:G.version,name:G.name,description:G.description,template:G.template,tags:G.tags,changed_by:"human",changed_at:new Date}),await w.update(D$).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.template!==void 0?{template:X.template}:{},...X.is_skill!==void 0?{is_skill:X.is_skill}:{},...X.skill_dir!==void 0?{skill_dir:X.skill_dir}:{},...X.skill_version!==void 0?{skill_version:X.skill_version}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.pinned!==void 0?{pinned:X.pinned}:{},version:G.version+1,updated_at:new Date}).where(V(D$.id,E));let J=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(dA(J))});Iw.openapi(S_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.prompts.findFirst({where:V(D$.id,E)}))throw new U0("Prompt",E);return await w.delete(D$).where(V(D$.id,E)),new Response(null,{status:204})});Iw.openapi(k_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{vars:X}=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!G)throw new U0("Prompt",E);return await w.update(D$).set({last_used_at:new Date}).where(V(D$.id,E)),$.json({rendered:C_(G.template,X??{}),prompt_id:G.id,version:G.version})});Iw.openapi(Z_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query");if(!await w.query.prompts.findFirst({where:V(D$.id,E)}))throw new U0("Prompt",E);let J=await w.query.prompt_history.findMany({where:V(ZG.prompt_id,E),limit:X,orderBy:[x0(ZG.version)]});return $.json({history:J.map(__)})})});function Oj($){return{id:$.id,agent:$.agent,agent_version:$.agent_version??null,project_id:$.project_id??null,job_run_id:$.job_run_id??null,summary:$.summary??null,tokens_used:$.tokens_used??null,created_at:$.created_at.toISOString()}}var lA,Wj,v_,f_,x_;var Uj=R(()=>{N1();x1();y$();d$();i$();lA=new p0,Wj=U.object({id:U.string(),agent:U.string(),agent_version:U.string().nullable(),project_id:U.string().nullable(),job_run_id:U.string().nullable(),summary:U.string().nullable(),tokens_used:U.number().nullable(),created_at:U.string().datetime()}).openapi("Session"),v_=Wj.extend({events:U.array(U.object({id:U.string(),type:U.string(),priority:U.number(),data:U.string(),created_at:U.string().datetime()})),snapshot:U.string().nullable()}).openapi("SessionDetail"),f_=m({method:"get",path:"/sessions",tags:["Sessions"],summary:"List recent sessions",request:{query:U.object({agent:U.string().optional(),job_run_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Sessions list",content:{"application/json":{schema:U.object({sessions:U.array(Wj)})}}}}}),x_=m({method:"get",path:"/sessions/{id}",tags:["Sessions"],summary:"Get session detail with events",request:{params:U.object({id:U.string()})},responses:{200:{description:"Session detail",content:{"application/json":{schema:v_}}},404:{description:"Not found"}}});lA.openapi(f_,async($)=>{let w=x(),{agent:E,job_run_id:X,limit:G}=$.req.valid("query"),J=[];if(E)J.push(V(C1.agent,E));if(X)J.push(V(C1.job_run_id,X));let A=await w.query.sessions.findMany({limit:G,orderBy:[x0(C1.created_at)],where:J.length>0?S0(...J):void 0});return $.json({sessions:A.map(Oj)})});lA.openapi(x_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.sessions.findFirst({where:V(C1.id,E)});if(!X)throw new U0("Session",E);let G=w.$client,J=G.query(`SELECT id, type, priority, data, created_at
519
+ </session>`}function Jj($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function TC($){let w=Date.now()-$.getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}var BE,_X,Oj,Wj;var pD=T(()=>{R$();B$();J$();Q$();cE();PD();f$();LG();Dj();BE=U.string().optional().describe("Project name (e.g. 'orc'). Defaults to activeProject from config if not set."),_X=[{name:"memory_search",description:"Search memories (3-layer BM25: porter \u2192 trigram \u2192 fallback). Returns compact index: IDs + snippets. "+"Filter by type (fact|decision|event|rule|discovery) or scope. Use memory_get for full content.",inputSchema:U.object({query:U.string().describe("Search query \u2014 keywords, phrases, or natural language"),scope:U.string().optional().describe("Scope filter (e.g. domain area)"),type:U.enum(["fact","decision","event","rule","discovery"]).optional().describe("Filter by memory type"),project:BE,limit:U.number().int().min(1).max(20).optional().default(10)})},{name:"memory_get",description:"Fetch full content of specific memories by IDs. Always batch multiple IDs in one call. "+"~10x more token-expensive than memory_search \u2014 only call after filtering by ID.",inputSchema:U.object({ids:U.array(U.string()).min(1).max(20).describe("Memory IDs to fetch")})},{name:"memory_store",description:"Store a fact, decision, or context entry. Use type to classify: 'decision' for choices made, 'rule' for conventions/constraints, 'discovery' for findings, 'event' for things that happened, 'fact' for general knowledge.",inputSchema:U.object({content:U.string().describe("Content to remember"),title:U.string().optional().describe("Short label (\u226460 chars) for quick scanning"),type:U.enum(["fact","decision","event","rule","discovery"]).optional().default("fact"),scope:U.string().optional().describe("Scope (e.g. domain area)"),tags:U.array(U.string()).optional(),importance:U.enum(["low","normal","high","critical"]).optional().default("normal"),project:BE})},{name:"task_list",description:"List active tasks \u2014 compact layer-1 index. Does NOT include body/comments.",inputSchema:U.object({project:BE,status:U.enum(["todo","queued","doing","review","changes_requested","blocked","paused"]).optional(),limit:U.number().int().min(1).max(50).optional().default(20)})},{name:"task_get",description:"Fetch full details of specific tasks by IDs (body, comments, full history).",inputSchema:U.object({ids:U.array(U.string()).min(1).max(10)})},{name:"task_create",description:"Create a new task.",inputSchema:U.object({title:U.string(),body:U.string().optional(),project:BE,priority:U.enum(["low","normal","high","critical"]).optional().default("normal"),author:U.string().optional().default("agent"),tags:U.array(U.string()).optional(),prompt_id:U.string().optional().describe("Prompt template to use for agent execution"),required_review:U.boolean().optional().default(!0).describe("Require human review before done"),agent_backend:U.enum(["claude","codex","cursor"]).optional().describe("Agent backend for task execution"),max_review_rounds:U.number().int().min(1).optional().default(3).describe("Max review iterations before pausing")})},{name:"task_update",description:"Update task status, priority, body, or add a comment. Status transitions are validated.",inputSchema:U.object({id:U.string(),status:U.enum(["todo","queued","doing","review","changes_requested","blocked","done","paused","cancelled"]).optional(),body:U.string().optional(),priority:U.enum(["low","normal","high","critical"]).optional(),comment:U.string().optional().describe("Add a comment to the task")})},{name:"task_batch_create",description:"Create multiple tasks with dependency links atomically. Use for PRD-to-task workflows. Each task has a 'ref' (temporary ID like 'T1') used to express dependencies between tasks in the batch.",inputSchema:U.object({tasks:U.array(U.object({ref:U.string().describe("Temporary reference ID, e.g. 'T1'"),title:U.string(),body:U.string().optional(),priority:U.enum(["low","normal","high","critical"]).optional().default("normal"),tags:U.array(U.string()).optional(),prompt_id:U.string().optional(),required_review:U.boolean().optional().default(!0),agent_backend:U.enum(["claude","codex","cursor"]).optional(),max_review_rounds:U.number().int().min(1).optional().default(3),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")})).min(1).max(100),project:BE,author:U.string().optional().default("agent")})},{name:"search",description:"Unified search across tasks and memories. Returns mixed results with resource_type indicator. Use instead of separate memory_search + task_search calls.",inputSchema:U.object({query:U.string().describe("Search query"),resources:U.array(U.enum(["tasks","memories"])).optional().default(["tasks","memories"]),project:BE,limit:U.number().int().min(1).max(20).optional().default(10)})},{name:"job_list",description:"List all jobs with last run status.",inputSchema:U.object({limit:U.number().int().optional().default(20),project:BE})},{name:"job_run",description:"Trigger a job by name.",inputSchema:U.object({name:U.string()})},{name:"job_status",description:"Get run status + exit code + error for a specific run ID.",inputSchema:U.object({run_id:U.string()})},{name:"context",description:"Compact context index \u2014 active tasks + important memories. ~200 tokens. Call at session start. "+"Pass project name to scope, or omit to use activeProject from config. Use task_get or memory_get to drill into specific items.",inputSchema:U.object({project:BE})},{name:"session_event",description:"Record a session event (file edit, decision, error, git op) for continuity across compaction. Duplicate events are silently deduped. Priority: 1=critical (file/task/rule), 2=high (git/env/error/decision), 3=normal, 4=low.",inputSchema:U.object({session_id:U.string().optional(),type:U.enum(["file","task","decision","error","git","env","intent","rule","plan","subagent"]),priority:U.number().int().min(1).max(4).optional().default(3),data:U.record(U.string()).describe("Event payload \u2014 tool, path, content, etc.")})},{name:"session_snapshot",description:"Build \u22642KB XML snapshot of current session state. Call from PreCompact hook before context window compacts.",inputSchema:U.object({session_id:U.string().optional()})},{name:"session_restore",description:"Restore session state after compaction or agent restart. Returns structured Session Guide.",inputSchema:U.object({session_id:U.string().optional()})},{name:"session_log",description:"Log a session summary after completing a unit of work. Auto-derives touched files, task changes, and stored memories from session events.",inputSchema:U.object({agent:U.string(),agent_version:U.string().optional().describe("Agent version string, e.g. 'claude-code/1.x'"),summary:U.string(),session_id:U.string().optional(),project:BE})},{name:"project_list",description:"List all projects. Returns name, status, and description for each.",inputSchema:U.object({status:U.enum(["active","archived","paused"]).optional()})},{name:"prompt_list",description:"Discover available prompts and skills. Returns name + description for each.",inputSchema:U.object({tags:U.array(U.string()).optional().describe("Filter by tags"),is_skill:U.boolean().optional().describe("Filter by skill flag")})},{name:"prompt_get",description:"Load full prompt content by name or ID.",inputSchema:U.object({name:U.string().optional().describe("Prompt name"),id:U.string().optional().describe("Prompt ID (alternative to name)")})}];Oj=new Set(["file","task","rule"]),Wj=new Set(["decision","git","env","error","plan"])});var q4,RC;var Uj=T(()=>{Ow();vw();pD();q4=new m0,RC=i({method:"post",path:"/mcp/tool",tags:["MCP"],summary:"Execute an MCP tool by name \u2014 used by hook scripts",request:{body:{content:{"application/json":{schema:U.object({name:U.string().min(1),args:U.record(U.unknown()).optional().default({})}).openapi("McpToolCall")}}}},responses:{200:{description:"Tool result",content:{"application/json":{schema:U.object({result:U.string()}).openapi("McpToolResult")}}}}});q4.openapi(RC,async($)=>{let{name:w,args:E}=$.req.valid("json"),X=_X.find((N)=>N.name===w);if(!X)throw new zE(`Unknown MCP tool: ${w}`);let G=X.inputSchema.safeParse(E??{});if(!G.success)throw new zE(`Invalid args: ${G.error.message}`);let A=await HA(w,G.data);return $.json({result:A})})});function Yj($){return{id:$.id,title:$.title??null,type:$.type??"fact",content:$.content,source:$.source,scope:$.scope,project_id:$.project_id??null,tags:$.tags?JSON.parse($.tags):null,importance:$.importance,expires_at:$.expires_at?new Date($.expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function VC($){return{id:$.id,title:$.title??null,type:$.type??"fact",content:$.content,source:$.source??null,scope:$.scope??null,project_id:$.project_id??null,tags:$.tags??null,importance:$.importance,expires_at:$.expires_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}var ZX,dD,k4,zC,BC,IC,QC,KC,S4=`m.id, m.title, m.type, m.content, m.source, m.scope, m.project_id, m.tags,
520
+ m.importance, m.expires_at, m.created_at, m.updated_at`;var Hj=T(()=>{Ow();vw();B$();J$();Q$();f$();ZX=new m0,dD=U.enum(["fact","decision","event","rule","discovery"]),k4=U.object({id:U.string(),title:U.string().nullable(),type:dD,content:U.string(),source:U.string().nullable(),scope:U.string().nullable(),project_id:U.string().nullable(),tags:U.array(U.string()).nullable(),importance:U.enum(["low","normal","high","critical"]),expires_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Memory"),zC=U.object({content:U.string().min(1),title:U.string().optional(),type:dD.optional().default("fact"),source:U.string().optional(),scope:U.string().optional(),project_id:U.string().optional(),tags:U.array(U.string()).optional(),importance:U.enum(["low","normal","high","critical"]).optional().default("normal"),expires_at:U.string().datetime().optional()}).openapi("CreateMemory"),BC=i({method:"get",path:"/memories/search",tags:["Memory"],summary:"Search memories (3-layer BM25: porter \u2192 trigram \u2192 fallback)",request:{query:U.object({q:U.string().min(1),scope:U.string().optional(),type:dD.optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(50).optional().default(10)})},responses:{200:{description:"Search results",content:{"application/json":{schema:U.object({results:U.array(k4)})}}}}}),IC=i({method:"get",path:"/memories",tags:["Memory"],summary:"List memories",request:{query:U.object({scope:U.string().optional(),type:dD.optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Memory list",content:{"application/json":{schema:U.object({memories:U.array(k4)})}}}}}),QC=i({method:"post",path:"/memories",tags:["Memory"],summary:"Store a memory",request:{body:{content:{"application/json":{schema:zC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:k4}}}}}),KC=i({method:"delete",path:"/memories/{id}",tags:["Memory"],summary:"Delete memory",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}});ZX.openapi(BC,async($)=>{let w=f(),{q:E,scope:X,type:G,project_id:A,limit:N}=$.req.valid("query"),D=w.$client,O=E.replace(/["]/g," ").trim(),W=X?" AND m.scope = ?":"",J=G?" AND m.type = ?":"",Y=A?" AND m.project_id = ?":"",H=[...X?[X]:[],...G?[G]:[],...A?[A]:[]],L=[],F=(B,I)=>{try{return D.query(`SELECT ${S4} FROM ${B} f JOIN memories m ON m.id = f.id
521
+ WHERE f.${B} MATCH ?${W}${J}${Y} ORDER BY rank LIMIT ?`).all(I,...H,N)}catch{return[]}},j=O.split(/\s+/).filter(Boolean),M=j.join(" AND "),R=j.join(" OR ");if(L=F("memories_fts",M),L.length===0)L=F("memories_fts",R);if(L.length===0)L=F("memories_fts_trigram",M);if(L.length===0)L=F("memories_fts_trigram",R);if(L.length===0){let B=[`%${O.toLowerCase()}%`,...H,N];L=D.query(`SELECT ${S4} FROM memories m
522
+ WHERE m.content LIKE ?${W}${J}${Y}
523
+ ORDER BY m.created_at DESC LIMIT ?`).all(...B)}return $.json({results:L.map(Yj)})});ZX.openapi(IC,async($)=>{let w=f(),{scope:E,type:X,project_id:G,limit:A}=$.req.valid("query"),N=w.$client,D=[],O=[];if(E)D.push("scope = ?"),O.push(E);if(X)D.push("type = ?"),O.push(X);if(G)D.push("project_id = ?"),O.push(G);O.push(A);let W=D.length?`WHERE ${D.join(" AND ")}`:"",J=N.query(`SELECT ${S4} FROM memories m ${W} ORDER BY m.created_at DESC LIMIT ?`).all(...O);return $.json({memories:J.map(Yj)})});ZX.openapi(QC,async($)=>{let w=f(),E=$.req.valid("json"),X=new Date,G=r();await w.insert(Hw).values({id:G,title:E.title,type:E.type??"fact",content:E.content,source:E.source,scope:E.scope,project_id:E.project_id,tags:E.tags,importance:E.importance,expires_at:E.expires_at?new Date(E.expires_at):void 0,created_at:X,updated_at:X});let A=await w.query.memories.findFirst({where:V(Hw.id,G)});return $.json(VC(A),201)});ZX.openapi(KC,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.memories.findFirst({where:V(Hw.id,E)}))throw new L0("Memory",E);return await w.delete(Hw).where(V(Hw.id,E)),new Response(null,{status:204})})});function LA($){return{...$,max_workers:$.max_workers??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function Lj($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function jj($){return{...$,created_at:$.created_at.toISOString()}}var xw,CX,PC,qC,SC,kC,bC,_C,ZC,CC,fC,Fj,vC,xC;var Mj=T(()=>{Ow();vw();B$();J$();Q$();f$();xw=new m0,CX=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),status:U.enum(["active","archived","paused"]),scope:U.string().nullable(),tags:U.array(U.string()).nullable(),obsidian_path:U.string().nullable(),max_workers:U.number().int().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Project"),PC=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional().default("active"),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional(),max_workers:U.number().int().min(1).optional()}).openapi("CreateProject"),qC=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100).optional(),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional(),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional(),max_workers:U.number().int().min(1).nullable().optional()}).openapi("UpdateProject"),SC=i({method:"get",path:"/projects",tags:["Projects"],summary:"List projects",request:{query:U.object({status:U.enum(["active","archived","paused"]).optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Projects",content:{"application/json":{schema:U.object({projects:U.array(CX)})}}}}}),kC=i({method:"get",path:"/projects/{id}",tags:["Projects"],summary:"Get project by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:CX}}}}}),bC=i({method:"post",path:"/projects",tags:["Projects"],summary:"Create project",request:{body:{content:{"application/json":{schema:PC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:CX}}}}}),_C=i({method:"patch",path:"/projects/{id}",tags:["Projects"],summary:"Update project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:qC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:CX}}}}}),ZC=i({method:"delete",path:"/projects/{id}",tags:["Projects"],summary:"Delete project",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),CC=i({method:"get",path:"/projects/by-name/{name}",tags:["Projects"],summary:"Get project by name (case-insensitive)",request:{params:U.object({name:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:CX}}}}}),fC=i({method:"get",path:"/projects/{id}/summary",tags:["Projects"],summary:"Get project summary with task/memory/job counts",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project summary",content:{"application/json":{schema:U.object({project:CX,tasks:U.object({total:U.number(),by_status:U.record(U.number())}),memories:U.number(),jobs:U.number()})}}}}});xw.openapi(SC,async($)=>{let w=f(),{status:E,tag:X,limit:G}=$.req.valid("query");if(X){let D=w.$client,O="SELECT DISTINCT p.* FROM projects p, json_each(p.tags) AS j WHERE j.value = ?",W=[X];if(E)O+=" AND p.status = ?",W.push(E);O+=" ORDER BY p.name ASC LIMIT ?",W.push(G);let Y=D.query(O).all(...W).map(Lj);return $.json({projects:Y})}let A=E?[V(y0.status,E)]:[],N=await w.query.projects.findMany({where:A.length>0?_0(...A):void 0,limit:G,orderBy:(D,{asc:O})=>[O(D.name)]});return $.json({projects:N.map(LA)})});xw.openapi(CC,async($)=>{let w=f(),{name:E}=$.req.valid("param"),G=w.$client.query("SELECT * FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(E);if(!G)throw new L0("Project",E);return $.json(Lj(G))});xw.openapi(fC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(y0.id,E)});if(!X)throw new L0("Project",E);let G=w.$client,A=G.query("SELECT status, COUNT(*) as count FROM tasks WHERE project_id = ? GROUP BY status").all(E),N={},D=0;for(let J of A)N[J.status]=J.count,D+=J.count;let O=G.query("SELECT COUNT(*) as count FROM memories WHERE project_id = ?").get(E)?.count??0,W=G.query("SELECT COUNT(*) as count FROM jobs WHERE project_id = ?").get(E)?.count??0;return $.json({project:LA(X),tasks:{total:D,by_status:N},memories:O,jobs:W})});xw.openapi(kC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(y0.id,E)});if(!X)throw new L0("Project",E);return $.json(LA(X))});xw.openapi(bC,async($)=>{let w=f(),E=$.req.valid("json"),X=new Date,G=r();await w.insert(y0).values({id:G,name:E.name,description:E.description,status:E.status,scope:E.scope,tags:E.tags,obsidian_path:E.obsidian_path,max_workers:E.max_workers,created_at:X,updated_at:X});let A=await w.query.projects.findFirst({where:V(y0.id,G)});if(!A)throw Error("Expected project to exist after write");return $.json(LA(A),201)});xw.openapi(_C,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(y0.id,E)}))throw new L0("Project",E);await w.update(y0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.status!==void 0?{status:X.status}:{},...X.scope!==void 0?{scope:X.scope}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.obsidian_path!==void 0?{obsidian_path:X.obsidian_path}:{},...X.max_workers!==void 0?{max_workers:X.max_workers}:{},updated_at:new Date}).where(V(y0.id,E));let A=await w.query.projects.findFirst({where:V(y0.id,E)});if(!A)throw Error("Expected updated to exist after write");return $.json(LA(A))});xw.openapi(ZC,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(y0.id,E)}))throw new L0("Project",E);return await w.delete(y0).where(V(y0.id,E)),new Response(null,{status:204})});Fj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("ProjectComment"),vC=i({method:"get",path:"/projects/{id}/comments",tags:["Projects"],summary:"List project comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(Fj)})}}}}}),xC=i({method:"post",path:"/projects/{id}/comments",tags:["Projects"],summary:"Add a comment to a project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddProjectComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:Fj}}}}});xw.openapi(vC,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(y0.id,E)}))throw new L0("Project",E);let G=await w.query.comments.findMany({where:_0(V(F$.resource_type,"project"),V(F$.resource_id,E)),orderBy:[r0(F$.created_at)]});return $.json({comments:G.map(jj)})});xw.openapi(xC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(y0.id,E)}))throw new L0("Project",E);let N=r(),D=new Date;await w.insert(F$).values({id:N,resource_type:"project",resource_id:E,content:X,author:G,created_at:D});let O=await w.query.comments.findFirst({where:V(F$.id,N)});if(!O)throw Error("Expected comment to exist after write");return $.json(jj(O),201)})});function sD($){return{...$,last_used_at:$.last_used_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function pC($,w){return $.replace(/\{\{(\w+)\}\}/g,(E,X)=>w[X]??`{{${X}}}`)}function dC($){return{...$,changed_at:$.changed_at.toISOString()}}var QE,lD,yC,gC,uC,nC,hC,cC,rC,tC,oC,mC,iC;var Tj=T(()=>{Ow();vw();B$();J$();Q$();f$();QE=new m0,lD=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),template:U.string(),is_skill:U.boolean(),skill_dir:U.string().nullable(),skill_version:U.string().nullable(),tags:U.array(U.string()).nullable(),version:U.number(),pinned:U.boolean(),last_used_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Prompt"),yC=U.object({name:U.string().min(1).max(200),description:U.string().optional(),template:U.string().min(1),is_skill:U.boolean().optional().default(!1),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional().default(!1)}).openapi("CreatePrompt"),gC=U.object({name:U.string().min(1).max(200).optional(),description:U.string().optional(),template:U.string().min(1).optional(),is_skill:U.boolean().optional(),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional()}).openapi("UpdatePrompt"),uC=U.object({vars:U.record(U.string()).optional().default({})}).openapi("RenderPrompt"),nC=i({method:"get",path:"/prompts",tags:["Prompts"],summary:"List prompts",request:{query:U.object({is_skill:U.coerce.boolean().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Prompts",content:{"application/json":{schema:U.object({prompts:U.array(lD)})}}}}}),hC=i({method:"get",path:"/prompts/{id}",tags:["Prompts"],summary:"Get prompt by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Prompt",content:{"application/json":{schema:lD}}}}}),cC=i({method:"post",path:"/prompts",tags:["Prompts"],summary:"Create prompt",request:{body:{content:{"application/json":{schema:yC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:lD}}}}}),rC=i({method:"patch",path:"/prompts/{id}",tags:["Prompts"],summary:"Update prompt (bumps version)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:gC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:lD}}}}}),tC=i({method:"delete",path:"/prompts/{id}",tags:["Prompts"],summary:"Delete prompt",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),oC=i({method:"post",path:"/prompts/{id}/render",tags:["Prompts"],summary:"Render prompt with variable interpolation",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:uC}}}},responses:{200:{description:"Rendered",content:{"application/json":{schema:U.object({rendered:U.string(),prompt_id:U.string(),version:U.number()}).openapi("RenderedPrompt")}}}}}),mC=U.object({id:U.string(),prompt_id:U.string(),version:U.number(),name:U.string(),description:U.string().nullable(),template:U.string(),tags:U.array(U.string()).nullable(),changed_by:U.string(),changed_at:U.string().datetime()}).openapi("PromptHistoryEntry"),iC=i({method:"get",path:"/prompts/{id}/history",tags:["Prompts"],summary:"List prompt version history (newest first)",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"History",content:{"application/json":{schema:U.object({history:U.array(mC)})}}}}});QE.openapi(nC,async($)=>{let w=f(),{is_skill:E,limit:X}=$.req.valid("query"),G=await w.query.prompts.findMany({where:E!==void 0?V(S0.is_skill,E):void 0,limit:X,orderBy:(A,{asc:N})=>[N(A.name)]});return $.json({prompts:G.map(sD)})});QE.openapi(hC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=await w.query.prompts.findFirst({where:V(S0.id,E)});if(!X)throw new L0("Prompt",E);return $.json(sD(X))});QE.openapi(cC,async($)=>{let w=f(),E=$.req.valid("json"),X=new Date,G=r();await w.insert(S0).values({id:G,name:E.name,description:E.description,template:E.template,is_skill:E.is_skill,skill_dir:E.skill_dir,skill_version:E.skill_version,tags:E.tags,pinned:E.pinned,created_at:X,updated_at:X});let A=await w.query.prompts.findFirst({where:V(S0.id,G)});if(!A)throw Error("Expected prompt to exist after write");return $.json(sD(A),201)});QE.openapi(rC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(S0.id,E)});if(!G)throw new L0("Prompt",E);await w.insert(vG).values({id:r(),prompt_id:G.id,version:G.version,name:G.name,description:G.description,template:G.template,tags:G.tags,changed_by:"human",changed_at:new Date}),await w.update(S0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.template!==void 0?{template:X.template}:{},...X.is_skill!==void 0?{is_skill:X.is_skill}:{},...X.skill_dir!==void 0?{skill_dir:X.skill_dir}:{},...X.skill_version!==void 0?{skill_version:X.skill_version}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.pinned!==void 0?{pinned:X.pinned}:{},version:G.version+1,updated_at:new Date}).where(V(S0.id,E));let A=await w.query.prompts.findFirst({where:V(S0.id,E)});if(!A)throw Error("Expected updated to exist after write");return $.json(sD(A))});QE.openapi(tC,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.prompts.findFirst({where:V(S0.id,E)}))throw new L0("Prompt",E);return await w.delete(S0).where(V(S0.id,E)),new Response(null,{status:204})});QE.openapi(oC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),{vars:X}=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(S0.id,E)});if(!G)throw new L0("Prompt",E);return await w.update(S0).set({last_used_at:new Date}).where(V(S0.id,E)),$.json({rendered:pC(G.template,X??{}),prompt_id:G.id,version:G.version})});QE.openapi(iC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query");if(!await w.query.prompts.findFirst({where:V(S0.id,E)}))throw new L0("Prompt",E);let A=await w.query.prompt_history.findMany({where:V(vG.prompt_id,E),limit:X,orderBy:[r0(vG.version)]});return $.json({history:A.map(dC)})})});function zj($){return{id:$.id,agent:$.agent,agent_version:$.agent_version??null,project_id:$.project_id??null,job_run_id:$.job_run_id??null,summary:$.summary??null,tokens_used:$.tokens_used??null,created_at:$.created_at.toISOString()}}var aD,Rj,lC,sC,aC;var Bj=T(()=>{Ow();vw();J$();Q$();f$();aD=new m0,Rj=U.object({id:U.string(),agent:U.string(),agent_version:U.string().nullable(),project_id:U.string().nullable(),job_run_id:U.string().nullable(),summary:U.string().nullable(),tokens_used:U.number().nullable(),created_at:U.string().datetime()}).openapi("Session"),lC=Rj.extend({events:U.array(U.object({id:U.string(),type:U.string(),priority:U.number(),data:U.string(),created_at:U.string().datetime()})),snapshot:U.string().nullable()}).openapi("SessionDetail"),sC=i({method:"get",path:"/sessions",tags:["Sessions"],summary:"List recent sessions",request:{query:U.object({agent:U.string().optional(),job_run_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Sessions list",content:{"application/json":{schema:U.object({sessions:U.array(Rj)})}}}}}),aC=i({method:"get",path:"/sessions/{id}",tags:["Sessions"],summary:"Get session detail with events",request:{params:U.object({id:U.string()})},responses:{200:{description:"Session detail",content:{"application/json":{schema:lC}}},404:{description:"Not found"}}});aD.openapi(sC,async($)=>{let w=f(),{agent:E,job_run_id:X,limit:G}=$.req.valid("query"),A=[];if(E)A.push(V(_w.agent,E));if(X)A.push(V(_w.job_run_id,X));let N=await w.query.sessions.findMany({limit:G,orderBy:[r0(_w.created_at)],where:A.length>0?_0(...A):void 0});return $.json({sessions:N.map(zj)})});aD.openapi(aC,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=await w.query.sessions.findFirst({where:V(_w.id,E)});if(!X)throw new L0("Session",E);let G=w.$client,A=G.query(`SELECT id, type, priority, data, created_at
515
524
  FROM session_events WHERE session_id = ?
516
- ORDER BY created_at ASC`).all(E),A=G.query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(E);return $.json({...Oj(X),snapshot:A?.xml??null,events:J.map((D)=>({id:D.id,type:D.type,priority:D.priority,data:D.data,created_at:new Date(D.created_at*1000).toISOString()}))})})});function g_(){return x().$client}var Q9,Yj,y_;var Hj=R(()=>{N1();y$();Q9=new p0,Yj={task:"tasks",project:"projects",memory:"memories",prompt:"prompts"},y_=m({method:"get",path:"/tags",tags:["Tags"],summary:"List unique tags across resources",request:{query:U.object({resource_type:U.enum(["task","project","memory","prompt"]).optional()})},responses:{200:{description:"Unique tags with counts",content:{"application/json":{schema:U.object({tags:U.array(U.object({name:U.string(),count:U.number(),resource_type:U.string()}))})}}}}});Q9.openapi(y_,async($)=>{let{resource_type:w}=$.req.valid("query"),E=g_(),X=w?[[w,Yj[w]]]:Object.entries(Yj),G=[];for(let[J,A]of X){let D=E.query(`SELECT j.value AS tag, COUNT(*) AS count
517
- FROM ${A}, json_each(${A}.tags) AS j
518
- WHERE ${A}.tags IS NOT NULL
525
+ ORDER BY created_at ASC`).all(E),N=G.query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(E);return $.json({...zj(X),snapshot:N?.xml??null,events:A.map((D)=>({id:D.id,type:D.type,priority:D.priority,data:D.data,created_at:new Date(D.created_at*1000).toISOString()}))})})});function $f(){return f().$client}var b4,Ij,eC;var Qj=T(()=>{Ow();J$();b4=new m0,Ij={task:"tasks",project:"projects",memory:"memories",prompt:"prompts"},eC=i({method:"get",path:"/tags",tags:["Tags"],summary:"List unique tags across resources",request:{query:U.object({resource_type:U.enum(["task","project","memory","prompt"]).optional()})},responses:{200:{description:"Unique tags with counts",content:{"application/json":{schema:U.object({tags:U.array(U.object({name:U.string(),count:U.number(),resource_type:U.string()}))})}}}}});b4.openapi(eC,async($)=>{let{resource_type:w}=$.req.valid("query"),E=$f(),X=w?[[w,Ij[w]]]:Object.entries(Ij),G=[];for(let[A,N]of X){let D=E.query(`SELECT j.value AS tag, COUNT(*) AS count
526
+ FROM ${N}, json_each(${N}.tags) AS j
527
+ WHERE ${N}.tags IS NOT NULL
519
528
  GROUP BY j.value
520
- ORDER BY count DESC, j.value ASC`).all();for(let N of D)G.push({name:N.tag,count:N.count,resource_type:J})}return $.json({tags:G})})});function Fj($){return{...$,created_at:$.created_at.toISOString()}}var W6,Lj,u_,h_,c_,n_;var jj=R(()=>{N1();x1();X1();nA();y$();d$();i$();W6=new p0,Lj=U.object({id:U.string(),from_task_id:U.string(),to_task_id:U.string(),link_type:F9,created_at:U.string().datetime()}).openapi("TaskLink"),u_=U.object({to_task_id:U.string(),link_type:F9}).openapi("CreateTaskLink"),h_=m({method:"get",path:"/tasks/{id}/links",tags:["Tasks"],summary:"List links for a task (both directions)",request:{params:U.object({id:U.string()})},responses:{200:{description:"Links",content:{"application/json":{schema:U.object({links:U.array(Lj)})}}}}}),c_=m({method:"post",path:"/tasks/{id}/links",tags:["Tasks"],summary:"Link this task to another task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:u_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:Lj}}}}}),n_=m({method:"delete",path:"/tasks/{id}/links/{linkId}",tags:["Tasks"],summary:"Remove a task link",request:{params:U.object({id:U.string(),linkId:U.string()})},responses:{204:{description:"Deleted"}}});W6.openapi(h_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let G=await w.query.task_links.findMany({where:VJ(V(f$.from_task_id,E),V(f$.to_task_id,E))});return $.json({links:G.map(Fj)})});W6.openapi(c_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{to_task_id:X,link_type:G}=$.req.valid("json"),[J,A]=await Promise.all([w.query.tasks.findFirst({where:V(r.id,E)}),w.query.tasks.findFirst({where:V(r.id,X)})]);if(!J)throw new U0("Task",E);if(!A)throw new U0("Task",X);if(E===X)throw new Ew("Cannot link a task to itself");if(await w.query.task_links.findFirst({where:S0(V(f$.from_task_id,E),V(f$.to_task_id,X))}))throw new Ew("Link already exists between these tasks");let N=i();await w.insert(f$).values({id:N,from_task_id:E,to_task_id:X,link_type:G,created_at:new Date});let W=await w.query.task_links.findFirst({where:V(f$.id,N)});if(!W)throw Error("Expected link to exist after write");return $.json(Fj(W),201)});W6.openapi(n_,async($)=>{let w=x(),{id:E,linkId:X}=$.req.valid("param"),G=await w.query.task_links.findFirst({where:V(f$.id,X)});if(!G||G.from_task_id!==E&&G.to_task_id!==E)throw new U0("TaskLink",X);return await w.delete(f$).where(V(f$.id,X)),new Response(null,{status:204})})});function I9($,w){return $.query(`SELECT t.id, t.title, t.status
521
- FROM task_links tl
522
- JOIN tasks t ON t.id = tl.from_task_id
523
- WHERE tl.to_task_id = ? AND tl.link_type = 'blocks'
524
- AND t.status NOT IN ('done', 'cancelled')
525
- UNION
526
- SELECT t.id, t.title, t.status
527
- FROM task_links tl
528
- JOIN tasks t ON t.id = tl.to_task_id
529
- WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by'
530
- AND t.status NOT IN ('done', 'cancelled')`).all(w,w)}function Mj($,w){let E=$.query(`SELECT DISTINCT dependent_id AS id FROM (
531
- SELECT tl.to_task_id AS dependent_id
532
- FROM task_links tl
533
- WHERE tl.from_task_id = ? AND tl.link_type = 'blocks'
534
- UNION
535
- SELECT tl.from_task_id AS dependent_id
536
- FROM task_links tl
537
- WHERE tl.to_task_id = ? AND tl.link_type = 'blocked_by'
538
- )`).all(w,w),X=[];for(let{id:G}of E)if(I9($,G).length===0){if($.query("SELECT status FROM tasks WHERE id = ?").get(G)?.status==="blocked")$.query("UPDATE tasks SET status = 'todo', updated_at = unixepoch() WHERE id = ?").run(G),X.push(G)}return X}function Rj($,w){let E=$.query(`SELECT tl.to_task_id FROM task_links tl
539
- WHERE tl.from_task_id = ? AND tl.link_type = 'subtask_of'
540
- LIMIT 1`).get(w);if(!E)return null;let X=E.to_task_id,G=$.query(`SELECT
541
- COUNT(*) as total,
542
- SUM(CASE WHEN t.status IN ('done', 'cancelled') THEN 1 ELSE 0 END) as done
543
- FROM task_links tl
544
- JOIN tasks t ON t.id = tl.from_task_id
545
- WHERE tl.to_task_id = ? AND tl.link_type = 'subtask_of'`).get(X);if(!G||G.total===0)return null;let J=Math.round(G.done/G.total*100);if($.query("UPDATE tasks SET progress = ?, updated_at = unixepoch() WHERE id = ?").run(J,X),G.done===G.total){let A=$.query("SELECT status FROM tasks WHERE id = ?").get(X);if(A&&!["done","cancelled","review"].includes(A.status))$.query("UPDATE tasks SET status = 'review', updated_at = unixepoch() WHERE id = ?").run(X)}return X}function sA(){return x().$client}function U6($){return{...$,due_at:$.due_at?.toISOString()??null,claim_expires_at:$.claim_expires_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function Ev($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,due_at:$.due_at?new Date($.due_at*1000).toISOString():null,claim_expires_at:$.claim_expires_at?new Date($.claim_expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Tj($){return{...$,created_at:$.created_at.toISOString()}}var j1,O6,zj,m_,r_,p_,o_,t_,i_,d_,l_,s_,a_,e_,$v,wv;var Bj=R(()=>{N1();x1();X1();nA();y$();d$();i$();j1=new p0,O6=U.object({id:U.string(),project_id:U.string().nullable(),title:U.string(),body:U.string().nullable(),status:uA,priority:J6,progress:U.number().int(),due_at:U.string().datetime().nullable(),tags:U.array(U.string()).nullable(),author:U.string(),claimed_by:U.string().nullable(),claim_expires_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Task"),zj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("Comment"),m_=U.object({title:U.string().min(1).max(500),body:U.string().optional(),project_id:U.string().optional(),status:U.enum(["todo","doing","blocked"]).optional().default("todo"),priority:J6.optional().default("normal"),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional(),author:U.string().optional().default("human")}).openapi("CreateTask"),r_=U.object({title:U.string().min(1).max(500).optional(),body:U.string().optional(),status:uA.optional(),priority:J6.optional(),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional()}).openapi("UpdateTask"),p_=m({method:"get",path:"/tasks",tags:["Tasks"],summary:"List tasks",request:{query:U.object({project_id:U.string().optional(),status:uA.optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Task list",content:{"application/json":{schema:U.object({tasks:U.array(O6),total:U.number()})}}}}}),o_=m({method:"get",path:"/tasks/{id}",tags:["Tasks"],summary:"Get task by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Task",content:{"application/json":{schema:O6}}}}}),t_=m({method:"post",path:"/tasks",tags:["Tasks"],summary:"Create task",request:{body:{content:{"application/json":{schema:m_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:O6}}}}}),i_=m({method:"patch",path:"/tasks/{id}",tags:["Tasks"],summary:"Update task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:r_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:O6}}}}}),d_=m({method:"delete",path:"/tasks/{id}",tags:["Tasks"],summary:"Delete task",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),l_=U.object({ref:U.string().describe("Temporary reference ID for dependency linking, e.g. 'T1'"),title:U.string().min(1).max(500),body:U.string().optional(),priority:J6.optional().default("normal"),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")}),s_=m({method:"post",path:"/tasks/batch",tags:["Tasks"],summary:"Create multiple tasks with dependency links atomically",request:{body:{content:{"application/json":{schema:U.object({tasks:U.array(l_).min(1).max(100),project_id:U.string().optional(),author:U.string().optional().default("agent")}).openapi("BatchCreateTasks")}}}},responses:{201:{description:"Created tasks with ref\u2192id mapping",content:{"application/json":{schema:U.object({created:U.number(),mapping:U.record(U.string(),U.string())})}}}}}),a_=m({method:"post",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Submit task for human review (HITL checkpoint)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({summary:U.string().min(1)}).openapi("SubmitReview")}}}},responses:{200:{description:"Submitted",content:{"application/json":{schema:O6}}}}}),e_=m({method:"get",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Poll HITL review result",request:{params:U.object({id:U.string()})},responses:{200:{description:"Review status",content:{"application/json":{schema:U.object({status:U.enum(["review","approved","changes_requested","pending"]),comment:U.string().nullable()}).openapi("ReviewStatus")}}}}}),$v=m({method:"get",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"List task comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(zj)})}}}}}),wv=m({method:"post",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"Add a comment to a task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:zj}}}}});j1.openapi(p_,async($)=>{let w=x(),{project_id:E,status:X,tag:G,limit:J}=$.req.valid("query");if(G){let N=sA(),W="SELECT DISTINCT t.* FROM tasks t, json_each(t.tags) AS j WHERE j.value = ?",O=[G];if(E)W+=" AND t.project_id = ?",O.push(E);if(X)W+=" AND t.status = ?",O.push(X);W+=" ORDER BY t.updated_at DESC LIMIT ?",O.push(J);let Y=N.query(W).all(...O),H=Y.map(Ev);return $.json({tasks:H,total:Y.length})}let A=[];if(E)A.push(V(r.project_id,E));if(X)A.push(V(r.status,X));let D=await w.query.tasks.findMany({where:A.length>0?S0(...A):void 0,limit:J,orderBy:[x0(r.updated_at)]});return $.json({tasks:D.map(U6),total:D.length})});j1.openapi(o_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(r.id,E)});if(!X)throw new U0("Task",E);return $.json(U6(X))});j1.openapi(t_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(r).values({id:G,title:E.title,body:E.body,project_id:E.project_id,status:E.status,priority:E.priority,...E.due_at?{due_at:new Date(E.due_at)}:{},tags:E.tags,author:E.author,created_at:X,updated_at:X});let J=await w.query.tasks.findFirst({where:V(r.id,G)});if(!J)throw Error("Expected task to exist after write");return $.json(U6(J),201)});j1.openapi(i_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.tasks.findFirst({where:V(r.id,E)});if(!G)throw new U0("Task",E);if(X.status==="doing"&&G.status!=="doing"){let A=I9(sA(),E);if(A.length>0){let D=A.map((N)=>`[${N.id.slice(-6)}] ${N.title}`).join(", ");throw new Ew(`Cannot start: blocked by ${D}`)}}if(await w.update(r).set({...X.title!==void 0?{title:X.title}:{},...X.body!==void 0?{body:X.body}:{},...X.status!==void 0?{status:X.status}:{},...X.priority!==void 0?{priority:X.priority}:{},...X.due_at!==void 0?{due_at:new Date(X.due_at)}:{},...X.tags!==void 0?{tags:X.tags}:{},updated_at:new Date}).where(V(r.id,E)),X.status&&["done","cancelled"].includes(X.status)){let A=sA();Mj(A,E),Rj(A,E)}let J=await w.query.tasks.findFirst({where:V(r.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(U6(J))});j1.openapi(d_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);return await w.delete(r).where(V(r.id,E)),new Response(null,{status:204})});j1.openapi(a_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{summary:X}=$.req.valid("json"),G=await w.query.tasks.findFirst({where:V(r.id,E)});if(!G)throw new U0("Task",E);if(!["doing","blocked"].includes(G.status))throw new Ew(`Task must be in doing/blocked to submit for review (current: ${G.status})`);let J=new Date;await w.update(r).set({status:"review",body:X,updated_at:J}).where(V(r.id,E)),await w.insert(G$).values({id:i(),resource_type:"task",resource_id:E,content:`[review submitted] ${X}`,author:"agent",created_at:J});let A=await w.query.tasks.findFirst({where:V(r.id,E)});if(!A)throw Error("Expected updated to exist after write");return $.json(U6(A))});j1.openapi(e_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(r.id,E)});if(!X)throw new U0("Task",E);let G=await w.query.comments.findFirst({where:S0(V(G$.resource_type,"task"),V(G$.resource_id,E),V(G$.author,"human")),orderBy:[x0(G$.created_at)]}),A={review:"review",done:"approved",changes_requested:"changes_requested"}[X.status]??"pending";return $.json({status:A,comment:G?.content??null})});j1.openapi($v,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let G=await w.query.comments.findMany({where:S0(V(G$.resource_type,"task"),V(G$.resource_id,E)),orderBy:[x0(G$.created_at)]});return $.json({comments:G.map(Tj)})});j1.openapi(wv,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let A=i(),D=new Date;await w.insert(G$).values({id:A,resource_type:"task",resource_id:E,content:X,author:G,created_at:D});let N=await w.query.comments.findFirst({where:V(G$.id,A)});if(!N)throw Error("Expected comment to exist after write");return $.json(Tj(N),201)});j1.openapi(s_,async($)=>{let w=x(),{tasks:E,project_id:X,author:G}=$.req.valid("json"),J=new Date,A={},D=sA();D.exec("BEGIN");try{for(let N of E){let W=i();A[N.ref]=W,await w.insert(r).values({id:W,title:N.title,body:N.body,project_id:X,priority:N.priority,author:G,status:"todo",created_at:J,updated_at:J})}for(let N of E){let W=A[N.ref];if(N.depends_on)for(let O of N.depends_on){let Y=A[O];if(!Y)continue;await w.insert(f$).values({id:i(),from_task_id:Y,to_task_id:W,link_type:"blocks",created_at:J})}if(N.subtask_of){let O=A[N.subtask_of];if(O)await w.insert(f$).values({id:i(),from_task_id:W,to_task_id:O,link_type:"subtask_of",created_at:J}),await w.insert(f$).values({id:i(),from_task_id:O,to_task_id:W,link_type:"parent_of",created_at:J})}}D.exec("COMMIT")}catch(N){throw D.exec("ROLLBACK"),N}return $.json({created:E.length,mapping:A},201)})});function Qj(){let $=O0(),w=new p0;return w.use("*",cF($.api.secret)),w.onError((E,X)=>{let G=E instanceof PX?E:null;if(G)return X.json({error:G.message,code:G.code},G.statusCode);return Xv.error("Unhandled error",E),X.json({error:"Internal server error",code:"INTERNAL_ERROR"},500)}),w.route("/",L9),w.route("/",z9),w.route("/",y1),w.route("/",Iw),w.route("/",j1),w.route("/",W6),w.route("/",SX),w.route("/",lA),w.route("/",Xw),w.route("/",gA),w.route("/",Q9),w.doc("/openapi.json",{openapi:"3.1.0",info:{title:"Orc API",version:lE,description:"Human + AI Orchestration Hub API"},servers:[{url:`http://${$.api.host}:${$.api.port}`,description:"Local"}]}),w.get("/docs",I3({url:"/openapi.json"})),w}var Xv;var Ij=R(()=>{K3();N1();C$();x1();p$();FJ();nF();mF();rF();oF();wj();Xj();Dj();Nj();Uj();Hj();jj();Bj();Xv=Z0("api")});var V9={};Ww(V9,{app:()=>Kj});var K9,ow,Kj;var P9=R(()=>{C$();p$();Ij();K9=Z0("api"),ow=O0(),Kj=Qj();Bun.serve({port:ow.api.port,hostname:ow.api.host,fetch:Kj.fetch});K9.info(`API server running on http://${ow.api.host}:${ow.api.port}`);K9.info(`OpenAPI spec: http://${ow.api.host}:${ow.api.port}/openapi.json`);K9.info(`Swagger UI: http://${ow.api.host}:${ow.api.port}/docs`)});function S($,w,E){function X(D,N){var W;Object.defineProperty(D,"_zod",{value:D._zod??{},enumerable:!1}),(W=D._zod).traits??(W.traits=new Set),D._zod.traits.add($),w(D,N);for(let O in A.prototype)if(!(O in D))Object.defineProperty(D,O,{value:A.prototype[O].bind(D)});D._zod.constr=A,D._zod.def=N}let G=E?.Parent??Object;class J extends G{}Object.defineProperty(J,"name",{value:$});function A(D){var N;let W=E?.Parent?new J:this;X(W,D),(N=W._zod).deferred??(N.deferred=[]);for(let O of W._zod.deferred)O();return W}return Object.defineProperty(A,"init",{value:X}),Object.defineProperty(A,Symbol.hasInstance,{value:(D)=>{if(E?.Parent&&D instanceof E.Parent)return!0;return D?._zod?.traits?.has($)}}),Object.defineProperty(A,"name",{value:$}),A}function R1($){if($)Object.assign($4,$);return $4}var PG0,qG0,iw,$4;var ZX=R(()=>{PG0=Object.freeze({status:"aborted"});qG0=Symbol("zod_brand");iw=class iw extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$4={}});var B0={};Ww(B0,{unwrapMessage:()=>L6,stringifyPrimitive:()=>X4,required:()=>nv,randomString:()=>_v,propertyKeyTypes:()=>g9,promiseAllObject:()=>Cv,primitiveTypes:()=>mj,prefixIssues:()=>Jw,pick:()=>yv,partial:()=>cv,optionalKeys:()=>u9,omit:()=>gv,numKeys:()=>vv,nullish:()=>j6,normalizeParams:()=>l,merge:()=>hv,jsonStringifyReplacer:()=>v9,joinValues:()=>w4,issue:()=>c9,isPlainObject:()=>_X,isObject:()=>CX,getSizableOrigin:()=>pj,getParsedType:()=>fv,getLengthableOrigin:()=>R6,getEnumValues:()=>_9,getElementAtPath:()=>Zv,floatSafeRemainder:()=>f9,finalizeIssue:()=>u1,extend:()=>uv,escapeRegex:()=>dw,esc:()=>PE,defineLazy:()=>C0,createTransparentProxy:()=>xv,clone:()=>Gw,cleanRegex:()=>M6,cleanEnum:()=>mv,captureStackTrace:()=>E4,cached:()=>F6,assignProp:()=>x9,assertNotEqual:()=>qv,assertNever:()=>kv,assertIs:()=>Sv,assertEqual:()=>Pv,assert:()=>bv,allowsEval:()=>y9,aborted:()=>qE,NUMBER_FORMAT_RANGES:()=>h9,Class:()=>oj,BIGINT_FORMAT_RANGES:()=>rj});function Pv($){return $}function qv($){return $}function Sv($){}function kv($){throw Error()}function bv($){}function _9($){let w=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,G])=>w.indexOf(+X)===-1).map(([X,G])=>G)}function w4($,w="|"){return $.map((E)=>X4(E)).join(w)}function v9($,w){if(typeof w==="bigint")return w.toString();return w}function F6($){return{get value(){{let E=$();return Object.defineProperty(this,"value",{value:E}),E}throw Error("cached value already set")}}}function j6($){return $===null||$===void 0}function M6($){let w=$.startsWith("^")?1:0,E=$.endsWith("$")?$.length-1:$.length;return $.slice(w,E)}function f9($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,J=Number.parseInt($.toFixed(G).replace(".","")),A=Number.parseInt(w.toFixed(G).replace(".",""));return J%A/10**G}function C0($,w,E){Object.defineProperty($,w,{get(){{let G=E();return $[w]=G,G}throw Error("cached value already set")},set(G){Object.defineProperty($,w,{value:G})},configurable:!0})}function x9($,w,E){Object.defineProperty($,w,{value:E,writable:!0,enumerable:!0,configurable:!0})}function Zv($,w){if(!w)return $;return w.reduce((E,X)=>E?.[X],$)}function Cv($){let w=Object.keys($),E=w.map((X)=>$[X]);return Promise.all(E).then((X)=>{let G={};for(let J=0;J<w.length;J++)G[w[J]]=X[J];return G})}function _v($=10){let E="";for(let X=0;X<$;X++)E+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return E}function PE($){return JSON.stringify($)}function CX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _X($){if(CX($)===!1)return!1;let w=$.constructor;if(w===void 0)return!0;let E=w.prototype;if(CX(E)===!1)return!1;if(Object.prototype.hasOwnProperty.call(E,"isPrototypeOf")===!1)return!1;return!0}function vv($){let w=0;for(let E in $)if(Object.prototype.hasOwnProperty.call($,E))w++;return w}function dw($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gw($,w,E){let X=new $._zod.constr(w??$._zod.def);if(!w||E?.parent)X._zod.parent=$;return X}function l($){let w=$;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function xv($){let w;return new Proxy({},{get(E,X,G){return w??(w=$()),Reflect.get(w,X,G)},set(E,X,G,J){return w??(w=$()),Reflect.set(w,X,G,J)},has(E,X){return w??(w=$()),Reflect.has(w,X)},deleteProperty(E,X){return w??(w=$()),Reflect.deleteProperty(w,X)},ownKeys(E){return w??(w=$()),Reflect.ownKeys(w)},getOwnPropertyDescriptor(E,X){return w??(w=$()),Reflect.getOwnPropertyDescriptor(w,X)},defineProperty(E,X,G){return w??(w=$()),Reflect.defineProperty(w,X,G)}})}function X4($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function u9($){return Object.keys($).filter((w)=>{return $[w]._zod.optin==="optional"&&$[w]._zod.optout==="optional"})}function yv($,w){let E={},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;E[G]=X.shape[G]}return Gw($,{...$._zod.def,shape:E,checks:[]})}function gv($,w){let E={...$._zod.def.shape},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete E[G]}return Gw($,{...$._zod.def,shape:E,checks:[]})}function uv($,w){if(!_X(w))throw Error("Invalid input to extend: expected a plain object");let E={...$._zod.def,get shape(){let X={...$._zod.def.shape,...w};return x9(this,"shape",X),X},checks:[]};return Gw($,E)}function hv($,w){return Gw($,{...$._zod.def,get shape(){let E={...$._zod.def.shape,...w._zod.def.shape};return x9(this,"shape",E),E},catchall:w._zod.def.catchall,checks:[]})}function cv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let J in E){if(!(J in X))throw Error(`Unrecognized key: "${J}"`);if(!E[J])continue;G[J]=$?new $({type:"optional",innerType:X[J]}):X[J]}else for(let J in X)G[J]=$?new $({type:"optional",innerType:X[J]}):X[J];return Gw(w,{...w._zod.def,shape:G,checks:[]})}function nv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let J in E){if(!(J in G))throw Error(`Unrecognized key: "${J}"`);if(!E[J])continue;G[J]=new $({type:"nonoptional",innerType:X[J]})}else for(let J in X)G[J]=new $({type:"nonoptional",innerType:X[J]});return Gw(w,{...w._zod.def,shape:G,checks:[]})}function qE($,w=0){for(let E=w;E<$.issues.length;E++)if($.issues[E]?.continue!==!0)return!0;return!1}function Jw($,w){return w.map((E)=>{var X;return(X=E).path??(X.path=[]),E.path.unshift($),E})}function L6($){return typeof $==="string"?$:$?.message}function u1($,w,E){let X={...$,path:$.path??[]};if(!$.message){let G=L6($.inst?._zod.def?.error?.($))??L6(w?.error?.($))??L6(E.customError?.($))??L6(E.localeError?.($))??"Invalid input";X.message=G}if(delete X.inst,delete X.continue,!w?.reportInput)delete X.input;return X}function pj($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function R6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function c9(...$){let[w,E,X]=$;if(typeof w==="string")return{message:w,code:"custom",input:E,inst:X};return{...w}}function mv($){return Object.entries($).filter(([w,E])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}class oj{constructor(...$){}}var E4,y9,fv=($)=>{let w=typeof $;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},g9,mj,h9,rj;var Kw=R(()=>{E4=Error.captureStackTrace?Error.captureStackTrace:(...$)=>{};y9=F6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});g9=new Set(["string","number","symbol"]),mj=new Set(["string","number","bigint","boolean","symbol","undefined"]);h9={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},rj={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function ij($,w=(E)=>E.message){let E={},X=[];for(let G of $.issues)if(G.path.length>0)E[G.path[0]]=E[G.path[0]]||[],E[G.path[0]].push(w(G));else X.push(w(G));return{formErrors:X,fieldErrors:E}}function dj($,w){let E=w||function(J){return J.message},X={_errors:[]},G=(J)=>{for(let A of J.issues)if(A.code==="invalid_union"&&A.errors.length)A.errors.map((D)=>G({issues:D}));else if(A.code==="invalid_key")G({issues:A.issues});else if(A.code==="invalid_element")G({issues:A.issues});else if(A.path.length===0)X._errors.push(E(A));else{let D=X,N=0;while(N<A.path.length){let W=A.path[N];if(N!==A.path.length-1)D[W]=D[W]||{_errors:[]};else D[W]=D[W]||{_errors:[]},D[W]._errors.push(E(A));D=D[W],N++}}};return G($),X}var tj=($,w)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:w,enumerable:!1}),Object.defineProperty($,"message",{get(){return JSON.stringify(w,v9,2)},enumerable:!0}),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},G4,n9;var m9=R(()=>{ZX();Kw();G4=S("$ZodError",tj),n9=S("$ZodError",tj,{Parent:Error})});var lj=($)=>(w,E,X,G)=>{let J=X?Object.assign(X,{async:!1}):{async:!1},A=w._zod.run({value:E,issues:[]},J);if(A instanceof Promise)throw new iw;if(A.issues.length){let D=new(G?.Err??$)(A.issues.map((N)=>u1(N,J,R1())));throw E4(D,G?.callee),D}return A.value},sj=($)=>async(w,E,X,G)=>{let J=X?Object.assign(X,{async:!0}):{async:!0},A=w._zod.run({value:E,issues:[]},J);if(A instanceof Promise)A=await A;if(A.issues.length){let D=new(G?.Err??$)(A.issues.map((N)=>u1(N,J,R1())));throw E4(D,G?.callee),D}return A.value},r9=($)=>(w,E,X)=>{let G=X?{...X,async:!1}:{async:!1},J=w._zod.run({value:E,issues:[]},G);if(J instanceof Promise)throw new iw;return J.issues.length?{success:!1,error:new($??G4)(J.issues.map((A)=>u1(A,G,R1())))}:{success:!0,data:J.value}},z6,p9=($)=>async(w,E,X)=>{let G=X?Object.assign(X,{async:!0}):{async:!0},J=w._zod.run({value:E,issues:[]},G);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((A)=>u1(A,G,R1())))}:{success:!0,data:J.value}},J4;var o9=R(()=>{ZX();m9();Kw();z6=r9(n9),J4=p9(n9)});function DM(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function MM($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function RM($){return new RegExp(`^${MM($)}$`)}function zM($){let w=MM({precision:$.precision}),E=["Z"];if($.local)E.push("");if($.offset)E.push("([+-]\\d{2}:\\d{2})");let X=`${w}(?:${E.join("|")})`;return new RegExp(`^${FM}T(?:${X})$`)}var aj,ej,$M,wM,EM,XM,GM,JM,t9=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},AM,NM,WM,OM,UM,YM,i9,HM,LM,FM="(?:(?:\\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])))",jM,TM=($)=>{let w=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)},BM,QM,IM,KM,VM,PM;var A4=R(()=>{aj=/^[cC][^\s-]{8,}$/,ej=/^[0-9a-z]+$/,$M=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,wM=/^[0-9a-vA-V]{20}$/,EM=/^[A-Za-z0-9]{27}$/,XM=/^[a-zA-Z0-9_-]{21}$/,GM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,JM=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,AM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;NM=/^(?:(?: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])$/,WM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,OM=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,UM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,YM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,i9=/^[A-Za-z0-9_-]*$/,HM=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,LM=/^\+(?:[0-9]){6,14}[0-9]$/,jM=new RegExp(`^${FM}$`);BM=/^\d+$/,QM=/^-?\d+(?:\.\d+)?/i,IM=/true|false/i,KM=/null/i,VM=/^[^A-Z]*$/,PM=/^[^a-z]*$/});var b$,qM,l9,s9,SM,kM,bM,ZM,CM,T6,_M,vM,fM,xM,yM,gM,uM;var D4=R(()=>{ZX();A4();Kw();b$=S("$ZodCheck",($,w)=>{var E;$._zod??($._zod={}),$._zod.def=w,(E=$._zod).onattach??(E.onattach=[])}),qM={number:"number",bigint:"bigint",object:"date"},l9=S("$ZodCheckLessThan",($,w)=>{b$.init($,w);let E=qM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(w.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<J)if(w.inclusive)G.maximum=w.value;else G.exclusiveMaximum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value<=w.value:X.value<w.value)return;X.issues.push({origin:E,code:"too_big",maximum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),s9=S("$ZodCheckGreaterThan",($,w)=>{b$.init($,w);let E=qM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(w.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>J)if(w.inclusive)G.minimum=w.value;else G.exclusiveMinimum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value>=w.value:X.value>w.value)return;X.issues.push({origin:E,code:"too_small",minimum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),SM=S("$ZodCheckMultipleOf",($,w)=>{b$.init($,w),$._zod.onattach.push((E)=>{var X;(X=E._zod.bag).multipleOf??(X.multipleOf=w.value)}),$._zod.check=(E)=>{if(typeof E.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof E.value==="bigint"?E.value%w.value===BigInt(0):f9(E.value,w.value)===0)return;E.issues.push({origin:typeof E.value,code:"not_multiple_of",divisor:w.value,input:E.value,inst:$,continue:!w.abort})}}),kM=S("$ZodCheckNumberFormat",($,w)=>{b$.init($,w),w.format=w.format||"float64";let E=w.format?.includes("int"),X=E?"int":"number",[G,J]=h9[w.format];$._zod.onattach.push((A)=>{let D=A._zod.bag;if(D.format=w.format,D.minimum=G,D.maximum=J,E)D.pattern=BM}),$._zod.check=(A)=>{let D=A.value;if(E){if(!Number.isInteger(D)){A.issues.push({expected:X,format:w.format,code:"invalid_type",input:D,inst:$});return}if(!Number.isSafeInteger(D)){if(D>0)A.issues.push({input:D,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});else A.issues.push({input:D,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});return}}if(D<G)A.issues.push({origin:"number",input:D,code:"too_small",minimum:G,inclusive:!0,inst:$,continue:!w.abort});if(D>J)A.issues.push({origin:"number",input:D,code:"too_big",maximum:J,inst:$})}}),bM=S("$ZodCheckMaxLength",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!j6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<G)X._zod.bag.maximum=w.maximum}),$._zod.check=(X)=>{let G=X.value;if(G.length<=w.maximum)return;let A=R6(G);X.issues.push({origin:A,code:"too_big",maximum:w.maximum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),ZM=S("$ZodCheckMinLength",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!j6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>G)X._zod.bag.minimum=w.minimum}),$._zod.check=(X)=>{let G=X.value;if(G.length>=w.minimum)return;let A=R6(G);X.issues.push({origin:A,code:"too_small",minimum:w.minimum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),CM=S("$ZodCheckLengthEquals",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!j6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.minimum=w.length,G.maximum=w.length,G.length=w.length}),$._zod.check=(X)=>{let G=X.value,J=G.length;if(J===w.length)return;let A=R6(G),D=J>w.length;X.issues.push({origin:A,...D?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!w.abort})}}),T6=S("$ZodCheckStringFormat",($,w)=>{var E,X;if(b$.init($,w),$._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=w.format,w.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(w.pattern)}),w.pattern)(E=$._zod).check??(E.check=(G)=>{if(w.pattern.lastIndex=0,w.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:w.format,input:G.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:$,continue:!w.abort})});else(X=$._zod).check??(X.check=()=>{})}),_M=S("$ZodCheckRegex",($,w)=>{T6.init($,w),$._zod.check=(E)=>{if(w.pattern.lastIndex=0,w.pattern.test(E.value))return;E.issues.push({origin:"string",code:"invalid_format",format:"regex",input:E.value,pattern:w.pattern.toString(),inst:$,continue:!w.abort})}}),vM=S("$ZodCheckLowerCase",($,w)=>{w.pattern??(w.pattern=VM),T6.init($,w)}),fM=S("$ZodCheckUpperCase",($,w)=>{w.pattern??(w.pattern=PM),T6.init($,w)}),xM=S("$ZodCheckIncludes",($,w)=>{b$.init($,w);let E=dw(w.includes),X=new RegExp(typeof w.position==="number"?`^.{${w.position}}${E}`:E);w.pattern=X,$._zod.onattach.push((G)=>{let J=G._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.includes(w.includes,w.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:G.value,inst:$,continue:!w.abort})}}),yM=S("$ZodCheckStartsWith",($,w)=>{b$.init($,w);let E=new RegExp(`^${dw(w.prefix)}.*`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.startsWith(w.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:X.value,inst:$,continue:!w.abort})}}),gM=S("$ZodCheckEndsWith",($,w)=>{b$.init($,w);let E=new RegExp(`.*${dw(w.suffix)}$`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.endsWith(w.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:X.value,inst:$,continue:!w.abort})}}),uM=S("$ZodCheckOverwrite",($,w)=>{b$.init($,w),$._zod.check=(E)=>{E.value=w.tx(E.value)}})});class a9{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let E=$.split(`
546
- `).filter((J)=>J),X=Math.min(...E.map((J)=>J.length-J.trimStart().length)),G=E.map((J)=>J.slice(X)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of G)this.content.push(J)}compile(){let $=Function,w=this?.args,X=[...(this?.content??[""]).map((G)=>` ${G}`)];return new $(...w,X.join(`
547
- `))}}var cM;var e9=R(()=>{cM={major:4,minor:0,patch:0}});function jR($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function pv($){if(!i9.test($))return!1;let w=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),E=w.padEnd(Math.ceil(w.length/4)*4,"=");return jR(E)}function ov($,w=null){try{let E=$.split(".");if(E.length!==3)return!1;let[X]=E;if(!X)return!1;let G=JSON.parse(atob(X));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&(!("alg"in G)||G.alg!==w))return!1;return!0}catch{return!1}}function nM($,w,E){if($.issues.length)w.issues.push(...Jw(E,$.issues));w.value[E]=$.value}function N4($,w,E){if($.issues.length)w.issues.push(...Jw(E,$.issues));w.value[E]=$.value}function mM($,w,E,X){if($.issues.length)if(X[E]===void 0)if(E in X)w.value[E]=void 0;else w.value[E]=$.value;else w.issues.push(...Jw(E,$.issues));else if($.value===void 0){if(E in X)w.value[E]=void 0}else w.value[E]=$.value}function rM($,w,E,X){for(let G of $)if(G.issues.length===0)return w.value=G.value,w;return w.issues.push({code:"invalid_union",input:w.value,inst:E,errors:$.map((G)=>G.issues.map((J)=>u1(J,X,R1())))}),w}function $5($,w){if($===w)return{valid:!0,data:$};if($ instanceof Date&&w instanceof Date&&+$===+w)return{valid:!0,data:$};if(_X($)&&_X(w)){let E=Object.keys(w),X=Object.keys($).filter((J)=>E.indexOf(J)!==-1),G={...$,...w};for(let J of X){let A=$5($[J],w[J]);if(!A.valid)return{valid:!1,mergeErrorPath:[J,...A.mergeErrorPath]};G[J]=A.data}return{valid:!0,data:G}}if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return{valid:!1,mergeErrorPath:[]};let E=[];for(let X=0;X<$.length;X++){let G=$[X],J=w[X],A=$5(G,J);if(!A.valid)return{valid:!1,mergeErrorPath:[X,...A.mergeErrorPath]};E.push(A.data)}return{valid:!0,data:E}}return{valid:!1,mergeErrorPath:[]}}function pM($,w,E){if(w.issues.length)$.issues.push(...w.issues);if(E.issues.length)$.issues.push(...E.issues);if(qE($))return $;let X=$5(w.value,E.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}function oM($,w){if($.value===void 0)$.value=w.defaultValue;return $}function tM($,w){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:w});return $}function iM($,w,E){if(qE($))return $;return w.out._zod.run({value:$.value,issues:$.issues},E)}function dM($){return $.value=Object.freeze($.value),$}function lM($,w,E,X){if(!$){let G={code:"custom",input:E,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)G.params=X._zod.def.params;w.issues.push(c9(G))}}var _0,W4,u0,sM,aM,eM,$R,wR,ER,XR,GR,JR,AR,DR,NR,WR,OR,UR,YR,HR,LR,FR,MR,RR,zR,TR,w5,BR,QR,IR,KR,VR,PR,qR,E5,SR,kR,bR,ZR,CR,_R,vR,fR,xR,yR,gR,uR,hR,cR,nR;var mR=R(()=>{D4();ZX();o9();A4();Kw();e9();Kw();_0=S("$ZodType",($,w)=>{var E;$??($={}),$._zod.def=w,$._zod.bag=$._zod.bag||{},$._zod.version=cM;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let G of X)for(let J of G._zod.onattach)J($);if(X.length===0)(E=$._zod).deferred??(E.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let G=(J,A,D)=>{let N=qE(J),W;for(let O of A){if(O._zod.def.when){if(!O._zod.def.when(J))continue}else if(N)continue;let Y=J.issues.length,H=O._zod.check(J);if(H instanceof Promise&&D?.async===!1)throw new iw;if(W||H instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await H,J.issues.length===Y)return;if(!N)N=qE(J,Y)});else{if(J.issues.length===Y)continue;if(!N)N=qE(J,Y)}}if(W)return W.then(()=>{return J});return J};$._zod.run=(J,A)=>{let D=$._zod.parse(J,A);if(D instanceof Promise){if(A.async===!1)throw new iw;return D.then((N)=>G(N,X,A))}return G(D,X,A)}}$["~standard"]={validate:(G)=>{try{let J=z6($,G);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return J4($,G).then((A)=>A.success?{value:A.data}:{issues:A.error?.issues})}},vendor:"zod",version:1}}),W4=S("$ZodString",($,w)=>{_0.init($,w),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??TM($._zod.bag),$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=String(E.value)}catch(G){}if(typeof E.value==="string")return E;return E.issues.push({expected:"string",code:"invalid_type",input:E.value,inst:$}),E}}),u0=S("$ZodStringFormat",($,w)=>{T6.init($,w),W4.init($,w)}),sM=S("$ZodGUID",($,w)=>{w.pattern??(w.pattern=JM),u0.init($,w)}),aM=S("$ZodUUID",($,w)=>{if(w.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(X===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=t9(X))}else w.pattern??(w.pattern=t9());u0.init($,w)}),eM=S("$ZodEmail",($,w)=>{w.pattern??(w.pattern=AM),u0.init($,w)}),$R=S("$ZodURL",($,w)=>{u0.init($,w),$._zod.check=(E)=>{try{let X=E.value,G=new URL(X),J=G.href;if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(G.hostname))E.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:HM.source,input:E.value,inst:$,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))E.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:E.value,inst:$,continue:!w.abort})}if(!X.endsWith("/")&&J.endsWith("/"))E.value=J.slice(0,-1);else E.value=J;return}catch(X){E.issues.push({code:"invalid_format",format:"url",input:E.value,inst:$,continue:!w.abort})}}}),wR=S("$ZodEmoji",($,w)=>{w.pattern??(w.pattern=DM()),u0.init($,w)}),ER=S("$ZodNanoID",($,w)=>{w.pattern??(w.pattern=XM),u0.init($,w)}),XR=S("$ZodCUID",($,w)=>{w.pattern??(w.pattern=aj),u0.init($,w)}),GR=S("$ZodCUID2",($,w)=>{w.pattern??(w.pattern=ej),u0.init($,w)}),JR=S("$ZodULID",($,w)=>{w.pattern??(w.pattern=$M),u0.init($,w)}),AR=S("$ZodXID",($,w)=>{w.pattern??(w.pattern=wM),u0.init($,w)}),DR=S("$ZodKSUID",($,w)=>{w.pattern??(w.pattern=EM),u0.init($,w)}),NR=S("$ZodISODateTime",($,w)=>{w.pattern??(w.pattern=zM(w)),u0.init($,w)}),WR=S("$ZodISODate",($,w)=>{w.pattern??(w.pattern=jM),u0.init($,w)}),OR=S("$ZodISOTime",($,w)=>{w.pattern??(w.pattern=RM(w)),u0.init($,w)}),UR=S("$ZodISODuration",($,w)=>{w.pattern??(w.pattern=GM),u0.init($,w)}),YR=S("$ZodIPv4",($,w)=>{w.pattern??(w.pattern=NM),u0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv4"})}),HR=S("$ZodIPv6",($,w)=>{w.pattern??(w.pattern=WM),u0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv6"}),$._zod.check=(E)=>{try{new URL(`http://[${E.value}]`)}catch{E.issues.push({code:"invalid_format",format:"ipv6",input:E.value,inst:$,continue:!w.abort})}}}),LR=S("$ZodCIDRv4",($,w)=>{w.pattern??(w.pattern=OM),u0.init($,w)}),FR=S("$ZodCIDRv6",($,w)=>{w.pattern??(w.pattern=UM),u0.init($,w),$._zod.check=(E)=>{let[X,G]=E.value.split("/");try{if(!G)throw Error();let J=Number(G);if(`${J}`!==G)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${X}]`)}catch{E.issues.push({code:"invalid_format",format:"cidrv6",input:E.value,inst:$,continue:!w.abort})}}});MR=S("$ZodBase64",($,w)=>{w.pattern??(w.pattern=YM),u0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64"}),$._zod.check=(E)=>{if(jR(E.value))return;E.issues.push({code:"invalid_format",format:"base64",input:E.value,inst:$,continue:!w.abort})}});RR=S("$ZodBase64URL",($,w)=>{w.pattern??(w.pattern=i9),u0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64url"}),$._zod.check=(E)=>{if(pv(E.value))return;E.issues.push({code:"invalid_format",format:"base64url",input:E.value,inst:$,continue:!w.abort})}}),zR=S("$ZodE164",($,w)=>{w.pattern??(w.pattern=LM),u0.init($,w)});TR=S("$ZodJWT",($,w)=>{u0.init($,w),$._zod.check=(E)=>{if(ov(E.value,w.alg))return;E.issues.push({code:"invalid_format",format:"jwt",input:E.value,inst:$,continue:!w.abort})}}),w5=S("$ZodNumber",($,w)=>{_0.init($,w),$._zod.pattern=$._zod.bag.pattern??QM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Number(E.value)}catch(A){}let G=E.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return E;let J=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return E.issues.push({expected:"number",code:"invalid_type",input:G,inst:$,...J?{received:J}:{}}),E}}),BR=S("$ZodNumber",($,w)=>{kM.init($,w),w5.init($,w)}),QR=S("$ZodBoolean",($,w)=>{_0.init($,w),$._zod.pattern=IM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Boolean(E.value)}catch(J){}let G=E.value;if(typeof G==="boolean")return E;return E.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:$}),E}}),IR=S("$ZodNull",($,w)=>{_0.init($,w),$._zod.pattern=KM,$._zod.values=new Set([null]),$._zod.parse=(E,X)=>{let G=E.value;if(G===null)return E;return E.issues.push({expected:"null",code:"invalid_type",input:G,inst:$}),E}}),KR=S("$ZodUnknown",($,w)=>{_0.init($,w),$._zod.parse=(E)=>E}),VR=S("$ZodNever",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{return E.issues.push({expected:"never",code:"invalid_type",input:E.value,inst:$}),E}});PR=S("$ZodArray",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!Array.isArray(G))return E.issues.push({expected:"array",code:"invalid_type",input:G,inst:$}),E;E.value=Array(G.length);let J=[];for(let A=0;A<G.length;A++){let D=G[A],N=w.element._zod.run({value:D,issues:[]},X);if(N instanceof Promise)J.push(N.then((W)=>nM(W,E,A)));else nM(N,E,A)}if(J.length)return Promise.all(J).then(()=>E);return E}});qR=S("$ZodObject",($,w)=>{_0.init($,w);let E=F6(()=>{let Y=Object.keys(w.shape);for(let L of Y)if(!(w.shape[L]instanceof _0))throw Error(`Invalid element at key "${L}": expected a Zod schema`);let H=u9(w.shape);return{shape:w.shape,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(H)}});C0($._zod,"propValues",()=>{let Y=w.shape,H={};for(let L in Y){let F=Y[L]._zod;if(F.values){H[L]??(H[L]=new Set);for(let j of F.values)H[L].add(j)}}return H});let X=(Y)=>{let H=new a9(["shape","payload","ctx"]),L=E.value,F=(B)=>{let Q=PE(B);return`shape[${Q}]._zod.run({ value: input[${Q}], issues: [] }, ctx)`};H.write("const input = payload.value;");let j=Object.create(null),M=0;for(let B of L.keys)j[B]=`key_${M++}`;H.write("const newResult = {}");for(let B of L.keys)if(L.optionalKeys.has(B)){let Q=j[B];H.write(`const ${Q} = ${F(B)};`);let k=PE(B);H.write(`
548
- if (${Q}.issues.length) {
549
- if (input[${k}] === undefined) {
550
- if (${k} in input) {
551
- newResult[${k}] = undefined;
529
+ ORDER BY count DESC, j.value ASC`).all();for(let O of D)G.push({name:O.tag,count:O.count,resource_type:A})}return $.json({tags:G})})});function Vj($){return{...$,created_at:$.created_at.toISOString()}}var FA,Kj,wf,Ef,Xf,Gf;var Pj=T(()=>{Ow();vw();B$();dG();J$();Q$();f$();FA=new m0,Kj=U.object({id:U.string(),from_task_id:U.string(),to_task_id:U.string(),link_type:hJ,created_at:U.string().datetime()}).openapi("TaskLink"),wf=U.object({to_task_id:U.string(),link_type:hJ}).openapi("CreateTaskLink"),Ef=i({method:"get",path:"/tasks/{id}/links",tags:["Tasks"],summary:"List links for a task (both directions)",request:{params:U.object({id:U.string()})},responses:{200:{description:"Links",content:{"application/json":{schema:U.object({links:U.array(Kj)})}}}}}),Xf=i({method:"post",path:"/tasks/{id}/links",tags:["Tasks"],summary:"Link this task to another task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:wf}}}},responses:{201:{description:"Created",content:{"application/json":{schema:Kj}}}}}),Gf=i({method:"delete",path:"/tasks/{id}/links/{linkId}",tags:["Tasks"],summary:"Remove a task link",request:{params:U.object({id:U.string(),linkId:U.string()})},responses:{204:{description:"Deleted"}}});FA.openapi(Ef,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(t.id,E)}))throw new L0("Task",E);let G=await w.query.task_links.findMany({where:kN(V(h$.from_task_id,E),V(h$.to_task_id,E))});return $.json({links:G.map(Vj)})});FA.openapi(Xf,async($)=>{let w=f(),{id:E}=$.req.valid("param"),{to_task_id:X,link_type:G}=$.req.valid("json"),[A,N]=await Promise.all([w.query.tasks.findFirst({where:V(t.id,E)}),w.query.tasks.findFirst({where:V(t.id,X)})]);if(!A)throw new L0("Task",E);if(!N)throw new L0("Task",X);if(E===X)throw new zE("Cannot link a task to itself");if(await w.query.task_links.findFirst({where:_0(V(h$.from_task_id,E),V(h$.to_task_id,X))}))throw new zE("Link already exists between these tasks");let O=r();await w.insert(h$).values({id:O,from_task_id:E,to_task_id:X,link_type:G,created_at:new Date});let W=await w.query.task_links.findFirst({where:V(h$.id,O)});if(!W)throw Error("Expected link to exist after write");return $.json(Vj(W),201)});FA.openapi(Gf,async($)=>{let w=f(),{id:E,linkId:X}=$.req.valid("param"),G=await w.query.task_links.findFirst({where:V(h$.id,X)});if(!G||G.from_task_id!==E&&G.to_task_id!==E)throw new L0("TaskLink",X);return await w.delete(h$).where(V(h$.id,X)),new Response(null,{status:204})})});function $6($){return{...$,due_at:$.due_at?.toISOString()??null,claim_expires_at:$.claim_expires_at?.toISOString()??null,prompt_id:$.prompt_id??null,required_review:$.required_review,agent_backend:$.agent_backend??null,max_review_rounds:$.max_review_rounds,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function jf($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,due_at:$.due_at?new Date($.due_at*1000).toISOString():null,claim_expires_at:$.claim_expires_at?new Date($.claim_expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Sj($){return{...$,created_at:$.created_at.toISOString()}}var EE,eD,qj,Af,Nf,Df,Of,Wf,Jf,Uf,Yf,Hf,Lf,Ff;var kj=T(()=>{Ow();vw();B$();dG();J$();Q$();PD();f$();EE=new m0,eD=U.object({id:U.string(),project_id:U.string().nullable(),title:U.string(),body:U.string().nullable(),status:QD,priority:pG,progress:U.number().int(),due_at:U.string().datetime().nullable(),tags:U.array(U.string()).nullable(),author:U.string(),claimed_by:U.string().nullable(),claim_expires_at:U.string().datetime().nullable(),prompt_id:U.string().nullable(),required_review:U.boolean(),agent_backend:U.string().nullable(),max_review_rounds:U.number().int(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Task"),qj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("Comment"),Af=U.object({title:U.string().min(1).max(500),body:U.string().optional(),project_id:U.string().optional(),status:U.enum(["todo","doing","blocked"]).optional().default("todo"),priority:pG.optional().default("normal"),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional(),author:U.string().optional().default("human"),prompt_id:U.string().optional(),required_review:U.boolean().optional().default(!0),agent_backend:U.enum(["claude","codex","cursor"]).optional(),max_review_rounds:U.number().int().min(1).optional().default(3)}).openapi("CreateTask"),Nf=U.object({title:U.string().min(1).max(500).optional(),body:U.string().optional(),status:QD.optional(),priority:pG.optional(),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional(),comment:U.string().optional()}).openapi("UpdateTask"),Df=i({method:"get",path:"/tasks",tags:["Tasks"],summary:"List tasks",request:{query:U.object({project_id:U.string().optional(),status:QD.optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Task list",content:{"application/json":{schema:U.object({tasks:U.array(eD),total:U.number()})}}}}}),Of=i({method:"get",path:"/tasks/{id}",tags:["Tasks"],summary:"Get task by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Task",content:{"application/json":{schema:eD}}}}}),Wf=i({method:"post",path:"/tasks",tags:["Tasks"],summary:"Create task",request:{body:{content:{"application/json":{schema:Af}}}},responses:{201:{description:"Created",content:{"application/json":{schema:eD}}}}}),Jf=i({method:"patch",path:"/tasks/{id}",tags:["Tasks"],summary:"Update task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:Nf}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:eD}}}}}),Uf=i({method:"delete",path:"/tasks/{id}",tags:["Tasks"],summary:"Delete task",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),Yf=U.object({ref:U.string().describe("Temporary reference ID for dependency linking, e.g. 'T1'"),title:U.string().min(1).max(500),body:U.string().optional(),priority:pG.optional().default("normal"),tags:U.array(U.string()).optional(),prompt_id:U.string().optional(),required_review:U.boolean().optional().default(!0),agent_backend:U.enum(["claude","codex","cursor"]).optional(),max_review_rounds:U.number().int().min(1).optional().default(3),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")}),Hf=i({method:"post",path:"/tasks/batch",tags:["Tasks"],summary:"Create multiple tasks with dependency links atomically",request:{body:{content:{"application/json":{schema:U.object({tasks:U.array(Yf).min(1).max(100),project_id:U.string().optional(),author:U.string().optional().default("agent")}).openapi("BatchCreateTasks")}}}},responses:{201:{description:"Created tasks with ref\u2192id mapping",content:{"application/json":{schema:U.object({created:U.number(),mapping:U.record(U.string(),U.string())})}}}}}),Lf=i({method:"get",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"List task comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(qj)})}}}}}),Ff=i({method:"post",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"Add a comment to a task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:qj}}}}});EE.openapi(Df,async($)=>{let w=f(),{project_id:E,status:X,tag:G,limit:A}=$.req.valid("query");if(G){let O=W$(),W="SELECT DISTINCT t.* FROM tasks t, json_each(t.tags) AS j WHERE j.value = ?",J=[G];if(E)W+=" AND t.project_id = ?",J.push(E);if(X)W+=" AND t.status = ?",J.push(X);W+=" ORDER BY t.updated_at DESC LIMIT ?",J.push(A);let Y=O.query(W).all(...J),H=Y.map(jf);return $.json({tasks:H,total:Y.length})}let N=[];if(E)N.push(V(t.project_id,E));if(X)N.push(V(t.status,X));let D=await w.query.tasks.findMany({where:N.length>0?_0(...N):void 0,limit:A,orderBy:[r0(t.updated_at)]});return $.json({tasks:D.map($6),total:D.length})});EE.openapi(Of,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(t.id,E)});if(!X)throw new L0("Task",E);return $.json($6(X))});EE.openapi(Wf,async($)=>{let w=f(),E=$.req.valid("json"),X=new Date,G=r();await w.insert(t).values({id:G,title:E.title,body:E.body,project_id:E.project_id,status:E.status,priority:E.priority,...E.due_at?{due_at:new Date(E.due_at)}:{},tags:E.tags,author:E.author,prompt_id:E.prompt_id,required_review:E.required_review??!0,agent_backend:E.agent_backend,max_review_rounds:E.max_review_rounds??3,created_at:X,updated_at:X});let A=await w.query.tasks.findFirst({where:V(t.id,G)});if(!A)throw Error("Expected task to exist after write");return $.json($6(A),201)});EE.openapi(Jf,async($)=>{let w=f(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.tasks.findFirst({where:V(t.id,E)}))throw new L0("Task",E);if(X.status){let D=await IX({taskId:E,status:X.status,comment:X.comment,author:"api"});if(!D.ok)throw new zE(D.error??"Transition failed")}else if(X.comment)await oE(E,X.comment,"api");let A={...X.title!==void 0?{title:X.title}:{},...X.body!==void 0?{body:X.body}:{},...X.priority!==void 0?{priority:X.priority}:{},...X.due_at!==void 0?{due_at:new Date(X.due_at)}:{},...X.tags!==void 0?{tags:X.tags}:{}};if(Object.keys(A).length>0)await w.update(t).set({...A,updated_at:new Date}).where(V(t.id,E));let N=await w.query.tasks.findFirst({where:V(t.id,E)});if(!N)throw Error("Expected updated to exist after write");return $.json($6(N))});EE.openapi(Uf,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(t.id,E)}))throw new L0("Task",E);return await w.delete(t).where(V(t.id,E)),new Response(null,{status:204})});EE.openapi(Lf,async($)=>{let w=f(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(t.id,E)}))throw new L0("Task",E);let G=await w.query.comments.findMany({where:_0(V(F$.resource_type,"task"),V(F$.resource_id,E)),orderBy:[r0(F$.created_at)]});return $.json({comments:G.map(Sj)})});EE.openapi(Ff,async($)=>{let w=f(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.tasks.findFirst({where:V(t.id,E)}))throw new L0("Task",E);let N=r(),D=new Date;await w.insert(F$).values({id:N,resource_type:"task",resource_id:E,content:X,author:G,created_at:D});let O=await w.query.comments.findFirst({where:V(F$.id,N)});if(!O)throw Error("Expected comment to exist after write");return $.json(Sj(O),201)});EE.openapi(Hf,async($)=>{let w=f(),{tasks:E,project_id:X,author:G}=$.req.valid("json"),A=new Date,N={},D=W$();D.exec("BEGIN");try{for(let O of E){let W=r();N[O.ref]=W,await w.insert(t).values({id:W,title:O.title,body:O.body,project_id:X,priority:O.priority,author:G,status:"todo",tags:O.tags,prompt_id:O.prompt_id,required_review:O.required_review??!0,agent_backend:O.agent_backend,max_review_rounds:O.max_review_rounds??3,created_at:A,updated_at:A})}for(let O of E){let W=N[O.ref];if(O.depends_on)for(let J of O.depends_on){let Y=N[J];if(!Y)continue;await w.insert(h$).values({id:r(),from_task_id:Y,to_task_id:W,link_type:"blocks",created_at:A})}if(O.subtask_of){let J=N[O.subtask_of];if(J)await w.insert(h$).values({id:r(),from_task_id:W,to_task_id:J,link_type:"subtask_of",created_at:A}),await w.insert(h$).values({id:r(),from_task_id:J,to_task_id:W,link_type:"parent_of",created_at:A})}}D.exec("COMMIT")}catch(O){throw D.exec("ROLLBACK"),O}return $.json({created:E.length,mapping:N},201)})});function bj(){let $=G0(),w=new m0;return w.use("*",aF($.api.secret)),w.onError((E,X)=>{let G=E instanceof bX?E:null;if(G)return X.json({error:G.message,code:G.code},G.statusCode);return Mf.error("Unhandled error",E),X.json({error:"Internal server error",code:"INTERNAL_ERROR"},500)}),w.route("/",Q4),w.route("/",q4),w.route("/",xw),w.route("/",QE),w.route("/",EE),w.route("/",FA),w.route("/",ZX),w.route("/",aD),w.route("/",wE),w.route("/",tD),w.route("/",b4),w.doc("/openapi.json",{openapi:"3.1.0",info:{title:"Orc API",version:a1,description:"Human + AI Orchestration Hub API"},servers:[{url:`http://${$.api.host}:${$.api.port}`,description:"Local"}]}),w.get("/docs",Z3({url:"/openapi.json"})),lF().catch(()=>{}),w}var Mf;var _j=T(()=>{C3();Ow();R$();vw();z$();RN();sF();eF();$j();wj();Ej();Uj();Hj();Mj();Tj();Bj();Qj();Pj();kj();Mf=B0("api")});var Z4={};OE(Z4,{app:()=>Zj});var _4,iE,Zj;var C4=T(()=>{R$();z$();_j();_4=B0("api"),iE=G0(),Zj=bj();Bun.serve({port:iE.api.port,hostname:iE.api.host,fetch:Zj.fetch});_4.info(`API server running on http://${iE.api.host}:${iE.api.port}`);_4.info(`OpenAPI spec: http://${iE.api.host}:${iE.api.port}/openapi.json`);_4.info(`Swagger UI: http://${iE.api.host}:${iE.api.port}/docs`)});function S($,w,E){function X(D,O){var W;Object.defineProperty(D,"_zod",{value:D._zod??{},enumerable:!1}),(W=D._zod).traits??(W.traits=new Set),D._zod.traits.add($),w(D,O);for(let J in N.prototype)if(!(J in D))Object.defineProperty(D,J,{value:N.prototype[J].bind(D)});D._zod.constr=N,D._zod.def=O}let G=E?.Parent??Object;class A extends G{}Object.defineProperty(A,"name",{value:$});function N(D){var O;let W=E?.Parent?new A:this;X(W,D),(O=W._zod).deferred??(O.deferred=[]);for(let J of W._zod.deferred)J();return W}return Object.defineProperty(N,"init",{value:X}),Object.defineProperty(N,Symbol.hasInstance,{value:(D)=>{if(E?.Parent&&D instanceof E.Parent)return!0;return D?._zod?.traits?.has($)}}),Object.defineProperty(N,"name",{value:$}),N}function Mw($){if($)Object.assign(X6,$);return X6}var _A0,ZA0,dE,X6;var vX=T(()=>{_A0=Object.freeze({status:"aborted"});ZA0=Symbol("zod_brand");dE=class dE extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};X6={}});var Q0={};OE(Q0,{unwrapMessage:()=>TA,stringifyPrimitive:()=>N6,required:()=>Xv,randomString:()=>pf,propertyKeyTypes:()=>o4,promiseAllObject:()=>mf,primitiveTypes:()=>sj,prefixIssues:()=>GE,pick:()=>af,partial:()=>Ev,optionalKeys:()=>m4,omit:()=>ef,numKeys:()=>df,nullish:()=>zA,normalizeParams:()=>s,merge:()=>wv,jsonStringifyReplacer:()=>h4,joinValues:()=>G6,issue:()=>p4,isPlainObject:()=>yX,isObject:()=>xX,getSizableOrigin:()=>ej,getParsedType:()=>lf,getLengthableOrigin:()=>IA,getEnumValues:()=>n4,getElementAtPath:()=>of,floatSafeRemainder:()=>c4,finalizeIssue:()=>gw,extend:()=>$v,escapeRegex:()=>lE,esc:()=>S1,defineLazy:()=>f0,createTransparentProxy:()=>sf,clone:()=>XE,cleanRegex:()=>BA,cleanEnum:()=>Gv,captureStackTrace:()=>A6,cached:()=>RA,assignProp:()=>r4,assertNotEqual:()=>hf,assertNever:()=>rf,assertIs:()=>cf,assertEqual:()=>nf,assert:()=>tf,allowsEval:()=>t4,aborted:()=>k1,NUMBER_FORMAT_RANGES:()=>i4,Class:()=>$M,BIGINT_FORMAT_RANGES:()=>aj});function nf($){return $}function hf($){return $}function cf($){}function rf($){throw Error()}function tf($){}function n4($){let w=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,G])=>w.indexOf(+X)===-1).map(([X,G])=>G)}function G6($,w="|"){return $.map((E)=>N6(E)).join(w)}function h4($,w){if(typeof w==="bigint")return w.toString();return w}function RA($){return{get value(){{let E=$();return Object.defineProperty(this,"value",{value:E}),E}throw Error("cached value already set")}}}function zA($){return $===null||$===void 0}function BA($){let w=$.startsWith("^")?1:0,E=$.endsWith("$")?$.length-1:$.length;return $.slice(w,E)}function c4($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,A=Number.parseInt($.toFixed(G).replace(".","")),N=Number.parseInt(w.toFixed(G).replace(".",""));return A%N/10**G}function f0($,w,E){Object.defineProperty($,w,{get(){{let G=E();return $[w]=G,G}throw Error("cached value already set")},set(G){Object.defineProperty($,w,{value:G})},configurable:!0})}function r4($,w,E){Object.defineProperty($,w,{value:E,writable:!0,enumerable:!0,configurable:!0})}function of($,w){if(!w)return $;return w.reduce((E,X)=>E?.[X],$)}function mf($){let w=Object.keys($),E=w.map((X)=>$[X]);return Promise.all(E).then((X)=>{let G={};for(let A=0;A<w.length;A++)G[w[A]]=X[A];return G})}function pf($=10){let E="";for(let X=0;X<$;X++)E+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return E}function S1($){return JSON.stringify($)}function xX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yX($){if(xX($)===!1)return!1;let w=$.constructor;if(w===void 0)return!0;let E=w.prototype;if(xX(E)===!1)return!1;if(Object.prototype.hasOwnProperty.call(E,"isPrototypeOf")===!1)return!1;return!0}function df($){let w=0;for(let E in $)if(Object.prototype.hasOwnProperty.call($,E))w++;return w}function lE($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XE($,w,E){let X=new $._zod.constr(w??$._zod.def);if(!w||E?.parent)X._zod.parent=$;return X}function s($){let w=$;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function sf($){let w;return new Proxy({},{get(E,X,G){return w??(w=$()),Reflect.get(w,X,G)},set(E,X,G,A){return w??(w=$()),Reflect.set(w,X,G,A)},has(E,X){return w??(w=$()),Reflect.has(w,X)},deleteProperty(E,X){return w??(w=$()),Reflect.deleteProperty(w,X)},ownKeys(E){return w??(w=$()),Reflect.ownKeys(w)},getOwnPropertyDescriptor(E,X){return w??(w=$()),Reflect.getOwnPropertyDescriptor(w,X)},defineProperty(E,X,G){return w??(w=$()),Reflect.defineProperty(w,X,G)}})}function N6($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function m4($){return Object.keys($).filter((w)=>{return $[w]._zod.optin==="optional"&&$[w]._zod.optout==="optional"})}function af($,w){let E={},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;E[G]=X.shape[G]}return XE($,{...$._zod.def,shape:E,checks:[]})}function ef($,w){let E={...$._zod.def.shape},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete E[G]}return XE($,{...$._zod.def,shape:E,checks:[]})}function $v($,w){if(!yX(w))throw Error("Invalid input to extend: expected a plain object");let E={...$._zod.def,get shape(){let X={...$._zod.def.shape,...w};return r4(this,"shape",X),X},checks:[]};return XE($,E)}function wv($,w){return XE($,{...$._zod.def,get shape(){let E={...$._zod.def.shape,...w._zod.def.shape};return r4(this,"shape",E),E},catchall:w._zod.def.catchall,checks:[]})}function Ev($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let A in E){if(!(A in X))throw Error(`Unrecognized key: "${A}"`);if(!E[A])continue;G[A]=$?new $({type:"optional",innerType:X[A]}):X[A]}else for(let A in X)G[A]=$?new $({type:"optional",innerType:X[A]}):X[A];return XE(w,{...w._zod.def,shape:G,checks:[]})}function Xv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let A in E){if(!(A in G))throw Error(`Unrecognized key: "${A}"`);if(!E[A])continue;G[A]=new $({type:"nonoptional",innerType:X[A]})}else for(let A in X)G[A]=new $({type:"nonoptional",innerType:X[A]});return XE(w,{...w._zod.def,shape:G,checks:[]})}function k1($,w=0){for(let E=w;E<$.issues.length;E++)if($.issues[E]?.continue!==!0)return!0;return!1}function GE($,w){return w.map((E)=>{var X;return(X=E).path??(X.path=[]),E.path.unshift($),E})}function TA($){return typeof $==="string"?$:$?.message}function gw($,w,E){let X={...$,path:$.path??[]};if(!$.message){let G=TA($.inst?._zod.def?.error?.($))??TA(w?.error?.($))??TA(E.customError?.($))??TA(E.localeError?.($))??"Invalid input";X.message=G}if(delete X.inst,delete X.continue,!w?.reportInput)delete X.input;return X}function ej($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function IA($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function p4(...$){let[w,E,X]=$;if(typeof w==="string")return{message:w,code:"custom",input:E,inst:X};return{...w}}function Gv($){return Object.entries($).filter(([w,E])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}class $M{constructor(...$){}}var A6,t4,lf=($)=>{let w=typeof $;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},o4,sj,i4,aj;var KE=T(()=>{A6=Error.captureStackTrace?Error.captureStackTrace:(...$)=>{};t4=RA(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});o4=new Set(["string","number","symbol"]),sj=new Set(["string","number","bigint","boolean","symbol","undefined"]);i4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},aj={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function EM($,w=(E)=>E.message){let E={},X=[];for(let G of $.issues)if(G.path.length>0)E[G.path[0]]=E[G.path[0]]||[],E[G.path[0]].push(w(G));else X.push(w(G));return{formErrors:X,fieldErrors:E}}function XM($,w){let E=w||function(A){return A.message},X={_errors:[]},G=(A)=>{for(let N of A.issues)if(N.code==="invalid_union"&&N.errors.length)N.errors.map((D)=>G({issues:D}));else if(N.code==="invalid_key")G({issues:N.issues});else if(N.code==="invalid_element")G({issues:N.issues});else if(N.path.length===0)X._errors.push(E(N));else{let D=X,O=0;while(O<N.path.length){let W=N.path[O];if(O!==N.path.length-1)D[W]=D[W]||{_errors:[]};else D[W]=D[W]||{_errors:[]},D[W]._errors.push(E(N));D=D[W],O++}}};return G($),X}var wM=($,w)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:w,enumerable:!1}),Object.defineProperty($,"message",{get(){return JSON.stringify(w,h4,2)},enumerable:!0}),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},D6,d4;var l4=T(()=>{vX();KE();D6=S("$ZodError",wM),d4=S("$ZodError",wM,{Parent:Error})});var GM=($)=>(w,E,X,G)=>{let A=X?Object.assign(X,{async:!1}):{async:!1},N=w._zod.run({value:E,issues:[]},A);if(N instanceof Promise)throw new dE;if(N.issues.length){let D=new(G?.Err??$)(N.issues.map((O)=>gw(O,A,Mw())));throw A6(D,G?.callee),D}return N.value},AM=($)=>async(w,E,X,G)=>{let A=X?Object.assign(X,{async:!0}):{async:!0},N=w._zod.run({value:E,issues:[]},A);if(N instanceof Promise)N=await N;if(N.issues.length){let D=new(G?.Err??$)(N.issues.map((O)=>gw(O,A,Mw())));throw A6(D,G?.callee),D}return N.value},s4=($)=>(w,E,X)=>{let G=X?{...X,async:!1}:{async:!1},A=w._zod.run({value:E,issues:[]},G);if(A instanceof Promise)throw new dE;return A.issues.length?{success:!1,error:new($??D6)(A.issues.map((N)=>gw(N,G,Mw())))}:{success:!0,data:A.value}},QA,a4=($)=>async(w,E,X)=>{let G=X?Object.assign(X,{async:!0}):{async:!0},A=w._zod.run({value:E,issues:[]},G);if(A instanceof Promise)A=await A;return A.issues.length?{success:!1,error:new $(A.issues.map((N)=>gw(N,G,Mw())))}:{success:!0,data:A.value}},O6;var e4=T(()=>{vX();l4();KE();QA=s4(d4),O6=a4(d4)});function FM(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function VM($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function PM($){return new RegExp(`^${VM($)}$`)}function qM($){let w=VM({precision:$.precision}),E=["Z"];if($.local)E.push("");if($.offset)E.push("([+-]\\d{2}:\\d{2})");let X=`${w}(?:${E.join("|")})`;return new RegExp(`^${QM}T(?:${X})$`)}var NM,DM,OM,WM,JM,UM,YM,HM,$8=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},LM,jM,MM,TM,RM,zM,w8,BM,IM,QM="(?:(?:\\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])))",KM,SM=($)=>{let w=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)},kM,bM,_M,ZM,CM,fM;var W6=T(()=>{NM=/^[cC][^\s-]{8,}$/,DM=/^[0-9a-z]+$/,OM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,WM=/^[0-9a-vA-V]{20}$/,JM=/^[A-Za-z0-9]{27}$/,UM=/^[a-zA-Z0-9_-]{21}$/,YM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,HM=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,LM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;jM=/^(?:(?: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])$/,MM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,TM=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,RM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,w8=/^[A-Za-z0-9_-]*$/,BM=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,IM=/^\+(?:[0-9]){6,14}[0-9]$/,KM=new RegExp(`^${QM}$`);kM=/^\d+$/,bM=/^-?\d+(?:\.\d+)?/i,_M=/true|false/i,ZM=/null/i,CM=/^[^A-Z]*$/,fM=/^[^a-z]*$/});var y$,vM,X8,G8,xM,yM,gM,uM,nM,KA,hM,cM,rM,tM,oM,mM,iM;var J6=T(()=>{vX();W6();KE();y$=S("$ZodCheck",($,w)=>{var E;$._zod??($._zod={}),$._zod.def=w,(E=$._zod).onattach??(E.onattach=[])}),vM={number:"number",bigint:"bigint",object:"date"},X8=S("$ZodCheckLessThan",($,w)=>{y$.init($,w);let E=vM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,A=(w.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<A)if(w.inclusive)G.maximum=w.value;else G.exclusiveMaximum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value<=w.value:X.value<w.value)return;X.issues.push({origin:E,code:"too_big",maximum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),G8=S("$ZodCheckGreaterThan",($,w)=>{y$.init($,w);let E=vM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,A=(w.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>A)if(w.inclusive)G.minimum=w.value;else G.exclusiveMinimum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value>=w.value:X.value>w.value)return;X.issues.push({origin:E,code:"too_small",minimum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),xM=S("$ZodCheckMultipleOf",($,w)=>{y$.init($,w),$._zod.onattach.push((E)=>{var X;(X=E._zod.bag).multipleOf??(X.multipleOf=w.value)}),$._zod.check=(E)=>{if(typeof E.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof E.value==="bigint"?E.value%w.value===BigInt(0):c4(E.value,w.value)===0)return;E.issues.push({origin:typeof E.value,code:"not_multiple_of",divisor:w.value,input:E.value,inst:$,continue:!w.abort})}}),yM=S("$ZodCheckNumberFormat",($,w)=>{y$.init($,w),w.format=w.format||"float64";let E=w.format?.includes("int"),X=E?"int":"number",[G,A]=i4[w.format];$._zod.onattach.push((N)=>{let D=N._zod.bag;if(D.format=w.format,D.minimum=G,D.maximum=A,E)D.pattern=kM}),$._zod.check=(N)=>{let D=N.value;if(E){if(!Number.isInteger(D)){N.issues.push({expected:X,format:w.format,code:"invalid_type",input:D,inst:$});return}if(!Number.isSafeInteger(D)){if(D>0)N.issues.push({input:D,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});else N.issues.push({input:D,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});return}}if(D<G)N.issues.push({origin:"number",input:D,code:"too_small",minimum:G,inclusive:!0,inst:$,continue:!w.abort});if(D>A)N.issues.push({origin:"number",input:D,code:"too_big",maximum:A,inst:$})}}),gM=S("$ZodCheckMaxLength",($,w)=>{var E;y$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!zA(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<G)X._zod.bag.maximum=w.maximum}),$._zod.check=(X)=>{let G=X.value;if(G.length<=w.maximum)return;let N=IA(G);X.issues.push({origin:N,code:"too_big",maximum:w.maximum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),uM=S("$ZodCheckMinLength",($,w)=>{var E;y$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!zA(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>G)X._zod.bag.minimum=w.minimum}),$._zod.check=(X)=>{let G=X.value;if(G.length>=w.minimum)return;let N=IA(G);X.issues.push({origin:N,code:"too_small",minimum:w.minimum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),nM=S("$ZodCheckLengthEquals",($,w)=>{var E;y$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!zA(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.minimum=w.length,G.maximum=w.length,G.length=w.length}),$._zod.check=(X)=>{let G=X.value,A=G.length;if(A===w.length)return;let N=IA(G),D=A>w.length;X.issues.push({origin:N,...D?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!w.abort})}}),KA=S("$ZodCheckStringFormat",($,w)=>{var E,X;if(y$.init($,w),$._zod.onattach.push((G)=>{let A=G._zod.bag;if(A.format=w.format,w.pattern)A.patterns??(A.patterns=new Set),A.patterns.add(w.pattern)}),w.pattern)(E=$._zod).check??(E.check=(G)=>{if(w.pattern.lastIndex=0,w.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:w.format,input:G.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:$,continue:!w.abort})});else(X=$._zod).check??(X.check=()=>{})}),hM=S("$ZodCheckRegex",($,w)=>{KA.init($,w),$._zod.check=(E)=>{if(w.pattern.lastIndex=0,w.pattern.test(E.value))return;E.issues.push({origin:"string",code:"invalid_format",format:"regex",input:E.value,pattern:w.pattern.toString(),inst:$,continue:!w.abort})}}),cM=S("$ZodCheckLowerCase",($,w)=>{w.pattern??(w.pattern=CM),KA.init($,w)}),rM=S("$ZodCheckUpperCase",($,w)=>{w.pattern??(w.pattern=fM),KA.init($,w)}),tM=S("$ZodCheckIncludes",($,w)=>{y$.init($,w);let E=lE(w.includes),X=new RegExp(typeof w.position==="number"?`^.{${w.position}}${E}`:E);w.pattern=X,$._zod.onattach.push((G)=>{let A=G._zod.bag;A.patterns??(A.patterns=new Set),A.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.includes(w.includes,w.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:G.value,inst:$,continue:!w.abort})}}),oM=S("$ZodCheckStartsWith",($,w)=>{y$.init($,w);let E=new RegExp(`^${lE(w.prefix)}.*`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.startsWith(w.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:X.value,inst:$,continue:!w.abort})}}),mM=S("$ZodCheckEndsWith",($,w)=>{y$.init($,w);let E=new RegExp(`.*${lE(w.suffix)}$`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.endsWith(w.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:X.value,inst:$,continue:!w.abort})}}),iM=S("$ZodCheckOverwrite",($,w)=>{y$.init($,w),$._zod.check=(E)=>{E.value=w.tx(E.value)}})});class A8{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let E=$.split(`
530
+ `).filter((A)=>A),X=Math.min(...E.map((A)=>A.length-A.trimStart().length)),G=E.map((A)=>A.slice(X)).map((A)=>" ".repeat(this.indent*2)+A);for(let A of G)this.content.push(A)}compile(){let $=Function,w=this?.args,X=[...(this?.content??[""]).map((G)=>` ${G}`)];return new $(...w,X.join(`
531
+ `))}}var dM;var N8=T(()=>{dM={major:4,minor:0,patch:0}});function KT($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Nv($){if(!w8.test($))return!1;let w=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),E=w.padEnd(Math.ceil(w.length/4)*4,"=");return KT(E)}function Dv($,w=null){try{let E=$.split(".");if(E.length!==3)return!1;let[X]=E;if(!X)return!1;let G=JSON.parse(atob(X));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&(!("alg"in G)||G.alg!==w))return!1;return!0}catch{return!1}}function lM($,w,E){if($.issues.length)w.issues.push(...GE(E,$.issues));w.value[E]=$.value}function U6($,w,E){if($.issues.length)w.issues.push(...GE(E,$.issues));w.value[E]=$.value}function sM($,w,E,X){if($.issues.length)if(X[E]===void 0)if(E in X)w.value[E]=void 0;else w.value[E]=$.value;else w.issues.push(...GE(E,$.issues));else if($.value===void 0){if(E in X)w.value[E]=void 0}else w.value[E]=$.value}function aM($,w,E,X){for(let G of $)if(G.issues.length===0)return w.value=G.value,w;return w.issues.push({code:"invalid_union",input:w.value,inst:E,errors:$.map((G)=>G.issues.map((A)=>gw(A,X,Mw())))}),w}function D8($,w){if($===w)return{valid:!0,data:$};if($ instanceof Date&&w instanceof Date&&+$===+w)return{valid:!0,data:$};if(yX($)&&yX(w)){let E=Object.keys(w),X=Object.keys($).filter((A)=>E.indexOf(A)!==-1),G={...$,...w};for(let A of X){let N=D8($[A],w[A]);if(!N.valid)return{valid:!1,mergeErrorPath:[A,...N.mergeErrorPath]};G[A]=N.data}return{valid:!0,data:G}}if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return{valid:!1,mergeErrorPath:[]};let E=[];for(let X=0;X<$.length;X++){let G=$[X],A=w[X],N=D8(G,A);if(!N.valid)return{valid:!1,mergeErrorPath:[X,...N.mergeErrorPath]};E.push(N.data)}return{valid:!0,data:E}}return{valid:!1,mergeErrorPath:[]}}function eM($,w,E){if(w.issues.length)$.issues.push(...w.issues);if(E.issues.length)$.issues.push(...E.issues);if(k1($))return $;let X=D8(w.value,E.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}function $T($,w){if($.value===void 0)$.value=w.defaultValue;return $}function wT($,w){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:w});return $}function ET($,w,E){if(k1($))return $;return w.out._zod.run({value:$.value,issues:$.issues},E)}function XT($){return $.value=Object.freeze($.value),$}function GT($,w,E,X){if(!$){let G={code:"custom",input:E,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)G.params=X._zod.def.params;w.issues.push(p4(G))}}var v0,Y6,n0,AT,NT,DT,OT,WT,JT,UT,YT,HT,LT,FT,jT,MT,TT,RT,zT,BT,IT,QT,VT,PT,qT,ST,O8,kT,bT,_T,ZT,CT,fT,vT,W8,xT,yT,gT,uT,nT,hT,cT,rT,tT,oT,mT,iT,pT,dT,lT;var sT=T(()=>{J6();vX();e4();W6();KE();N8();KE();v0=S("$ZodType",($,w)=>{var E;$??($={}),$._zod.def=w,$._zod.bag=$._zod.bag||{},$._zod.version=dM;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let G of X)for(let A of G._zod.onattach)A($);if(X.length===0)(E=$._zod).deferred??(E.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let G=(A,N,D)=>{let O=k1(A),W;for(let J of N){if(J._zod.def.when){if(!J._zod.def.when(A))continue}else if(O)continue;let Y=A.issues.length,H=J._zod.check(A);if(H instanceof Promise&&D?.async===!1)throw new dE;if(W||H instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await H,A.issues.length===Y)return;if(!O)O=k1(A,Y)});else{if(A.issues.length===Y)continue;if(!O)O=k1(A,Y)}}if(W)return W.then(()=>{return A});return A};$._zod.run=(A,N)=>{let D=$._zod.parse(A,N);if(D instanceof Promise){if(N.async===!1)throw new dE;return D.then((O)=>G(O,X,N))}return G(D,X,N)}}$["~standard"]={validate:(G)=>{try{let A=QA($,G);return A.success?{value:A.data}:{issues:A.error?.issues}}catch(A){return O6($,G).then((N)=>N.success?{value:N.data}:{issues:N.error?.issues})}},vendor:"zod",version:1}}),Y6=S("$ZodString",($,w)=>{v0.init($,w),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??SM($._zod.bag),$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=String(E.value)}catch(G){}if(typeof E.value==="string")return E;return E.issues.push({expected:"string",code:"invalid_type",input:E.value,inst:$}),E}}),n0=S("$ZodStringFormat",($,w)=>{KA.init($,w),Y6.init($,w)}),AT=S("$ZodGUID",($,w)=>{w.pattern??(w.pattern=HM),n0.init($,w)}),NT=S("$ZodUUID",($,w)=>{if(w.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(X===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=$8(X))}else w.pattern??(w.pattern=$8());n0.init($,w)}),DT=S("$ZodEmail",($,w)=>{w.pattern??(w.pattern=LM),n0.init($,w)}),OT=S("$ZodURL",($,w)=>{n0.init($,w),$._zod.check=(E)=>{try{let X=E.value,G=new URL(X),A=G.href;if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(G.hostname))E.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:BM.source,input:E.value,inst:$,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))E.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:E.value,inst:$,continue:!w.abort})}if(!X.endsWith("/")&&A.endsWith("/"))E.value=A.slice(0,-1);else E.value=A;return}catch(X){E.issues.push({code:"invalid_format",format:"url",input:E.value,inst:$,continue:!w.abort})}}}),WT=S("$ZodEmoji",($,w)=>{w.pattern??(w.pattern=FM()),n0.init($,w)}),JT=S("$ZodNanoID",($,w)=>{w.pattern??(w.pattern=UM),n0.init($,w)}),UT=S("$ZodCUID",($,w)=>{w.pattern??(w.pattern=NM),n0.init($,w)}),YT=S("$ZodCUID2",($,w)=>{w.pattern??(w.pattern=DM),n0.init($,w)}),HT=S("$ZodULID",($,w)=>{w.pattern??(w.pattern=OM),n0.init($,w)}),LT=S("$ZodXID",($,w)=>{w.pattern??(w.pattern=WM),n0.init($,w)}),FT=S("$ZodKSUID",($,w)=>{w.pattern??(w.pattern=JM),n0.init($,w)}),jT=S("$ZodISODateTime",($,w)=>{w.pattern??(w.pattern=qM(w)),n0.init($,w)}),MT=S("$ZodISODate",($,w)=>{w.pattern??(w.pattern=KM),n0.init($,w)}),TT=S("$ZodISOTime",($,w)=>{w.pattern??(w.pattern=PM(w)),n0.init($,w)}),RT=S("$ZodISODuration",($,w)=>{w.pattern??(w.pattern=YM),n0.init($,w)}),zT=S("$ZodIPv4",($,w)=>{w.pattern??(w.pattern=jM),n0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv4"})}),BT=S("$ZodIPv6",($,w)=>{w.pattern??(w.pattern=MM),n0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv6"}),$._zod.check=(E)=>{try{new URL(`http://[${E.value}]`)}catch{E.issues.push({code:"invalid_format",format:"ipv6",input:E.value,inst:$,continue:!w.abort})}}}),IT=S("$ZodCIDRv4",($,w)=>{w.pattern??(w.pattern=TM),n0.init($,w)}),QT=S("$ZodCIDRv6",($,w)=>{w.pattern??(w.pattern=RM),n0.init($,w),$._zod.check=(E)=>{let[X,G]=E.value.split("/");try{if(!G)throw Error();let A=Number(G);if(`${A}`!==G)throw Error();if(A<0||A>128)throw Error();new URL(`http://[${X}]`)}catch{E.issues.push({code:"invalid_format",format:"cidrv6",input:E.value,inst:$,continue:!w.abort})}}});VT=S("$ZodBase64",($,w)=>{w.pattern??(w.pattern=zM),n0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64"}),$._zod.check=(E)=>{if(KT(E.value))return;E.issues.push({code:"invalid_format",format:"base64",input:E.value,inst:$,continue:!w.abort})}});PT=S("$ZodBase64URL",($,w)=>{w.pattern??(w.pattern=w8),n0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64url"}),$._zod.check=(E)=>{if(Nv(E.value))return;E.issues.push({code:"invalid_format",format:"base64url",input:E.value,inst:$,continue:!w.abort})}}),qT=S("$ZodE164",($,w)=>{w.pattern??(w.pattern=IM),n0.init($,w)});ST=S("$ZodJWT",($,w)=>{n0.init($,w),$._zod.check=(E)=>{if(Dv(E.value,w.alg))return;E.issues.push({code:"invalid_format",format:"jwt",input:E.value,inst:$,continue:!w.abort})}}),O8=S("$ZodNumber",($,w)=>{v0.init($,w),$._zod.pattern=$._zod.bag.pattern??bM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Number(E.value)}catch(N){}let G=E.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return E;let A=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return E.issues.push({expected:"number",code:"invalid_type",input:G,inst:$,...A?{received:A}:{}}),E}}),kT=S("$ZodNumber",($,w)=>{yM.init($,w),O8.init($,w)}),bT=S("$ZodBoolean",($,w)=>{v0.init($,w),$._zod.pattern=_M,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Boolean(E.value)}catch(A){}let G=E.value;if(typeof G==="boolean")return E;return E.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:$}),E}}),_T=S("$ZodNull",($,w)=>{v0.init($,w),$._zod.pattern=ZM,$._zod.values=new Set([null]),$._zod.parse=(E,X)=>{let G=E.value;if(G===null)return E;return E.issues.push({expected:"null",code:"invalid_type",input:G,inst:$}),E}}),ZT=S("$ZodUnknown",($,w)=>{v0.init($,w),$._zod.parse=(E)=>E}),CT=S("$ZodNever",($,w)=>{v0.init($,w),$._zod.parse=(E,X)=>{return E.issues.push({expected:"never",code:"invalid_type",input:E.value,inst:$}),E}});fT=S("$ZodArray",($,w)=>{v0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!Array.isArray(G))return E.issues.push({expected:"array",code:"invalid_type",input:G,inst:$}),E;E.value=Array(G.length);let A=[];for(let N=0;N<G.length;N++){let D=G[N],O=w.element._zod.run({value:D,issues:[]},X);if(O instanceof Promise)A.push(O.then((W)=>lM(W,E,N)));else lM(O,E,N)}if(A.length)return Promise.all(A).then(()=>E);return E}});vT=S("$ZodObject",($,w)=>{v0.init($,w);let E=RA(()=>{let Y=Object.keys(w.shape);for(let L of Y)if(!(w.shape[L]instanceof v0))throw Error(`Invalid element at key "${L}": expected a Zod schema`);let H=m4(w.shape);return{shape:w.shape,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(H)}});f0($._zod,"propValues",()=>{let Y=w.shape,H={};for(let L in Y){let F=Y[L]._zod;if(F.values){H[L]??(H[L]=new Set);for(let j of F.values)H[L].add(j)}}return H});let X=(Y)=>{let H=new A8(["shape","payload","ctx"]),L=E.value,F=(B)=>{let I=S1(B);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};H.write("const input = payload.value;");let j=Object.create(null),M=0;for(let B of L.keys)j[B]=`key_${M++}`;H.write("const newResult = {}");for(let B of L.keys)if(L.optionalKeys.has(B)){let I=j[B];H.write(`const ${I} = ${F(B)};`);let C=S1(B);H.write(`
532
+ if (${I}.issues.length) {
533
+ if (input[${C}] === undefined) {
534
+ if (${C} in input) {
535
+ newResult[${C}] = undefined;
552
536
  }
553
537
  } else {
554
538
  payload.issues = payload.issues.concat(
555
- ${Q}.issues.map((iss) => ({
539
+ ${I}.issues.map((iss) => ({
556
540
  ...iss,
557
- path: iss.path ? [${k}, ...iss.path] : [${k}],
541
+ path: iss.path ? [${C}, ...iss.path] : [${C}],
558
542
  }))
559
543
  );
560
544
  }
561
- } else if (${Q}.value === undefined) {
562
- if (${k} in input) newResult[${k}] = undefined;
545
+ } else if (${I}.value === undefined) {
546
+ if (${C} in input) newResult[${C}] = undefined;
563
547
  } else {
564
- newResult[${k}] = ${Q}.value;
548
+ newResult[${C}] = ${I}.value;
565
549
  }
566
- `)}else{let Q=j[B];H.write(`const ${Q} = ${F(B)};`),H.write(`
567
- if (${Q}.issues.length) payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({
550
+ `)}else{let I=j[B];H.write(`const ${I} = ${F(B)};`),H.write(`
551
+ if (${I}.issues.length) payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
568
552
  ...iss,
569
- path: iss.path ? [${PE(B)}, ...iss.path] : [${PE(B)}]
570
- })));`),H.write(`newResult[${PE(B)}] = ${Q}.value`)}H.write("payload.value = newResult;"),H.write("return payload;");let z=H.compile();return(B,Q)=>z(Y,B,Q)},G,J=CX,A=!$4.jitless,N=A&&y9.value,W=w.catchall,O;$._zod.parse=(Y,H)=>{O??(O=E.value);let L=Y.value;if(!J(L))return Y.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),Y;let F=[];if(A&&N&&H?.async===!1&&H.jitless!==!0){if(!G)G=X(w.shape);Y=G(Y,H)}else{Y.value={};let Q=O.shape;for(let k of O.keys){let v=Q[k],C=v._zod.run({value:L[k],issues:[]},H),n=v._zod.optin==="optional"&&v._zod.optout==="optional";if(C instanceof Promise)F.push(C.then((T0)=>n?mM(T0,Y,k,L):N4(T0,Y,k)));else if(n)mM(C,Y,k,L);else N4(C,Y,k)}}if(!W)return F.length?Promise.all(F).then(()=>Y):Y;let j=[],M=O.keySet,z=W._zod,B=z.def.type;for(let Q of Object.keys(L)){if(M.has(Q))continue;if(B==="never"){j.push(Q);continue}let k=z.run({value:L[Q],issues:[]},H);if(k instanceof Promise)F.push(k.then((v)=>N4(v,Y,Q)));else N4(k,Y,Q)}if(j.length)Y.issues.push({code:"unrecognized_keys",keys:j,input:L,inst:$});if(!F.length)return Y;return Promise.all(F).then(()=>{return Y})}});E5=S("$ZodUnion",($,w)=>{_0.init($,w),C0($._zod,"optin",()=>w.options.some((E)=>E._zod.optin==="optional")?"optional":void 0),C0($._zod,"optout",()=>w.options.some((E)=>E._zod.optout==="optional")?"optional":void 0),C0($._zod,"values",()=>{if(w.options.every((E)=>E._zod.values))return new Set(w.options.flatMap((E)=>Array.from(E._zod.values)));return}),C0($._zod,"pattern",()=>{if(w.options.every((E)=>E._zod.pattern)){let E=w.options.map((X)=>X._zod.pattern);return new RegExp(`^(${E.map((X)=>M6(X.source)).join("|")})$`)}return}),$._zod.parse=(E,X)=>{let G=!1,J=[];for(let A of w.options){let D=A._zod.run({value:E.value,issues:[]},X);if(D instanceof Promise)J.push(D),G=!0;else{if(D.issues.length===0)return D;J.push(D)}}if(!G)return rM(J,E,$,X);return Promise.all(J).then((A)=>{return rM(A,E,$,X)})}}),SR=S("$ZodDiscriminatedUnion",($,w)=>{E5.init($,w);let E=$._zod.parse;C0($._zod,"propValues",()=>{let G={};for(let J of w.options){let A=J._zod.propValues;if(!A||Object.keys(A).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(J)}"`);for(let[D,N]of Object.entries(A)){if(!G[D])G[D]=new Set;for(let W of N)G[D].add(W)}}return G});let X=F6(()=>{let G=w.options,J=new Map;for(let A of G){let D=A._zod.propValues[w.discriminator];if(!D||D.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(A)}"`);for(let N of D){if(J.has(N))throw Error(`Duplicate discriminator value "${String(N)}"`);J.set(N,A)}}return J});$._zod.parse=(G,J)=>{let A=G.value;if(!CX(A))return G.issues.push({code:"invalid_type",expected:"object",input:A,inst:$}),G;let D=X.value.get(A?.[w.discriminator]);if(D)return D._zod.run(G,J);if(w.unionFallback)return E(G,J);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:A,path:[w.discriminator],inst:$}),G}}),kR=S("$ZodIntersection",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value,J=w.left._zod.run({value:G,issues:[]},X),A=w.right._zod.run({value:G,issues:[]},X);if(J instanceof Promise||A instanceof Promise)return Promise.all([J,A]).then(([N,W])=>{return pM(E,N,W)});return pM(E,J,A)}});bR=S("$ZodRecord",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!_X(G))return E.issues.push({expected:"record",code:"invalid_type",input:G,inst:$}),E;let J=[];if(w.keyType._zod.values){let A=w.keyType._zod.values;E.value={};for(let N of A)if(typeof N==="string"||typeof N==="number"||typeof N==="symbol"){let W=w.valueType._zod.run({value:G[N],issues:[]},X);if(W instanceof Promise)J.push(W.then((O)=>{if(O.issues.length)E.issues.push(...Jw(N,O.issues));E.value[N]=O.value}));else{if(W.issues.length)E.issues.push(...Jw(N,W.issues));E.value[N]=W.value}}let D;for(let N in G)if(!A.has(N))D=D??[],D.push(N);if(D&&D.length>0)E.issues.push({code:"unrecognized_keys",input:G,inst:$,keys:D})}else{E.value={};for(let A of Reflect.ownKeys(G)){if(A==="__proto__")continue;let D=w.keyType._zod.run({value:A,issues:[]},X);if(D instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(D.issues.length){E.issues.push({origin:"record",code:"invalid_key",issues:D.issues.map((W)=>u1(W,X,R1())),input:A,path:[A],inst:$}),E.value[D.value]=D.value;continue}let N=w.valueType._zod.run({value:G[A],issues:[]},X);if(N instanceof Promise)J.push(N.then((W)=>{if(W.issues.length)E.issues.push(...Jw(A,W.issues));E.value[D.value]=W.value}));else{if(N.issues.length)E.issues.push(...Jw(A,N.issues));E.value[D.value]=N.value}}}if(J.length)return Promise.all(J).then(()=>E);return E}}),ZR=S("$ZodEnum",($,w)=>{_0.init($,w);let E=_9(w.entries);$._zod.values=new Set(E),$._zod.pattern=new RegExp(`^(${E.filter((X)=>g9.has(typeof X)).map((X)=>typeof X==="string"?dw(X):X.toString()).join("|")})$`),$._zod.parse=(X,G)=>{let J=X.value;if($._zod.values.has(J))return X;return X.issues.push({code:"invalid_value",values:E,input:J,inst:$}),X}}),CR=S("$ZodLiteral",($,w)=>{_0.init($,w),$._zod.values=new Set(w.values),$._zod.pattern=new RegExp(`^(${w.values.map((E)=>typeof E==="string"?dw(E):E?E.toString():String(E)).join("|")})$`),$._zod.parse=(E,X)=>{let G=E.value;if($._zod.values.has(G))return E;return E.issues.push({code:"invalid_value",values:w.values,input:G,inst:$}),E}}),_R=S("$ZodTransform",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=w.transform(E.value,E);if(X.async)return(G instanceof Promise?G:Promise.resolve(G)).then((A)=>{return E.value=A,E});if(G instanceof Promise)throw new iw;return E.value=G,E}}),vR=S("$ZodOptional",($,w)=>{_0.init($,w),$._zod.optin="optional",$._zod.optout="optional",C0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),C0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${M6(E.source)})?$`):void 0}),$._zod.parse=(E,X)=>{if(w.innerType._zod.optin==="optional")return w.innerType._zod.run(E,X);if(E.value===void 0)return E;return w.innerType._zod.run(E,X)}}),fR=S("$ZodNullable",($,w)=>{_0.init($,w),C0($._zod,"optin",()=>w.innerType._zod.optin),C0($._zod,"optout",()=>w.innerType._zod.optout),C0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${M6(E.source)}|null)$`):void 0}),C0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),$._zod.parse=(E,X)=>{if(E.value===null)return E;return w.innerType._zod.run(E,X)}}),xR=S("$ZodDefault",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)return E.value=w.defaultValue,E;let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>oM(J,w));return oM(G,w)}});yR=S("$ZodPrefault",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)E.value=w.defaultValue;return w.innerType._zod.run(E,X)}}),gR=S("$ZodNonOptional",($,w)=>{_0.init($,w),C0($._zod,"values",()=>{let E=w.innerType._zod.values;return E?new Set([...E].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>tM(J,$));return tM(G,$)}});uR=S("$ZodCatch",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"optout",()=>w.innerType._zod.optout),C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>{if(E.value=J.value,J.issues.length)E.value=w.catchValue({...E,error:{issues:J.issues.map((A)=>u1(A,X,R1()))},input:E.value}),E.issues=[];return E});if(E.value=G.value,G.issues.length)E.value=w.catchValue({...E,error:{issues:G.issues.map((J)=>u1(J,X,R1()))},input:E.value}),E.issues=[];return E}}),hR=S("$ZodPipe",($,w)=>{_0.init($,w),C0($._zod,"values",()=>w.in._zod.values),C0($._zod,"optin",()=>w.in._zod.optin),C0($._zod,"optout",()=>w.out._zod.optout),$._zod.parse=(E,X)=>{let G=w.in._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>iM(J,w,X));return iM(G,w,X)}});cR=S("$ZodReadonly",($,w)=>{_0.init($,w),C0($._zod,"propValues",()=>w.innerType._zod.propValues),C0($._zod,"values",()=>w.innerType._zod.values),C0($._zod,"optin",()=>w.innerType._zod.optin),C0($._zod,"optout",()=>w.innerType._zod.optout),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then(dM);return dM(G)}});nR=S("$ZodCustom",($,w)=>{b$.init($,w),_0.init($,w),$._zod.parse=(E,X)=>{return E},$._zod.check=(E)=>{let X=E.value,G=w.fn(X);if(G instanceof Promise)return G.then((J)=>lM(J,E,X,$));lM(G,E,X,$);return}})});function X5(){return{localeError:iv()}}var tv=($)=>{let w=typeof $;switch(w){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return w},iv=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(X){return $[X]??null}let E={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${tv(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${X4(X.values[0])}`;return`Invalid option: expected one of ${w4(X.values,"|")}`;case"too_big":{let G=X.inclusive?"<=":"<",J=w(X.origin);if(J)return`Too big: expected ${X.origin??"value"} to have ${G}${X.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${G}${X.maximum.toString()}`}case"too_small":{let G=X.inclusive?">=":">",J=w(X.origin);if(J)return`Too small: expected ${X.origin} to have ${G}${X.minimum.toString()} ${J.unit}`;return`Too small: expected ${X.origin} to be ${G}${X.minimum.toString()}`}case"invalid_format":{let G=X;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${E[G.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${w4(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};var rR=R(()=>{Kw()});var O4=()=>{};class pR{constructor(){this._map=new Map,this._idmap=new Map}add($,...w){let E=w[0];if(this._map.set($,E),E&&typeof E==="object"&&"id"in E){if(this._idmap.has(E.id))throw Error(`ID ${E.id} already exists in the registry`);this._idmap.set(E.id,$)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove($){let w=this._map.get($);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete($),this}get($){let w=$._zod.parent;if(w){let E={...this.get(w)??{}};return delete E.id,{...E,...this._map.get($)}}return this._map.get($)}has($){return this._map.has($)}}function dv(){return new pR}var cG0,nG0,B6;var oR=R(()=>{cG0=Symbol("ZodOutput"),nG0=Symbol("ZodInput");B6=dv()});function tR($,w){return new $({type:"string",...l(w)})}function iR($,w){return new $({type:"string",format:"email",check:"string_format",abort:!1,...l(w)})}function J5($,w){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...l(w)})}function dR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...l(w)})}function lR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...l(w)})}function sR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...l(w)})}function aR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...l(w)})}function eR($,w){return new $({type:"string",format:"url",check:"string_format",abort:!1,...l(w)})}function $z($,w){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...l(w)})}function wz($,w){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...l(w)})}function Ez($,w){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...l(w)})}function Xz($,w){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...l(w)})}function Gz($,w){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...l(w)})}function Jz($,w){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...l(w)})}function Az($,w){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...l(w)})}function Dz($,w){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...l(w)})}function Nz($,w){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...l(w)})}function Wz($,w){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...l(w)})}function Oz($,w){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...l(w)})}function Uz($,w){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...l(w)})}function Yz($,w){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...l(w)})}function Hz($,w){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...l(w)})}function Lz($,w){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...l(w)})}function Fz($,w){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...l(w)})}function jz($,w){return new $({type:"string",format:"date",check:"string_format",...l(w)})}function Mz($,w){return new $({type:"string",format:"time",check:"string_format",precision:null,...l(w)})}function Rz($,w){return new $({type:"string",format:"duration",check:"string_format",...l(w)})}function zz($,w){return new $({type:"number",checks:[],...l(w)})}function Tz($,w){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...l(w)})}function Bz($,w){return new $({type:"boolean",...l(w)})}function Qz($,w){return new $({type:"null",...l(w)})}function Iz($){return new $({type:"unknown"})}function Kz($,w){return new $({type:"never",...l(w)})}function U4($,w){return new l9({check:"less_than",...l(w),value:$,inclusive:!1})}function Q6($,w){return new l9({check:"less_than",...l(w),value:$,inclusive:!0})}function Y4($,w){return new s9({check:"greater_than",...l(w),value:$,inclusive:!1})}function I6($,w){return new s9({check:"greater_than",...l(w),value:$,inclusive:!0})}function H4($,w){return new SM({check:"multiple_of",...l(w),value:$})}function L4($,w){return new bM({check:"max_length",...l(w),maximum:$})}function vX($,w){return new ZM({check:"min_length",...l(w),minimum:$})}function F4($,w){return new CM({check:"length_equals",...l(w),length:$})}function A5($,w){return new _M({check:"string_format",format:"regex",...l(w),pattern:$})}function D5($){return new vM({check:"string_format",format:"lowercase",...l($)})}function N5($){return new fM({check:"string_format",format:"uppercase",...l($)})}function W5($,w){return new xM({check:"string_format",format:"includes",...l(w),includes:$})}function O5($,w){return new yM({check:"string_format",format:"starts_with",...l(w),prefix:$})}function U5($,w){return new gM({check:"string_format",format:"ends_with",...l(w),suffix:$})}function SE($){return new uM({check:"overwrite",tx:$})}function Y5($){return SE((w)=>w.normalize($))}function H5(){return SE(($)=>$.trim())}function L5(){return SE(($)=>$.toLowerCase())}function F5(){return SE(($)=>$.toUpperCase())}function Vz($,w,E){return new $({type:"array",element:w,...l(E)})}function Pz($,w,E){let X=l(E);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:w,...X})}function qz($,w,E){return new $({type:"custom",check:"custom",fn:w,...l(E)})}var Sz=R(()=>{D4();Kw()});var kz=()=>{};var bz=()=>{};var Zz=()=>{};var z1=R(()=>{Kw();A4();O4();Zz();ZX();o9();m9();mR();D4();e9();oR();kz();Sz();bz()});var Cz=R(()=>{z1()});var _z=()=>{};var vz=()=>{};var fz=()=>{};var xz=()=>{};var yz=R(()=>{z1();O4();fz();xz();Cz();_z();vz()});var gz=R(()=>{yz()});var uz=R(()=>{gz()});function xX($){return!!$._zod}function lw($,w){if(xX($))return z6($,w);return $.safeParse(w)}function j4($){if(!$)return;let w;if(xX($))w=$._zod?.def?.shape;else w=$.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function hz($){if(xX($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let E=$._def;if(E){if(E.value!==void 0)return E.value;if(Array.isArray(E.values)&&E.values.length>0)return E.values[0]}let X=$.value;if(X!==void 0)return X;return}var M4=R(()=>{uz()});var j5=R(()=>{z1()});var K6={};Ww(K6,{time:()=>z5,duration:()=>T5,datetime:()=>M5,date:()=>R5,ZodISOTime:()=>mz,ZodISODuration:()=>rz,ZodISODateTime:()=>cz,ZodISODate:()=>nz});function M5($){return Fz(cz,$)}function R5($){return jz(nz,$)}function z5($){return Mz(mz,$)}function T5($){return Rz(rz,$)}var cz,nz,mz,rz;var B5=R(()=>{z1();Q5();cz=S("ZodISODateTime",($,w)=>{NR.init($,w),o0.init($,w)});nz=S("ZodISODate",($,w)=>{WR.init($,w),o0.init($,w)});mz=S("ZodISOTime",($,w)=>{OR.init($,w),o0.init($,w)});rz=S("ZodISODuration",($,w)=>{UR.init($,w),o0.init($,w)})});var pz=($,w)=>{G4.init($,w),$.name="ZodError",Object.defineProperties($,{format:{value:(E)=>dj($,E)},flatten:{value:(E)=>ij($,E)},addIssue:{value:(E)=>$.issues.push(E)},addIssues:{value:(E)=>$.issues.push(...E)},isEmpty:{get(){return $.issues.length===0}}})},C60,V6;var I5=R(()=>{z1();z1();C60=S("ZodError",pz),V6=S("ZodError",pz,{Parent:Error})});var oz,tz,iz,dz;var K5=R(()=>{z1();I5();oz=lj(V6),tz=sj(V6),iz=r9(V6),dz=p9(V6)});function P($){return tR(Af,$)}function q0($){return zz($T,$)}function sz($){return Tz(Kf,$)}function F$($){return Bz(Vf,$)}function q5($){return Qz(Pf,$)}function t0(){return Iz(qf)}function kf($){return Kz(Sf,$)}function j0($,w){return Vz(bf,$,w)}function u($,w){let E={type:"object",get shape(){return B0.assignProp(this,"shape",{...$}),this.shape},...B0.normalizeParams(w)};return new wT(E)}function h$($,w){return new wT({type:"object",get shape(){return B0.assignProp(this,"shape",{...$}),this.shape},catchall:t0(),...B0.normalizeParams(w)})}function v0($,w){return new ET({type:"union",options:$,...B0.normalizeParams(w)})}function S5($,w,E){return new Zf({type:"union",options:w,discriminator:$,...B0.normalizeParams(E)})}function z4($,w){return new Cf({type:"intersection",left:$,right:w})}function i0($,w,E){return new _f({type:"record",keyType:$,valueType:w,...B0.normalizeParams(E)})}function a$($,w){let E=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new V5({type:"enum",entries:E,...B0.normalizeParams(w)})}function p($,w){return new vf({type:"literal",values:Array.isArray($)?$:[$],...B0.normalizeParams(w)})}function XT($){return new ff({type:"transform",transform:$})}function a0($){return new GT({type:"optional",innerType:$})}function az($){return new xf({type:"nullable",innerType:$})}function gf($,w){return new yf({type:"default",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function hf($,w){return new uf({type:"prefault",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function cf($,w){return new JT({type:"nonoptional",innerType:$,...B0.normalizeParams(w)})}function mf($,w){return new nf({type:"catch",innerType:$,catchValue:typeof w==="function"?w:()=>w})}function P5($,w){return new rf({type:"pipe",in:$,out:w})}function of($){return new pf({type:"readonly",innerType:$})}function tf($){let w=new b$({check:"custom"});return w._zod.check=$,w}function DT($,w){return Pz(AT,$??(()=>!0),w)}function df($,w={}){return qz(AT,$,w)}function lf($){let w=tf((E)=>{return E.addIssue=(X)=>{if(typeof X==="string")E.issues.push(B0.issue(X,E.value,w._zod.def));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=E.value),G.inst??(G.inst=w),G.continue??(G.continue=!w._zod.def.abort),E.issues.push(B0.issue(G))}},$(E.value,E)});return w}function k5($,w){return P5(XT($),w)}var e0,ez,Af,o0,Df,lz,R4,Nf,Wf,Of,Uf,Yf,Hf,Lf,Ff,jf,Mf,Rf,zf,Tf,Bf,Qf,If,$T,Kf,Vf,Pf,qf,Sf,bf,wT,ET,Zf,Cf,_f,V5,vf,ff,GT,xf,yf,uf,JT,nf,rf,pf,AT;var Q5=R(()=>{z1();z1();j5();B5();K5();e0=S("ZodType",($,w)=>{return _0.init($,w),$.def=w,Object.defineProperty($,"_def",{value:w}),$.check=(...E)=>{return $.clone({...w,checks:[...w.checks??[],...E.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]})},$.clone=(E,X)=>Gw($,E,X),$.brand=()=>$,$.register=(E,X)=>{return E.add($,X),$},$.parse=(E,X)=>oz($,E,X,{callee:$.parse}),$.safeParse=(E,X)=>iz($,E,X),$.parseAsync=async(E,X)=>tz($,E,X,{callee:$.parseAsync}),$.safeParseAsync=async(E,X)=>dz($,E,X),$.spa=$.safeParseAsync,$.refine=(E,X)=>$.check(df(E,X)),$.superRefine=(E)=>$.check(lf(E)),$.overwrite=(E)=>$.check(SE(E)),$.optional=()=>a0($),$.nullable=()=>az($),$.nullish=()=>a0(az($)),$.nonoptional=(E)=>cf($,E),$.array=()=>j0($),$.or=(E)=>v0([$,E]),$.and=(E)=>z4($,E),$.transform=(E)=>P5($,XT(E)),$.default=(E)=>gf($,E),$.prefault=(E)=>hf($,E),$.catch=(E)=>mf($,E),$.pipe=(E)=>P5($,E),$.readonly=()=>of($),$.describe=(E)=>{let X=$.clone();return B6.add(X,{description:E}),X},Object.defineProperty($,"description",{get(){return B6.get($)?.description},configurable:!0}),$.meta=(...E)=>{if(E.length===0)return B6.get($);let X=$.clone();return B6.add(X,E[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),ez=S("_ZodString",($,w)=>{W4.init($,w),e0.init($,w);let E=$._zod.bag;$.format=E.format??null,$.minLength=E.minimum??null,$.maxLength=E.maximum??null,$.regex=(...X)=>$.check(A5(...X)),$.includes=(...X)=>$.check(W5(...X)),$.startsWith=(...X)=>$.check(O5(...X)),$.endsWith=(...X)=>$.check(U5(...X)),$.min=(...X)=>$.check(vX(...X)),$.max=(...X)=>$.check(L4(...X)),$.length=(...X)=>$.check(F4(...X)),$.nonempty=(...X)=>$.check(vX(1,...X)),$.lowercase=(X)=>$.check(D5(X)),$.uppercase=(X)=>$.check(N5(X)),$.trim=()=>$.check(H5()),$.normalize=(...X)=>$.check(Y5(...X)),$.toLowerCase=()=>$.check(L5()),$.toUpperCase=()=>$.check(F5())}),Af=S("ZodString",($,w)=>{W4.init($,w),ez.init($,w),$.email=(E)=>$.check(iR(Df,E)),$.url=(E)=>$.check(eR(Nf,E)),$.jwt=(E)=>$.check(Lz(If,E)),$.emoji=(E)=>$.check($z(Wf,E)),$.guid=(E)=>$.check(J5(lz,E)),$.uuid=(E)=>$.check(dR(R4,E)),$.uuidv4=(E)=>$.check(lR(R4,E)),$.uuidv6=(E)=>$.check(sR(R4,E)),$.uuidv7=(E)=>$.check(aR(R4,E)),$.nanoid=(E)=>$.check(wz(Of,E)),$.guid=(E)=>$.check(J5(lz,E)),$.cuid=(E)=>$.check(Ez(Uf,E)),$.cuid2=(E)=>$.check(Xz(Yf,E)),$.ulid=(E)=>$.check(Gz(Hf,E)),$.base64=(E)=>$.check(Uz(Tf,E)),$.base64url=(E)=>$.check(Yz(Bf,E)),$.xid=(E)=>$.check(Jz(Lf,E)),$.ksuid=(E)=>$.check(Az(Ff,E)),$.ipv4=(E)=>$.check(Dz(jf,E)),$.ipv6=(E)=>$.check(Nz(Mf,E)),$.cidrv4=(E)=>$.check(Wz(Rf,E)),$.cidrv6=(E)=>$.check(Oz(zf,E)),$.e164=(E)=>$.check(Hz(Qf,E)),$.datetime=(E)=>$.check(M5(E)),$.date=(E)=>$.check(R5(E)),$.time=(E)=>$.check(z5(E)),$.duration=(E)=>$.check(T5(E))});o0=S("ZodStringFormat",($,w)=>{u0.init($,w),ez.init($,w)}),Df=S("ZodEmail",($,w)=>{eM.init($,w),o0.init($,w)}),lz=S("ZodGUID",($,w)=>{sM.init($,w),o0.init($,w)}),R4=S("ZodUUID",($,w)=>{aM.init($,w),o0.init($,w)}),Nf=S("ZodURL",($,w)=>{$R.init($,w),o0.init($,w)}),Wf=S("ZodEmoji",($,w)=>{wR.init($,w),o0.init($,w)}),Of=S("ZodNanoID",($,w)=>{ER.init($,w),o0.init($,w)}),Uf=S("ZodCUID",($,w)=>{XR.init($,w),o0.init($,w)}),Yf=S("ZodCUID2",($,w)=>{GR.init($,w),o0.init($,w)}),Hf=S("ZodULID",($,w)=>{JR.init($,w),o0.init($,w)}),Lf=S("ZodXID",($,w)=>{AR.init($,w),o0.init($,w)}),Ff=S("ZodKSUID",($,w)=>{DR.init($,w),o0.init($,w)}),jf=S("ZodIPv4",($,w)=>{YR.init($,w),o0.init($,w)}),Mf=S("ZodIPv6",($,w)=>{HR.init($,w),o0.init($,w)}),Rf=S("ZodCIDRv4",($,w)=>{LR.init($,w),o0.init($,w)}),zf=S("ZodCIDRv6",($,w)=>{FR.init($,w),o0.init($,w)}),Tf=S("ZodBase64",($,w)=>{MR.init($,w),o0.init($,w)}),Bf=S("ZodBase64URL",($,w)=>{RR.init($,w),o0.init($,w)}),Qf=S("ZodE164",($,w)=>{zR.init($,w),o0.init($,w)}),If=S("ZodJWT",($,w)=>{TR.init($,w),o0.init($,w)}),$T=S("ZodNumber",($,w)=>{w5.init($,w),e0.init($,w),$.gt=(X,G)=>$.check(Y4(X,G)),$.gte=(X,G)=>$.check(I6(X,G)),$.min=(X,G)=>$.check(I6(X,G)),$.lt=(X,G)=>$.check(U4(X,G)),$.lte=(X,G)=>$.check(Q6(X,G)),$.max=(X,G)=>$.check(Q6(X,G)),$.int=(X)=>$.check(sz(X)),$.safe=(X)=>$.check(sz(X)),$.positive=(X)=>$.check(Y4(0,X)),$.nonnegative=(X)=>$.check(I6(0,X)),$.negative=(X)=>$.check(U4(0,X)),$.nonpositive=(X)=>$.check(Q6(0,X)),$.multipleOf=(X,G)=>$.check(H4(X,G)),$.step=(X,G)=>$.check(H4(X,G)),$.finite=()=>$;let E=$._zod.bag;$.minValue=Math.max(E.minimum??Number.NEGATIVE_INFINITY,E.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(E.maximum??Number.POSITIVE_INFINITY,E.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(E.format??"").includes("int")||Number.isSafeInteger(E.multipleOf??0.5),$.isFinite=!0,$.format=E.format??null});Kf=S("ZodNumberFormat",($,w)=>{BR.init($,w),$T.init($,w)});Vf=S("ZodBoolean",($,w)=>{QR.init($,w),e0.init($,w)});Pf=S("ZodNull",($,w)=>{IR.init($,w),e0.init($,w)});qf=S("ZodUnknown",($,w)=>{KR.init($,w),e0.init($,w)});Sf=S("ZodNever",($,w)=>{VR.init($,w),e0.init($,w)});bf=S("ZodArray",($,w)=>{PR.init($,w),e0.init($,w),$.element=w.element,$.min=(E,X)=>$.check(vX(E,X)),$.nonempty=(E)=>$.check(vX(1,E)),$.max=(E,X)=>$.check(L4(E,X)),$.length=(E,X)=>$.check(F4(E,X)),$.unwrap=()=>$.element});wT=S("ZodObject",($,w)=>{qR.init($,w),e0.init($,w),B0.defineLazy($,"shape",()=>w.shape),$.keyof=()=>a$(Object.keys($._zod.def.shape)),$.catchall=(E)=>$.clone({...$._zod.def,catchall:E}),$.passthrough=()=>$.clone({...$._zod.def,catchall:t0()}),$.loose=()=>$.clone({...$._zod.def,catchall:t0()}),$.strict=()=>$.clone({...$._zod.def,catchall:kf()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(E)=>{return B0.extend($,E)},$.merge=(E)=>B0.merge($,E),$.pick=(E)=>B0.pick($,E),$.omit=(E)=>B0.omit($,E),$.partial=(...E)=>B0.partial(GT,$,E[0]),$.required=(...E)=>B0.required(JT,$,E[0])});ET=S("ZodUnion",($,w)=>{E5.init($,w),e0.init($,w),$.options=w.options});Zf=S("ZodDiscriminatedUnion",($,w)=>{ET.init($,w),SR.init($,w)});Cf=S("ZodIntersection",($,w)=>{kR.init($,w),e0.init($,w)});_f=S("ZodRecord",($,w)=>{bR.init($,w),e0.init($,w),$.keyType=w.keyType,$.valueType=w.valueType});V5=S("ZodEnum",($,w)=>{ZR.init($,w),e0.init($,w),$.enum=w.entries,$.options=Object.values(w.entries);let E=new Set(Object.keys(w.entries));$.extract=(X,G)=>{let J={};for(let A of X)if(E.has(A))J[A]=w.entries[A];else throw Error(`Key ${A} not found in enum`);return new V5({...w,checks:[],...B0.normalizeParams(G),entries:J})},$.exclude=(X,G)=>{let J={...w.entries};for(let A of X)if(E.has(A))delete J[A];else throw Error(`Key ${A} not found in enum`);return new V5({...w,checks:[],...B0.normalizeParams(G),entries:J})}});vf=S("ZodLiteral",($,w)=>{CR.init($,w),e0.init($,w),$.values=new Set(w.values),Object.defineProperty($,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});ff=S("ZodTransform",($,w)=>{_R.init($,w),e0.init($,w),$._zod.parse=(E,X)=>{E.addIssue=(J)=>{if(typeof J==="string")E.issues.push(B0.issue(J,E.value,w));else{let A=J;if(A.fatal)A.continue=!1;A.code??(A.code="custom"),A.input??(A.input=E.value),A.inst??(A.inst=$),A.continue??(A.continue=!0),E.issues.push(B0.issue(A))}};let G=w.transform(E.value,E);if(G instanceof Promise)return G.then((J)=>{return E.value=J,E});return E.value=G,E}});GT=S("ZodOptional",($,w)=>{vR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});xf=S("ZodNullable",($,w)=>{fR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});yf=S("ZodDefault",($,w)=>{xR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});uf=S("ZodPrefault",($,w)=>{yR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});JT=S("ZodNonOptional",($,w)=>{gR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});nf=S("ZodCatch",($,w)=>{uR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});rf=S("ZodPipe",($,w)=>{hR.init($,w),e0.init($,w),$.in=w.in,$.out=w.out});pf=S("ZodReadonly",($,w)=>{cR.init($,w),e0.init($,w)});AT=S("ZodCustom",($,w)=>{nR.init($,w),e0.init($,w)})});var NT=()=>{};var WT=()=>{};var OT=R(()=>{z1();z1();rR();O4();B5();WT();Q5();j5();I5();K5();NT();R1(X5())});var UT=R(()=>{OT()});var YT=R(()=>{UT()});var b5="2025-11-25",HT,sw="io.modelcontextprotocol/related-task",B4="2.0",T$,LT,FT,qJ0,ef,$x,Z5,W1,P6,jT=($)=>P6.safeParse($).success,B$,T1,B1,Q$,Q4,MT,C5=($)=>MT.safeParse($).success,RT,zT=($)=>RT.safeParse($).success,_5,q6=($)=>_5.safeParse($).success,L0,v5,TT=($)=>v5.safeParse($).success,BT,SJ0,I4,wx,K4,Ex,S6,yX,QT,Xx,Gx,Jx,Ax,Dx,Nx,f5,Wx,Ox,x5,V4,Ux,Yx,P4,Hx,k6,b6,Lx,Z6,gX,Fx,C6,q4,S4,k4,kJ0,b4,Z4,C4,IT,KT,VT,y5,PT,_6,uX,qT,jx,Mx,Rx,zx,Tx,g5,Bx,Qx,Ix,Kx,Vx,Px,qx,Sx,kx,bx,Zx,Cx,_x,vx,fx,xx,u5,h5,c5,yx,gx,ux,n5,hx,cx,nx,mx,rx,ST,m5,px,_4,bJ0,ox,v6,tx,ZJ0,f6,ix,r5,dx,lx,sx,ax,ex,$y,wy,T4,Ey,Xy,Gy,x6,p5,Jy,Ay,Dy,Ny,Wy,Oy,Uy,Yy,Hy,Ly,Fy,jy,My,Ry,zy,Ty,By,Qy,hX,Iy,Ky,Vy,Py,qy,Sy,ky,o5,by,CJ0,_J0,vJ0,fJ0,xJ0,yJ0,A0,kT;var cX=R(()=>{YT();HT=[b5,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],T$=DT(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),LT=v0([P(),q0().int()]),FT=P(),qJ0=h$({ttl:v0([q0(),q5()]).optional(),pollInterval:q0().optional()}),ef=u({ttl:q0().optional()}),$x=u({taskId:P()}),Z5=h$({progressToken:LT.optional(),[sw]:$x.optional()}),W1=u({_meta:Z5.optional()}),P6=W1.extend({task:ef.optional()}),B$=u({method:P(),params:W1.loose().optional()}),T1=u({_meta:Z5.optional()}),B1=u({method:P(),params:T1.loose().optional()}),Q$=h$({_meta:Z5.optional()}),Q4=v0([P(),q0().int()]),MT=u({jsonrpc:p(B4),id:Q4,...B$.shape}).strict(),RT=u({jsonrpc:p(B4),...B1.shape}).strict(),_5=u({jsonrpc:p(B4),id:Q4,result:Q$}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(L0||(L0={}));v5=u({jsonrpc:p(B4),id:Q4.optional(),error:u({code:q0().int(),message:P(),data:t0().optional()})}).strict(),BT=v0([MT,RT,_5,v5]),SJ0=v0([_5,v5]),I4=Q$.strict(),wx=T1.extend({requestId:Q4.optional(),reason:P().optional()}),K4=B1.extend({method:p("notifications/cancelled"),params:wx}),Ex=u({src:P(),mimeType:P().optional(),sizes:j0(P()).optional(),theme:a$(["light","dark"]).optional()}),S6=u({icons:j0(Ex).optional()}),yX=u({name:P(),title:P().optional()}),QT=yX.extend({...yX.shape,...S6.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),Xx=z4(u({applyDefaults:F$().optional()}),i0(P(),t0())),Gx=k5(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},z4(u({form:Xx.optional(),url:T$.optional()}),i0(P(),t0()).optional())),Jx=h$({list:T$.optional(),cancel:T$.optional(),requests:h$({sampling:h$({createMessage:T$.optional()}).optional(),elicitation:h$({create:T$.optional()}).optional()}).optional()}),Ax=h$({list:T$.optional(),cancel:T$.optional(),requests:h$({tools:h$({call:T$.optional()}).optional()}).optional()}),Dx=u({experimental:i0(P(),T$).optional(),sampling:u({context:T$.optional(),tools:T$.optional()}).optional(),elicitation:Gx.optional(),roots:u({listChanged:F$().optional()}).optional(),tasks:Jx.optional()}),Nx=W1.extend({protocolVersion:P(),capabilities:Dx,clientInfo:QT}),f5=B$.extend({method:p("initialize"),params:Nx}),Wx=u({experimental:i0(P(),T$).optional(),logging:T$.optional(),completions:T$.optional(),prompts:u({listChanged:F$().optional()}).optional(),resources:u({subscribe:F$().optional(),listChanged:F$().optional()}).optional(),tools:u({listChanged:F$().optional()}).optional(),tasks:Ax.optional()}),Ox=Q$.extend({protocolVersion:P(),capabilities:Wx,serverInfo:QT,instructions:P().optional()}),x5=B1.extend({method:p("notifications/initialized"),params:T1.optional()}),V4=B$.extend({method:p("ping"),params:W1.optional()}),Ux=u({progress:q0(),total:a0(q0()),message:a0(P())}),Yx=u({...T1.shape,...Ux.shape,progressToken:LT}),P4=B1.extend({method:p("notifications/progress"),params:Yx}),Hx=W1.extend({cursor:FT.optional()}),k6=B$.extend({params:Hx.optional()}),b6=Q$.extend({nextCursor:FT.optional()}),Lx=a$(["working","input_required","completed","failed","cancelled"]),Z6=u({taskId:P(),status:Lx,ttl:v0([q0(),q5()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:a0(q0()),statusMessage:a0(P())}),gX=Q$.extend({task:Z6}),Fx=T1.merge(Z6),C6=B1.extend({method:p("notifications/tasks/status"),params:Fx}),q4=B$.extend({method:p("tasks/get"),params:W1.extend({taskId:P()})}),S4=Q$.merge(Z6),k4=B$.extend({method:p("tasks/result"),params:W1.extend({taskId:P()})}),kJ0=Q$.loose(),b4=k6.extend({method:p("tasks/list")}),Z4=b6.extend({tasks:j0(Z6)}),C4=B$.extend({method:p("tasks/cancel"),params:W1.extend({taskId:P()})}),IT=Q$.merge(Z6),KT=u({uri:P(),mimeType:a0(P()),_meta:i0(P(),t0()).optional()}),VT=KT.extend({text:P()}),y5=P().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),PT=KT.extend({blob:y5}),_6=a$(["user","assistant"]),uX=u({audience:j0(_6).optional(),priority:q0().min(0).max(1).optional(),lastModified:K6.datetime({offset:!0}).optional()}),qT=u({...yX.shape,...S6.shape,uri:P(),description:a0(P()),mimeType:a0(P()),annotations:uX.optional(),_meta:a0(h$({}))}),jx=u({...yX.shape,...S6.shape,uriTemplate:P(),description:a0(P()),mimeType:a0(P()),annotations:uX.optional(),_meta:a0(h$({}))}),Mx=k6.extend({method:p("resources/list")}),Rx=b6.extend({resources:j0(qT)}),zx=k6.extend({method:p("resources/templates/list")}),Tx=b6.extend({resourceTemplates:j0(jx)}),g5=W1.extend({uri:P()}),Bx=g5,Qx=B$.extend({method:p("resources/read"),params:Bx}),Ix=Q$.extend({contents:j0(v0([VT,PT]))}),Kx=B1.extend({method:p("notifications/resources/list_changed"),params:T1.optional()}),Vx=g5,Px=B$.extend({method:p("resources/subscribe"),params:Vx}),qx=g5,Sx=B$.extend({method:p("resources/unsubscribe"),params:qx}),kx=T1.extend({uri:P()}),bx=B1.extend({method:p("notifications/resources/updated"),params:kx}),Zx=u({name:P(),description:a0(P()),required:a0(F$())}),Cx=u({...yX.shape,...S6.shape,description:a0(P()),arguments:a0(j0(Zx)),_meta:a0(h$({}))}),_x=k6.extend({method:p("prompts/list")}),vx=b6.extend({prompts:j0(Cx)}),fx=W1.extend({name:P(),arguments:i0(P(),P()).optional()}),xx=B$.extend({method:p("prompts/get"),params:fx}),u5=u({type:p("text"),text:P(),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),h5=u({type:p("image"),data:y5,mimeType:P(),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),c5=u({type:p("audio"),data:y5,mimeType:P(),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),yx=u({type:p("tool_use"),name:P(),id:P(),input:i0(P(),t0()),_meta:i0(P(),t0()).optional()}),gx=u({type:p("resource"),resource:v0([VT,PT]),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),ux=qT.extend({type:p("resource_link")}),n5=v0([u5,h5,c5,ux,gx]),hx=u({role:_6,content:n5}),cx=Q$.extend({description:P().optional(),messages:j0(hx)}),nx=B1.extend({method:p("notifications/prompts/list_changed"),params:T1.optional()}),mx=u({title:P().optional(),readOnlyHint:F$().optional(),destructiveHint:F$().optional(),idempotentHint:F$().optional(),openWorldHint:F$().optional()}),rx=u({taskSupport:a$(["required","optional","forbidden"]).optional()}),ST=u({...yX.shape,...S6.shape,description:P().optional(),inputSchema:u({type:p("object"),properties:i0(P(),T$).optional(),required:j0(P()).optional()}).catchall(t0()),outputSchema:u({type:p("object"),properties:i0(P(),T$).optional(),required:j0(P()).optional()}).catchall(t0()).optional(),annotations:mx.optional(),execution:rx.optional(),_meta:i0(P(),t0()).optional()}),m5=k6.extend({method:p("tools/list")}),px=b6.extend({tools:j0(ST)}),_4=Q$.extend({content:j0(n5).default([]),structuredContent:i0(P(),t0()).optional(),isError:F$().optional()}),bJ0=_4.or(Q$.extend({toolResult:t0()})),ox=P6.extend({name:P(),arguments:i0(P(),t0()).optional()}),v6=B$.extend({method:p("tools/call"),params:ox}),tx=B1.extend({method:p("notifications/tools/list_changed"),params:T1.optional()}),ZJ0=u({autoRefresh:F$().default(!0),debounceMs:q0().int().nonnegative().default(300)}),f6=a$(["debug","info","notice","warning","error","critical","alert","emergency"]),ix=W1.extend({level:f6}),r5=B$.extend({method:p("logging/setLevel"),params:ix}),dx=T1.extend({level:f6,logger:P().optional(),data:t0()}),lx=B1.extend({method:p("notifications/message"),params:dx}),sx=u({name:P().optional()}),ax=u({hints:j0(sx).optional(),costPriority:q0().min(0).max(1).optional(),speedPriority:q0().min(0).max(1).optional(),intelligencePriority:q0().min(0).max(1).optional()}),ex=u({mode:a$(["auto","required","none"]).optional()}),$y=u({type:p("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:j0(n5).default([]),structuredContent:u({}).loose().optional(),isError:F$().optional(),_meta:i0(P(),t0()).optional()}),wy=S5("type",[u5,h5,c5]),T4=S5("type",[u5,h5,c5,yx,$y]),Ey=u({role:_6,content:v0([T4,j0(T4)]),_meta:i0(P(),t0()).optional()}),Xy=P6.extend({messages:j0(Ey),modelPreferences:ax.optional(),systemPrompt:P().optional(),includeContext:a$(["none","thisServer","allServers"]).optional(),temperature:q0().optional(),maxTokens:q0().int(),stopSequences:j0(P()).optional(),metadata:T$.optional(),tools:j0(ST).optional(),toolChoice:ex.optional()}),Gy=B$.extend({method:p("sampling/createMessage"),params:Xy}),x6=Q$.extend({model:P(),stopReason:a0(a$(["endTurn","stopSequence","maxTokens"]).or(P())),role:_6,content:wy}),p5=Q$.extend({model:P(),stopReason:a0(a$(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:_6,content:v0([T4,j0(T4)])}),Jy=u({type:p("boolean"),title:P().optional(),description:P().optional(),default:F$().optional()}),Ay=u({type:p("string"),title:P().optional(),description:P().optional(),minLength:q0().optional(),maxLength:q0().optional(),format:a$(["email","uri","date","date-time"]).optional(),default:P().optional()}),Dy=u({type:a$(["number","integer"]),title:P().optional(),description:P().optional(),minimum:q0().optional(),maximum:q0().optional(),default:q0().optional()}),Ny=u({type:p("string"),title:P().optional(),description:P().optional(),enum:j0(P()),default:P().optional()}),Wy=u({type:p("string"),title:P().optional(),description:P().optional(),oneOf:j0(u({const:P(),title:P()})),default:P().optional()}),Oy=u({type:p("string"),title:P().optional(),description:P().optional(),enum:j0(P()),enumNames:j0(P()).optional(),default:P().optional()}),Uy=v0([Ny,Wy]),Yy=u({type:p("array"),title:P().optional(),description:P().optional(),minItems:q0().optional(),maxItems:q0().optional(),items:u({type:p("string"),enum:j0(P())}),default:j0(P()).optional()}),Hy=u({type:p("array"),title:P().optional(),description:P().optional(),minItems:q0().optional(),maxItems:q0().optional(),items:u({anyOf:j0(u({const:P(),title:P()}))}),default:j0(P()).optional()}),Ly=v0([Yy,Hy]),Fy=v0([Oy,Uy,Ly]),jy=v0([Fy,Jy,Ay,Dy]),My=P6.extend({mode:p("form").optional(),message:P(),requestedSchema:u({type:p("object"),properties:i0(P(),jy),required:j0(P()).optional()})}),Ry=P6.extend({mode:p("url"),message:P(),elicitationId:P(),url:P().url()}),zy=v0([My,Ry]),Ty=B$.extend({method:p("elicitation/create"),params:zy}),By=T1.extend({elicitationId:P()}),Qy=B1.extend({method:p("notifications/elicitation/complete"),params:By}),hX=Q$.extend({action:a$(["accept","decline","cancel"]),content:k5(($)=>$===null?void 0:$,i0(P(),v0([P(),q0(),F$(),j0(P())])).optional())}),Iy=u({type:p("ref/resource"),uri:P()}),Ky=u({type:p("ref/prompt"),name:P()}),Vy=W1.extend({ref:v0([Ky,Iy]),argument:u({name:P(),value:P()}),context:u({arguments:i0(P(),P()).optional()}).optional()}),Py=B$.extend({method:p("completion/complete"),params:Vy}),qy=Q$.extend({completion:h$({values:j0(P()).max(100),total:a0(q0().int()),hasMore:a0(F$())})}),Sy=u({uri:P().startsWith("file://"),name:P().optional(),_meta:i0(P(),t0()).optional()}),ky=B$.extend({method:p("roots/list"),params:W1.optional()}),o5=Q$.extend({roots:j0(Sy)}),by=B1.extend({method:p("notifications/roots/list_changed"),params:T1.optional()}),CJ0=v0([V4,f5,Py,r5,xx,_x,Mx,zx,Qx,Px,Sx,v6,m5,q4,k4,b4,C4]),_J0=v0([K4,P4,x5,by,C6]),vJ0=v0([I4,x6,p5,hX,o5,S4,Z4,gX]),fJ0=v0([V4,Gy,Ty,ky,q4,k4,b4,C4]),xJ0=v0([K4,P4,lx,bx,Kx,tx,nx,C6,Qy]),yJ0=v0([I4,Ox,qy,cx,vx,Rx,Tx,Ix,_4,px,S4,Z4,gX]);A0=class A0 extends Error{constructor($,w,E){super(`MCP error ${$}: ${w}`);this.code=$,this.data=E,this.name="McpError"}static fromError($,w,E){if($===L0.UrlElicitationRequired&&E){let X=E;if(X.elicitations)return new kT(X.elicitations,w)}return new A0($,w,E)}};kT=class kT extends A0{constructor($,w=`URL elicitation${$.length>1?"s":""} required`){super(L0.UrlElicitationRequired,w,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});function aw($){return $==="completed"||$==="failed"||$==="cancelled"}var Zy;var v4=R(()=>{Zy=Symbol("Let zodToJsonSchema decide on which parser to use")});var t5=R(()=>{v4()});var Q1=()=>{};var i5=R(()=>{N$()});var d5=()=>{};var f4=R(()=>{N$()});var l5=R(()=>{N$()});var s5=()=>{};var a5=R(()=>{N$()});var e5=R(()=>{N$();Q1()});var $W=R(()=>{N$()});var jA0;var x4=R(()=>{jA0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});var y4=R(()=>{N$();x4();f4();Q1()});var wW=R(()=>{N$();y4();Q1()});var EW=R(()=>{Q1()});var g4=R(()=>{N$()});var XW=R(()=>{N$();g4()});var GW=()=>{};var JW=R(()=>{N$()});var AW=R(()=>{N$();Q1()});var DW=R(()=>{N$()});var NW=R(()=>{N$()});var WW=R(()=>{N$()});var OW=R(()=>{N$()});var UW=R(()=>{Q1()});var YW=R(()=>{Q1()});var HW=R(()=>{N$()});var LW=R(()=>{Q1();i5();d5();f4();l5();s5();a5();e5();$W();wW();EW();XW();GW();JW();AW();DW();NW();y4();WW();x4();OW();UW();g4();YW();HW()});var N$=R(()=>{v4();LW();Q1()});var bT=()=>{};var FW=R(()=>{N$();t5();Q1()});var ZT=R(()=>{FW();v4();t5();N$();bT();Q1();i5();d5();f4();l5();s5();a5();e5();$W();wW();EW();XW();GW();JW();AW();DW();NW();HW();y4();WW();x4();OW();UW();g4();YW();LW();FW()});function jW($){let E=j4($)?.method;if(!E)throw Error("Schema is missing a method literal");let X=hz(E);if(typeof X!=="string")throw Error("Schema method literal must be a string");return X}function MW($,w){let E=lw($,w);if(!E.success)throw E.error;return E.data}var CT=R(()=>{M4();ZT()});class RW{constructor($){if(this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(K4,(w)=>{this._oncancel(w)}),this.setNotificationHandler(P4,(w)=>{this._onprogress(w)}),this.setRequestHandler(V4,(w)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(q4,async(w,E)=>{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new A0(L0.InvalidParams,"Failed to retrieve task: Task not found");return{...X}}),this.setRequestHandler(k4,async(w,E)=>{let X=async()=>{let G=w.params.taskId;if(this._taskMessageQueue){let A;while(A=await this._taskMessageQueue.dequeue(G,E.sessionId)){if(A.type==="response"||A.type==="error"){let D=A.message,N=D.id,W=this._requestResolvers.get(N);if(W)if(this._requestResolvers.delete(N),A.type==="response")W(D);else{let O=D,Y=new A0(O.error.code,O.error.message,O.error.data);W(Y)}else{let O=A.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${N}`))}continue}await this._transport?.send(A.message,{relatedRequestId:E.requestId})}}let J=await this._taskStore.getTask(G,E.sessionId);if(!J)throw new A0(L0.InvalidParams,`Task not found: ${G}`);if(!aw(J.status))return await this._waitForTaskUpdate(G,E.signal),await X();if(aw(J.status)){let A=await this._taskStore.getTaskResult(G,E.sessionId);return this._clearTaskQueue(G),{...A,_meta:{...A._meta,[sw]:{taskId:G}}}}return await X()};return await X()}),this.setRequestHandler(b4,async(w,E)=>{try{let{tasks:X,nextCursor:G}=await this._taskStore.listTasks(w.params?.cursor,E.sessionId);return{tasks:X,nextCursor:G,_meta:{}}}catch(X){throw new A0(L0.InvalidParams,`Failed to list tasks: ${X instanceof Error?X.message:String(X)}`)}}),this.setRequestHandler(C4,async(w,E)=>{try{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new A0(L0.InvalidParams,`Task not found: ${w.params.taskId}`);if(aw(X.status))throw new A0(L0.InvalidParams,`Cannot cancel task in terminal status: ${X.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",E.sessionId),this._clearTaskQueue(w.params.taskId);let G=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!G)throw new A0(L0.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...G}}catch(X){if(X instanceof A0)throw X;throw new A0(L0.InvalidRequest,`Failed to cancel task: ${X instanceof Error?X.message:String(X)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,w,E,X,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(X,w),startTime:Date.now(),timeout:w,maxTotalTimeout:E,resetTimeoutOnProgress:G,onTimeout:X})}_resetTimeout($){let w=this._timeoutInfo.get($);if(!w)return!1;let E=Date.now()-w.startTime;if(w.maxTotalTimeout&&E>=w.maxTotalTimeout)throw this._timeoutInfo.delete($),A0.fromError(L0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:E});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout($){let w=this._timeoutInfo.get($);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let E=this.transport?.onerror;this._transport.onerror=(G)=>{E?.(G),this._onerror(G)};let X=this._transport?.onmessage;this._transport.onmessage=(G,J)=>{if(X?.(G,J),q6(G)||TT(G))this._onresponse(G);else if(C5(G))this._onrequest(G,J);else if(zT(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let E of this._requestHandlerAbortControllers.values())E.abort();this._requestHandlerAbortControllers.clear();let w=A0.fromError(L0.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let E of $.values())E(w)}_onerror($){this.onerror?.($)}_onnotification($){let w=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w($)).catch((E)=>this._onerror(Error(`Uncaught error in notification handler: ${E}`)))}_onrequest($,w){let E=this._requestHandlers.get($.method)??this.fallbackRequestHandler,X=this._transport,G=$.params?._meta?.[sw]?.taskId;if(E===void 0){let W={jsonrpc:"2.0",id:$.id,error:{code:L0.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:W,timestamp:Date.now()},X?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else X?.send(W).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J);let A=jT($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,X?.sessionId):void 0,N={signal:J.signal,sessionId:X?.sessionId,_meta:$.params?._meta,sendNotification:async(W)=>{if(J.signal.aborted)return;let O={relatedRequestId:$.id};if(G)O.relatedTask={taskId:G};await this.notification(W,O)},sendRequest:async(W,O,Y)=>{if(J.signal.aborted)throw new A0(L0.ConnectionClosed,"Request was cancelled");let H={...Y,relatedRequestId:$.id};if(G&&!H.relatedTask)H.relatedTask={taskId:G};let L=H.relatedTask?.taskId??G;if(L&&D)await D.updateTaskStatus(L,"input_required");return await this.request(W,O,H)},authInfo:w?.authInfo,requestId:$.id,requestInfo:w?.requestInfo,taskId:G,taskStore:D,taskRequestedTtl:A?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(A)this.assertTaskHandlerCapability($.method)}).then(()=>E($,N)).then(async(W)=>{if(J.signal.aborted)return;let O={result:W,jsonrpc:"2.0",id:$.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:O,timestamp:Date.now()},X?.sessionId);else await X?.send(O)},async(W)=>{if(J.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(W.code)?W.code:L0.InternalError,message:W.message??"Internal error",...W.data!==void 0&&{data:W.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:O,timestamp:Date.now()},X?.sessionId);else await X?.send(O)}).catch((W)=>this._onerror(Error(`Failed to send response: ${W}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:w,...E}=$.params,X=Number(w),G=this._progressHandlers.get(X);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let J=this._responseHandlers.get(X),A=this._timeoutInfo.get(X);if(A&&J&&A.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(D){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),J(D);return}G(E)}_onresponse($){let w=Number($.id),E=this._requestResolvers.get(w);if(E){if(this._requestResolvers.delete(w),q6($))E($);else{let J=new A0($.error.code,$.error.message,$.error.data);E(J)}return}let X=this._responseHandlers.get(w);if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let G=!1;if(q6($)&&$.result&&typeof $.result==="object"){let J=$.result;if(J.task&&typeof J.task==="object"){let A=J.task;if(typeof A.taskId==="string")G=!0,this._taskProgressTokens.set(A.taskId,w)}}if(!G)this._progressHandlers.delete(w);if(q6($))X($);else{let J=A0.fromError($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,w,E){let{task:X}=E??{};if(!X){try{yield{type:"result",result:await this.request($,w,E)}}catch(J){yield{type:"error",error:J instanceof A0?J:new A0(L0.InternalError,String(J))}}return}let G;try{let J=await this.request($,gX,E);if(J.task)G=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new A0(L0.InternalError,"Task creation did not return a task");while(!0){let A=await this.getTask({taskId:G},E);if(yield{type:"taskStatus",task:A},aw(A.status)){if(A.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};else if(A.status==="failed")yield{type:"error",error:new A0(L0.InternalError,`Task ${G} failed`)};else if(A.status==="cancelled")yield{type:"error",error:new A0(L0.InternalError,`Task ${G} was cancelled`)};return}if(A.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};return}let D=A.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((N)=>setTimeout(N,D)),E?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof A0?J:new A0(L0.InternalError,String(J))}}}request($,w,E){let{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J,task:A,relatedTask:D}=E??{};return new Promise((N,W)=>{let O=(z)=>{W(z)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),A)this.assertTaskCapability($.method)}catch(z){O(z);return}E?.signal?.throwIfAborted();let Y=this._requestMessageId++,H={...$,jsonrpc:"2.0",id:Y};if(E?.onprogress)this._progressHandlers.set(Y,E.onprogress),H.params={...$.params,_meta:{...$.params?._meta||{},progressToken:Y}};if(A)H.params={...H.params,task:A};if(D)H.params={...H.params,_meta:{...H.params?._meta||{},[sw]:D}};let L=(z)=>{this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:Y,reason:String(z)}},{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((Q)=>this._onerror(Error(`Failed to send cancellation: ${Q}`)));let B=z instanceof A0?z:new A0(L0.RequestTimeout,String(z));W(B)};this._responseHandlers.set(Y,(z)=>{if(E?.signal?.aborted)return;if(z instanceof Error)return W(z);try{let B=lw(w,z.result);if(!B.success)W(B.error);else N(B.data)}catch(B){W(B)}}),E?.signal?.addEventListener("abort",()=>{L(E?.signal?.reason)});let F=E?.timeout??yy,j=()=>L(A0.fromError(L0.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(Y,F,E?.maxTotalTimeout,j,E?.resetTimeoutOnProgress??!1);let M=D?.taskId;if(M){let z=(B)=>{let Q=this._responseHandlers.get(Y);if(Q)Q(B);else this._onerror(Error(`Response handler missing for side-channeled request ${Y}`))};this._requestResolvers.set(Y,z),this._enqueueTaskMessage(M,{type:"request",message:H,timestamp:Date.now()}).catch((B)=>{this._cleanupTimeout(Y),W(B)})}else this._transport.send(H,{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((z)=>{this._cleanupTimeout(Y),W(z)})})}async getTask($,w){return this.request({method:"tasks/get",params:$},S4,w)}async getTaskResult($,w,E){return this.request({method:"tasks/result",params:$},w,E)}async listTasks($,w){return this.request({method:"tasks/list",params:$},Z4,w)}async cancelTask($,w){return this.request({method:"tasks/cancel",params:$},IT,w)}async notification($,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let E=w?.relatedTask?.taskId;if(E){let A={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[sw]:w.relatedTask}}};await this._enqueueTaskMessage(E,{type:"notification",message:A,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let A={...$,jsonrpc:"2.0"};if(w?.relatedTask)A={...A,params:{...A.params,_meta:{...A.params?._meta||{},[sw]:w.relatedTask}}};this._transport?.send(A,w).catch((D)=>this._onerror(D))});return}let J={...$,jsonrpc:"2.0"};if(w?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[sw]:w.relatedTask}}};await this._transport.send(J,w)}setRequestHandler($,w){let E=jW($);this.assertRequestHandlerCapability(E),this._requestHandlers.set(E,(X,G)=>{let J=MW($,X);return Promise.resolve(w(J,G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,w){let E=jW($);this._notificationHandlers.set(E,(X)=>{let G=MW($,X);return Promise.resolve(w(G))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let w=this._taskProgressTokens.get($);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,w,E){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let X=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,w,E,X)}async _clearTaskQueue($,w){if(this._taskMessageQueue){let E=await this._taskMessageQueue.dequeueAll($,w);for(let X of E)if(X.type==="request"&&C5(X.message)){let G=X.message.id,J=this._requestResolvers.get(G);if(J)J(new A0(L0.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,w){let E=this._options?.defaultTaskPollInterval??1000;try{let X=await this._taskStore?.getTask($);if(X?.pollInterval)E=X.pollInterval}catch{}return new Promise((X,G)=>{if(w.aborted){G(new A0(L0.InvalidRequest,"Request cancelled"));return}let J=setTimeout(X,E);w.addEventListener("abort",()=>{clearTimeout(J),G(new A0(L0.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,w){let E=this._taskStore;if(!E)throw Error("No task store configured");return{createTask:async(X)=>{if(!$)throw Error("No request provided");return await E.createTask(X,$.id,{method:$.method,params:$.params},w)},getTask:async(X)=>{let G=await E.getTask(X,w);if(!G)throw new A0(L0.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(X,G,J)=>{await E.storeTaskResult(X,G,J,w);let A=await E.getTask(X,w);if(A){let D=C6.parse({method:"notifications/tasks/status",params:A});if(await this.notification(D),aw(A.status))this._cleanupTaskProgressHandler(X)}},getTaskResult:(X)=>{return E.getTaskResult(X,w)},updateTaskStatus:async(X,G,J)=>{let A=await E.getTask(X,w);if(!A)throw new A0(L0.InvalidParams,`Task "${X}" not found - it may have been cleaned up`);if(aw(A.status))throw new A0(L0.InvalidParams,`Cannot update task "${X}" from terminal status "${A.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await E.updateTaskStatus(X,G,J,w);let D=await E.getTask(X,w);if(D){let N=C6.parse({method:"notifications/tasks/status",params:D});if(await this.notification(N),aw(D.status))this._cleanupTaskProgressHandler(X)}},listTasks:(X)=>{return E.listTasks(X,w)}}}}function _T($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function vT($,w){let E={...$};for(let X in w){let G=X,J=w[G];if(J===void 0)continue;let A=E[G];if(_T(A)&&_T(J))E[G]={...A,...J};else E[G]=J}return E}var yy=60000;var fT=R(()=>{M4();cX();CT()});var u6=Z((gT)=>{Object.defineProperty(gT,"__esModule",{value:!0});gT.regexpCode=gT.getEsmExportName=gT.getProperty=gT.safeStringify=gT.stringify=gT.strConcat=gT.addCodeArg=gT.str=gT._=gT.nil=gT._Code=gT.Name=gT.IDENTIFIER=gT._CodeOrName=void 0;class u4{}gT._CodeOrName=u4;gT.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class nX extends u4{constructor($){super();if(!gT.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}gT.Name=nX;class h1 extends u4{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,E)=>`${w}${E}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,E)=>{if(E instanceof nX)w[E.str]=(w[E.str]||0)+1;return w},{})}}gT._Code=h1;gT.nil=new h1("");function xT($,...w){let E=[$[0]],X=0;while(X<w.length)TW(E,w[X]),E.push($[++X]);return new h1(E)}gT._=xT;var zW=new h1("+");function yT($,...w){let E=[g6($[0])],X=0;while(X<w.length)E.push(zW),TW(E,w[X]),E.push(zW,g6($[++X]));return gy(E),new h1(E)}gT.str=yT;function TW($,w){if(w instanceof h1)$.push(...w._items);else if(w instanceof nX)$.push(w);else $.push(cy(w))}gT.addCodeArg=TW;function gy($){let w=1;while(w<$.length-1){if($[w]===zW){let E=uy($[w-1],$[w+1]);if(E!==void 0){$.splice(w-1,3,E);continue}$[w++]="+"}w++}}function uy($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof nX||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof nX))return`"${$}${w.slice(1)}`;return}function hy($,w){return w.emptyStr()?$:$.emptyStr()?w:yT`${$}${w}`}gT.strConcat=hy;function cy($){return typeof $=="number"||typeof $=="boolean"||$===null?$:g6(Array.isArray($)?$.join(","):$)}function ny($){return new h1(g6($))}gT.stringify=ny;function g6($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}gT.safeStringify=g6;function my($){return typeof $=="string"&&gT.IDENTIFIER.test($)?new h1(`.${$}`):xT`[${$}]`}gT.getProperty=my;function ry($){if(typeof $=="string"&&gT.IDENTIFIER.test($))return new h1(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}gT.getEsmExportName=ry;function py($){return new h1($.toString())}gT.regexpCode=py});var KW=Z((nT)=>{Object.defineProperty(nT,"__esModule",{value:!0});nT.ValueScope=nT.ValueScopeName=nT.Scope=nT.varKinds=nT.UsedValueState=void 0;var e$=u6();class hT extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var c4;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(c4||(nT.UsedValueState=c4={}));nT.varKinds={const:new e$.Name("const"),let:new e$.Name("let"),var:new e$.Name("var")};class QW{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof e$.Name?$:this.name($)}name($){return new e$.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,E;if(((E=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||E===void 0?void 0:E.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}nT.Scope=QW;class IW extends e$.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:E}){this.value=$,this.scopePath=e$._`.${new e$.Name(w)}[${E}]`}}nT.ValueScopeName=IW;var Gg=e$._`\n`;class cT extends QW{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?Gg:e$.nil}}get(){return this._scope}name($){return new IW($,this._newName($))}value($,w){var E;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName($),{prefix:G}=X,J=(E=w.key)!==null&&E!==void 0?E:w.ref,A=this._values[G];if(A){let W=A.get(J);if(W)return W}else A=this._values[G]=new Map;A.set(J,X);let D=this._scope[G]||(this._scope[G]=[]),N=D.length;return D[N]=w.ref,X.setValue(w,{property:G,itemIndex:N}),X}getValue($,w){let E=this._values[$];if(!E)return;return E.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(E)=>{if(E.scopePath===void 0)throw Error(`CodeGen: name "${E}" has no value`);return e$._`${$}${E.scopePath}`})}scopeCode($=this._values,w,E){return this._reduceValues($,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},w,E)}_reduceValues($,w,E={},X){let G=e$.nil;for(let J in $){let A=$[J];if(!A)continue;let D=E[J]=E[J]||new Map;A.forEach((N)=>{if(D.has(N))return;D.set(N,c4.Started);let W=w(N);if(W){let O=this.opts.es5?nT.varKinds.var:nT.varKinds.const;G=e$._`${G}${O} ${N} = ${W};${this.opts._n}`}else if(W=X===null||X===void 0?void 0:X(N))G=e$._`${G}${W}${this.opts._n}`;else throw new hT(N);D.set(N,c4.Completed)})}return G}}nT.ValueScope=cT});var W0=Z(($1)=>{Object.defineProperty($1,"__esModule",{value:!0});$1.or=$1.and=$1.not=$1.CodeGen=$1.operators=$1.varKinds=$1.ValueScopeName=$1.ValueScope=$1.Scope=$1.Name=$1.regexpCode=$1.stringify=$1.getProperty=$1.nil=$1.strConcat=$1.str=$1._=void 0;var M0=u6(),c1=KW(),ew=u6();Object.defineProperty($1,"_",{enumerable:!0,get:function(){return ew._}});Object.defineProperty($1,"str",{enumerable:!0,get:function(){return ew.str}});Object.defineProperty($1,"strConcat",{enumerable:!0,get:function(){return ew.strConcat}});Object.defineProperty($1,"nil",{enumerable:!0,get:function(){return ew.nil}});Object.defineProperty($1,"getProperty",{enumerable:!0,get:function(){return ew.getProperty}});Object.defineProperty($1,"stringify",{enumerable:!0,get:function(){return ew.stringify}});Object.defineProperty($1,"regexpCode",{enumerable:!0,get:function(){return ew.regexpCode}});Object.defineProperty($1,"Name",{enumerable:!0,get:function(){return ew.Name}});var t4=KW();Object.defineProperty($1,"Scope",{enumerable:!0,get:function(){return t4.Scope}});Object.defineProperty($1,"ValueScope",{enumerable:!0,get:function(){return t4.ValueScope}});Object.defineProperty($1,"ValueScopeName",{enumerable:!0,get:function(){return t4.ValueScopeName}});Object.defineProperty($1,"varKinds",{enumerable:!0,get:function(){return t4.varKinds}});$1.operators={GT:new M0._Code(">"),GTE:new M0._Code(">="),LT:new M0._Code("<"),LTE:new M0._Code("<="),EQ:new M0._Code("==="),NEQ:new M0._Code("!=="),NOT:new M0._Code("!"),OR:new M0._Code("||"),AND:new M0._Code("&&"),ADD:new M0._Code("+")};class $E{optimizeNodes(){return this}optimizeNames($,w){return this}}class rT extends $E{constructor($,w,E){super();this.varKind=$,this.name=w,this.rhs=E}render({es5:$,_n:w}){let E=$?c1.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${X};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=rX(this.rhs,$,w);return this}get names(){return this.rhs instanceof M0._CodeOrName?this.rhs.names:{}}}class qW extends $E{constructor($,w,E){super();this.lhs=$,this.rhs=w,this.sideEffects=E}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof M0.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=rX(this.rhs,$,w),this}get names(){let $=this.lhs instanceof M0.Name?{}:{...this.lhs.names};return o4($,this.rhs)}}class pT extends qW{constructor($,w,E,X){super($,E,X);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class oT extends $E{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class tT extends $E{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class iT extends $E{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class dT extends $E{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=rX(this.code,$,w),this}get names(){return this.code instanceof M0._CodeOrName?this.code.names:{}}}class i4 extends $E{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,E)=>w+E.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let E=$[w].optimizeNodes();if(Array.isArray(E))$.splice(w,1,...E);else if(E)$[w]=E;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:E}=this,X=E.length;while(X--){let G=E[X];if(G.optimizeNames($,w))continue;Ng($,G.names),E.splice(X,1)}return E.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>kE($,w.names),{})}}class wE extends i4{render($){return"{"+$._n+super.render($)+"}"+$._n}}class lT extends i4{}class h6 extends wE{}h6.kind="else";class Pw extends wE{constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let E=w.optimizeNodes();w=this.else=Array.isArray(E)?new h6(E):E}if(w){if($===!1)return w instanceof Pw?w:w.nodes;if(this.nodes.length)return this;return new Pw(wB($),w instanceof Pw?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=rX(this.condition,$,w),this}get names(){let $=super.names;if(o4($,this.condition),this.else)kE($,this.else.names);return $}}Pw.kind="if";class mX extends wE{}mX.kind="for";class sT extends mX{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=rX(this.iteration,$,w),this}get names(){return kE(super.names,this.iteration.names)}}class aT extends mX{constructor($,w,E,X){super();this.varKind=$,this.name=w,this.from=E,this.to=X}render($){let w=$.es5?c1.varKinds.var:this.varKind,{name:E,from:X,to:G}=this;return`for(${w} ${E}=${X}; ${E}<${G}; ${E}++)`+super.render($)}get names(){let $=o4(super.names,this.from);return o4($,this.to)}}class VW extends mX{constructor($,w,E,X){super();this.loop=$,this.varKind=w,this.name=E,this.iterable=X}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=rX(this.iterable,$,w),this}get names(){return kE(super.names,this.iterable.names)}}class n4 extends wE{constructor($,w,E){super();this.name=$,this.args=w,this.async=E}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}n4.kind="func";class m4 extends i4{render($){return"return "+super.render($)}}m4.kind="return";class eT extends wE{render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var E,X;return super.optimizeNames($,w),(E=this.catch)===null||E===void 0||E.optimizeNames($,w),(X=this.finally)===null||X===void 0||X.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)kE($,this.catch.names);if(this.finally)kE($,this.finally.names);return $}}class r4 extends wE{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}r4.kind="catch";class p4 extends wE{render($){return"finally"+super.render($)}}p4.kind="finally";class $B{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
571
- `:""},this._extScope=$,this._scope=new c1.Scope({parent:$}),this._nodes=[new lT]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let E=this._extScope.value($,w);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,E,X){let G=this._scope.toName(w);if(E!==void 0&&X)this._constants[G.str]=E;return this._leafNode(new rT($,G,E)),G}const($,w,E){return this._def(c1.varKinds.const,$,w,E)}let($,w,E){return this._def(c1.varKinds.let,$,w,E)}var($,w,E){return this._def(c1.varKinds.var,$,w,E)}assign($,w,E){return this._leafNode(new qW($,w,E))}add($,w){return this._leafNode(new pT($,$1.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==M0.nil)this._leafNode(new dT($));return this}object(...$){let w=["{"];for(let[E,X]of $){if(w.length>1)w.push(",");if(w.push(E),E!==X||this.opts.es5)w.push(":"),(0,M0.addCodeArg)(w,X)}return w.push("}"),new M0._Code(w)}if($,w,E){if(this._blockNode(new Pw($)),w&&E)this.code(w).else().code(E).endIf();else if(w)this.code(w).endIf();else if(E)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new Pw($))}else(){return this._elseNode(new h6)}endIf(){return this._endBlockNode(Pw,h6)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new sT($),w)}forRange($,w,E,X,G=this.opts.es5?c1.varKinds.var:c1.varKinds.let){let J=this._scope.toName($);return this._for(new aT(G,J,w,E),()=>X(J))}forOf($,w,E,X=c1.varKinds.const){let G=this._scope.toName($);if(this.opts.es5){let J=w instanceof M0.Name?w:this.var("_arr",w);return this.forRange("_i",0,M0._`${J}.length`,(A)=>{this.var(G,M0._`${J}[${A}]`),E(G)})}return this._for(new VW("of",X,G,w),()=>E(G))}forIn($,w,E,X=this.opts.es5?c1.varKinds.var:c1.varKinds.const){if(this.opts.ownProperties)return this.forOf($,M0._`Object.keys(${w})`,E);let G=this._scope.toName($);return this._for(new VW("in",X,G,w),()=>E(G))}endFor(){return this._endBlockNode(mX)}label($){return this._leafNode(new oT($))}break($){return this._leafNode(new tT($))}return($){let w=new m4;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(m4)}try($,w,E){if(!w&&!E)throw Error('CodeGen: "try" without "catch" and "finally"');let X=new eT;if(this._blockNode(X),this.code($),w){let G=this.name("e");this._currNode=X.catch=new r4(G),w(G)}if(E)this._currNode=X.finally=new p4,this.code(E);return this._endBlockNode(r4,p4)}throw($){return this._leafNode(new iT($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let E=this._nodes.length-w;if(E<0||$!==void 0&&E!==$)throw Error(`CodeGen: wrong number of nodes: ${E} vs ${$} expected`);return this._nodes.length=w,this}func($,w=M0.nil,E,X){if(this._blockNode(new n4($,w,E)),X)this.code(X).endFunc();return this}endFunc(){return this._endBlockNode(n4)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let E=this._currNode;if(E instanceof $||w&&E instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof Pw))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}$1.CodeGen=$B;function kE($,w){for(let E in w)$[E]=($[E]||0)+(w[E]||0);return $}function o4($,w){return w instanceof M0._CodeOrName?kE($,w.names):$}function rX($,w,E){if($ instanceof M0.Name)return X($);if(!G($))return $;return new M0._Code($._items.reduce((J,A)=>{if(A instanceof M0.Name)A=X(A);if(A instanceof M0._Code)J.push(...A._items);else J.push(A);return J},[]));function X(J){let A=E[J.str];if(A===void 0||w[J.str]!==1)return J;return delete w[J.str],A}function G(J){return J instanceof M0._Code&&J._items.some((A)=>A instanceof M0.Name&&w[A.str]===1&&E[A.str]!==void 0)}}function Ng($,w){for(let E in w)$[E]=($[E]||0)-(w[E]||0)}function wB($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:M0._`!${PW($)}`}$1.not=wB;var Wg=EB($1.operators.AND);function Og(...$){return $.reduce(Wg)}$1.and=Og;var Ug=EB($1.operators.OR);function Yg(...$){return $.reduce(Ug)}$1.or=Yg;function EB($){return(w,E)=>w===M0.nil?E:E===M0.nil?w:M0._`${PW(w)} ${$} ${PW(E)}`}function PW($){return $ instanceof M0.Name?$:M0._`(${$})`}});var R0=Z((UB)=>{Object.defineProperty(UB,"__esModule",{value:!0});UB.checkStrictMode=UB.getErrorPath=UB.Type=UB.useFunc=UB.setEvaluated=UB.evaluatedPropsToName=UB.mergeEvaluated=UB.eachItem=UB.unescapeJsonPointer=UB.escapeJsonPointer=UB.escapeFragment=UB.unescapeFragment=UB.schemaRefOrVal=UB.schemaHasRulesButRef=UB.schemaHasRules=UB.checkUnknownRules=UB.alwaysValidSchema=UB.toHash=void 0;var b0=W0(),jg=u6();function Mg($){let w={};for(let E of $)w[E]=!0;return w}UB.toHash=Mg;function Rg($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return AB($,w),!DB(w,$.self.RULES.all)}UB.alwaysValidSchema=Rg;function AB($,w=$.schema){let{opts:E,self:X}=$;if(!E.strictSchema)return;if(typeof w==="boolean")return;let G=X.RULES.keywords;for(let J in w)if(!G[J])OB($,`unknown keyword: "${J}"`)}UB.checkUnknownRules=AB;function DB($,w){if(typeof $=="boolean")return!$;for(let E in $)if(w[E])return!0;return!1}UB.schemaHasRules=DB;function zg($,w){if(typeof $=="boolean")return!$;for(let E in $)if(E!=="$ref"&&w.all[E])return!0;return!1}UB.schemaHasRulesButRef=zg;function Tg({topSchemaRef:$,schemaPath:w},E,X,G){if(!G){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return b0._`${E}`}return b0._`${$}${w}${(0,b0.getProperty)(X)}`}UB.schemaRefOrVal=Tg;function Bg($){return NB(decodeURIComponent($))}UB.unescapeFragment=Bg;function Qg($){return encodeURIComponent(kW($))}UB.escapeFragment=Qg;function kW($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}UB.escapeJsonPointer=kW;function NB($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}UB.unescapeJsonPointer=NB;function Ig($,w){if(Array.isArray($))for(let E of $)w(E);else w($)}UB.eachItem=Ig;function GB({mergeNames:$,mergeToName:w,mergeValues:E,resultToName:X}){return(G,J,A,D)=>{let N=A===void 0?J:A instanceof b0.Name?(J instanceof b0.Name?$(G,J,A):w(G,J,A),A):J instanceof b0.Name?(w(G,A,J),J):E(J,A);return D===b0.Name&&!(N instanceof b0.Name)?X(G,N):N}}UB.mergeEvaluated={props:GB({mergeNames:($,w,E)=>$.if(b0._`${E} !== true && ${w} !== undefined`,()=>{$.if(b0._`${w} === true`,()=>$.assign(E,!0),()=>$.assign(E,b0._`${E} || {}`).code(b0._`Object.assign(${E}, ${w})`))}),mergeToName:($,w,E)=>$.if(b0._`${E} !== true`,()=>{if(w===!0)$.assign(E,!0);else $.assign(E,b0._`${E} || {}`),bW($,E,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:WB}),items:GB({mergeNames:($,w,E)=>$.if(b0._`${E} !== true && ${w} !== undefined`,()=>$.assign(E,b0._`${w} === true ? true : ${E} > ${w} ? ${E} : ${w}`)),mergeToName:($,w,E)=>$.if(b0._`${E} !== true`,()=>$.assign(E,w===!0?!0:b0._`${E} > ${w} ? ${E} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function WB($,w){if(w===!0)return $.var("props",!0);let E=$.var("props",b0._`{}`);if(w!==void 0)bW($,E,w);return E}UB.evaluatedPropsToName=WB;function bW($,w,E){Object.keys(E).forEach((X)=>$.assign(b0._`${w}${(0,b0.getProperty)(X)}`,!0))}UB.setEvaluated=bW;var JB={};function Kg($,w){return $.scopeValue("func",{ref:w,code:JB[w.code]||(JB[w.code]=new jg._Code(w.code))})}UB.useFunc=Kg;var SW;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(SW||(UB.Type=SW={}));function Vg($,w,E){if($ instanceof b0.Name){let X=w===SW.Num;return E?X?b0._`"[" + ${$} + "]"`:b0._`"['" + ${$} + "']"`:X?b0._`"/" + ${$}`:b0._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,b0.getProperty)($).toString():"/"+kW($)}UB.getErrorPath=Vg;function OB($,w,E=$.opts.strictSchema){if(!E)return;if(w=`strict mode: ${w}`,E===!0)throw Error(w);$.self.logger.warn(w)}UB.checkStrictMode=OB});var qw=Z((HB)=>{Object.defineProperty(HB,"__esModule",{value:!0});var Z$=W0(),mg={data:new Z$.Name("data"),valCxt:new Z$.Name("valCxt"),instancePath:new Z$.Name("instancePath"),parentData:new Z$.Name("parentData"),parentDataProperty:new Z$.Name("parentDataProperty"),rootData:new Z$.Name("rootData"),dynamicAnchors:new Z$.Name("dynamicAnchors"),vErrors:new Z$.Name("vErrors"),errors:new Z$.Name("errors"),this:new Z$.Name("this"),self:new Z$.Name("self"),scope:new Z$.Name("scope"),json:new Z$.Name("json"),jsonPos:new Z$.Name("jsonPos"),jsonLen:new Z$.Name("jsonLen"),jsonPart:new Z$.Name("jsonPart")};HB.default=mg});var c6=Z((MB)=>{Object.defineProperty(MB,"__esModule",{value:!0});MB.extendErrors=MB.resetErrorsCount=MB.reportExtraError=MB.reportError=MB.keyword$DataError=MB.keywordError=void 0;var z0=W0(),l4=R0(),c$=qw();MB.keywordError={message:({keyword:$})=>z0.str`must pass "${$}" keyword validation`};MB.keyword$DataError={message:({keyword:$,schemaType:w})=>w?z0.str`"${$}" keyword must be ${w} ($data)`:z0.str`"${$}" keyword is invalid ($data)`};function pg($,w=MB.keywordError,E,X){let{it:G}=$,{gen:J,compositeRule:A,allErrors:D}=G,N=jB($,w,E);if(X!==null&&X!==void 0?X:A||D)LB(J,N);else FB(G,z0._`[${N}]`)}MB.reportError=pg;function og($,w=MB.keywordError,E){let{it:X}=$,{gen:G,compositeRule:J,allErrors:A}=X,D=jB($,w,E);if(LB(G,D),!(J||A))FB(X,c$.default.vErrors)}MB.reportExtraError=og;function tg($,w){$.assign(c$.default.errors,w),$.if(z0._`${c$.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(z0._`${c$.default.vErrors}.length`,w),()=>$.assign(c$.default.vErrors,null)))}MB.resetErrorsCount=tg;function ig({gen:$,keyword:w,schemaValue:E,data:X,errsCount:G,it:J}){if(G===void 0)throw Error("ajv implementation error");let A=$.name("err");$.forRange("i",G,c$.default.errors,(D)=>{if($.const(A,z0._`${c$.default.vErrors}[${D}]`),$.if(z0._`${A}.instancePath === undefined`,()=>$.assign(z0._`${A}.instancePath`,(0,z0.strConcat)(c$.default.instancePath,J.errorPath))),$.assign(z0._`${A}.schemaPath`,z0.str`${J.errSchemaPath}/${w}`),J.opts.verbose)$.assign(z0._`${A}.schema`,E),$.assign(z0._`${A}.data`,X)})}MB.extendErrors=ig;function LB($,w){let E=$.const("err",w);$.if(z0._`${c$.default.vErrors} === null`,()=>$.assign(c$.default.vErrors,z0._`[${E}]`),z0._`${c$.default.vErrors}.push(${E})`),$.code(z0._`${c$.default.errors}++`)}function FB($,w){let{gen:E,validateName:X,schemaEnv:G}=$;if(G.$async)E.throw(z0._`new ${$.ValidationError}(${w})`);else E.assign(z0._`${X}.errors`,w),E.return(!1)}var bE={keyword:new z0.Name("keyword"),schemaPath:new z0.Name("schemaPath"),params:new z0.Name("params"),propertyName:new z0.Name("propertyName"),message:new z0.Name("message"),schema:new z0.Name("schema"),parentSchema:new z0.Name("parentSchema")};function jB($,w,E){let{createErrors:X}=$.it;if(X===!1)return z0._`{}`;return dg($,w,E)}function dg($,w,E={}){let{gen:X,it:G}=$,J=[lg(G,E),sg($,E)];return ag($,w,J),X.object(...J)}function lg({errorPath:$},{instancePath:w}){let E=w?z0.str`${$}${(0,l4.getErrorPath)(w,l4.Type.Str)}`:$;return[c$.default.instancePath,(0,z0.strConcat)(c$.default.instancePath,E)]}function sg({keyword:$,it:{errSchemaPath:w}},{schemaPath:E,parentSchema:X}){let G=X?w:z0.str`${w}/${$}`;if(E)G=z0.str`${G}${(0,l4.getErrorPath)(E,l4.Type.Str)}`;return[bE.schemaPath,G]}function ag($,{params:w,message:E},X){let{keyword:G,data:J,schemaValue:A,it:D}=$,{opts:N,propertyName:W,topSchemaRef:O,schemaPath:Y}=D;if(X.push([bE.keyword,G],[bE.params,typeof w=="function"?w($):w||z0._`{}`]),N.messages)X.push([bE.message,typeof E=="function"?E($):E]);if(N.verbose)X.push([bE.schema,A],[bE.parentSchema,z0._`${O}${Y}`],[c$.default.data,J]);if(W)X.push([bE.propertyName,W])}});var QB=Z((TB)=>{Object.defineProperty(TB,"__esModule",{value:!0});TB.boolOrEmptySchema=TB.topBoolOrEmptySchema=void 0;var Xu=c6(),Gu=W0(),Ju=qw(),Au={message:"boolean schema is false"};function Du($){let{gen:w,schema:E,validateName:X}=$;if(E===!1)zB($,!1);else if(typeof E=="object"&&E.$async===!0)w.return(Ju.default.data);else w.assign(Gu._`${X}.errors`,null),w.return(!0)}TB.topBoolOrEmptySchema=Du;function Nu($,w){let{gen:E,schema:X}=$;if(X===!1)E.var(w,!1),zB($);else E.var(w,!0)}TB.boolOrEmptySchema=Nu;function zB($,w){let{gen:E,data:X}=$,G={gen:E,keyword:"false schema",data:X,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,Xu.reportError)(G,Au,void 0,w)}});var CW=Z((IB)=>{Object.defineProperty(IB,"__esModule",{value:!0});IB.getRules=IB.isJSONType=void 0;var Ou=["string","number","integer","boolean","null","object","array"],Uu=new Set(Ou);function Yu($){return typeof $=="string"&&Uu.has($)}IB.isJSONType=Yu;function Hu(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}IB.getRules=Hu});var _W=Z((qB)=>{Object.defineProperty(qB,"__esModule",{value:!0});qB.shouldUseRule=qB.shouldUseGroup=qB.schemaHasRulesForType=void 0;function Fu({schema:$,self:w},E){let X=w.RULES.types[E];return X&&X!==!0&&VB($,X)}qB.schemaHasRulesForType=Fu;function VB($,w){return w.rules.some((E)=>PB($,E))}qB.shouldUseGroup=VB;function PB($,w){var E;return $[w.keyword]!==void 0||((E=w.definition.implements)===null||E===void 0?void 0:E.some((X)=>$[X]!==void 0))}qB.shouldUseRule=PB});var n6=Z((CB)=>{Object.defineProperty(CB,"__esModule",{value:!0});CB.reportTypeError=CB.checkDataTypes=CB.checkDataType=CB.coerceAndCheckDataType=CB.getJSONTypes=CB.getSchemaTypes=CB.DataType=void 0;var Ru=CW(),zu=_W(),Tu=c6(),D0=W0(),kB=R0(),pX;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(pX||(CB.DataType=pX={}));function Bu($){let w=bB($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}CB.getSchemaTypes=Bu;function bB($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(Ru.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}CB.getJSONTypes=bB;function Qu($,w){let{gen:E,data:X,opts:G}=$,J=Iu(w,G.coerceTypes),A=w.length>0&&!(J.length===0&&w.length===1&&(0,zu.schemaHasRulesForType)($,w[0]));if(A){let D=fW(w,X,G.strictNumbers,pX.Wrong);E.if(D,()=>{if(J.length)Ku($,w,J);else xW($)})}return A}CB.coerceAndCheckDataType=Qu;var ZB=new Set(["string","number","integer","boolean","null"]);function Iu($,w){return w?$.filter((E)=>ZB.has(E)||w==="array"&&E==="array"):[]}function Ku($,w,E){let{gen:X,data:G,opts:J}=$,A=X.let("dataType",D0._`typeof ${G}`),D=X.let("coerced",D0._`undefined`);if(J.coerceTypes==="array")X.if(D0._`${A} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>X.assign(G,D0._`${G}[0]`).assign(A,D0._`typeof ${G}`).if(fW(w,G,J.strictNumbers),()=>X.assign(D,G)));X.if(D0._`${D} !== undefined`);for(let W of E)if(ZB.has(W)||W==="array"&&J.coerceTypes==="array")N(W);X.else(),xW($),X.endIf(),X.if(D0._`${D} !== undefined`,()=>{X.assign(G,D),Vu($,D)});function N(W){switch(W){case"string":X.elseIf(D0._`${A} == "number" || ${A} == "boolean"`).assign(D,D0._`"" + ${G}`).elseIf(D0._`${G} === null`).assign(D,D0._`""`);return;case"number":X.elseIf(D0._`${A} == "boolean" || ${G} === null
572
- || (${A} == "string" && ${G} && ${G} == +${G})`).assign(D,D0._`+${G}`);return;case"integer":X.elseIf(D0._`${A} === "boolean" || ${G} === null
573
- || (${A} === "string" && ${G} && ${G} == +${G} && !(${G} % 1))`).assign(D,D0._`+${G}`);return;case"boolean":X.elseIf(D0._`${G} === "false" || ${G} === 0 || ${G} === null`).assign(D,!1).elseIf(D0._`${G} === "true" || ${G} === 1`).assign(D,!0);return;case"null":X.elseIf(D0._`${G} === "" || ${G} === 0 || ${G} === false`),X.assign(D,null);return;case"array":X.elseIf(D0._`${A} === "string" || ${A} === "number"
574
- || ${A} === "boolean" || ${G} === null`).assign(D,D0._`[${G}]`)}}}function Vu({gen:$,parentData:w,parentDataProperty:E},X){$.if(D0._`${w} !== undefined`,()=>$.assign(D0._`${w}[${E}]`,X))}function vW($,w,E,X=pX.Correct){let G=X===pX.Correct?D0.operators.EQ:D0.operators.NEQ,J;switch($){case"null":return D0._`${w} ${G} null`;case"array":J=D0._`Array.isArray(${w})`;break;case"object":J=D0._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":J=A(D0._`!(${w} % 1) && !isNaN(${w})`);break;case"number":J=A();break;default:return D0._`typeof ${w} ${G} ${$}`}return X===pX.Correct?J:(0,D0.not)(J);function A(D=D0.nil){return(0,D0.and)(D0._`typeof ${w} == "number"`,D,E?D0._`isFinite(${w})`:D0.nil)}}CB.checkDataType=vW;function fW($,w,E,X){if($.length===1)return vW($[0],w,E,X);let G,J=(0,kB.toHash)($);if(J.array&&J.object){let A=D0._`typeof ${w} != "object"`;G=J.null?A:D0._`!${w} || ${A}`,delete J.null,delete J.array,delete J.object}else G=D0.nil;if(J.number)delete J.integer;for(let A in J)G=(0,D0.and)(G,vW(A,w,E,X));return G}CB.checkDataTypes=fW;var Pu={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?D0._`{type: ${$}}`:D0._`{type: ${w}}`};function xW($){let w=qu($);(0,Tu.reportError)(w,Pu)}CB.reportTypeError=xW;function qu($){let{gen:w,data:E,schema:X}=$,G=(0,kB.schemaRefOrVal)($,X,"type");return{gen:w,keyword:"type",data:E,schema:X.type,schemaCode:G,schemaValue:G,parentSchema:X,params:{},it:$}}});var yB=Z((fB)=>{Object.defineProperty(fB,"__esModule",{value:!0});fB.assignDefaults=void 0;var oX=W0(),vu=R0();function fu($,w){let{properties:E,items:X}=$.schema;if(w==="object"&&E)for(let G in E)vB($,G,E[G].default);else if(w==="array"&&Array.isArray(X))X.forEach((G,J)=>vB($,J,G.default))}fB.assignDefaults=fu;function vB($,w,E){let{gen:X,compositeRule:G,data:J,opts:A}=$;if(E===void 0)return;let D=oX._`${J}${(0,oX.getProperty)(w)}`;if(G){(0,vu.checkStrictMode)($,`default is ignored for: ${D}`);return}let N=oX._`${D} === undefined`;if(A.useDefaults==="empty")N=oX._`${N} || ${D} === null || ${D} === ""`;X.if(N,oX._`${D} = ${(0,oX.stringify)(E)}`)}});var I1=Z((hB)=>{Object.defineProperty(hB,"__esModule",{value:!0});hB.validateUnion=hB.validateArray=hB.usePattern=hB.callValidateCode=hB.schemaProperties=hB.allSchemaProperties=hB.noPropertyInData=hB.propertyInData=hB.isOwnProperty=hB.hasPropFunc=hB.reportMissingProp=hB.checkMissingProp=hB.checkReportMissingProp=void 0;var h0=W0(),yW=R0(),EE=qw(),xu=R0();function yu($,w){let{gen:E,data:X,it:G}=$;E.if(uW(E,X,w,G.opts.ownProperties),()=>{$.setParams({missingProperty:h0._`${w}`},!0),$.error()})}hB.checkReportMissingProp=yu;function gu({gen:$,data:w,it:{opts:E}},X,G){return(0,h0.or)(...X.map((J)=>(0,h0.and)(uW($,w,J,E.ownProperties),h0._`${G} = ${J}`)))}hB.checkMissingProp=gu;function uu($,w){$.setParams({missingProperty:w},!0),$.error()}hB.reportMissingProp=uu;function gB($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:h0._`Object.prototype.hasOwnProperty`})}hB.hasPropFunc=gB;function gW($,w,E){return h0._`${gB($)}.call(${w}, ${E})`}hB.isOwnProperty=gW;function hu($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} !== undefined`;return X?h0._`${G} && ${gW($,w,E)}`:G}hB.propertyInData=hu;function uW($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} === undefined`;return X?(0,h0.or)(G,(0,h0.not)(gW($,w,E))):G}hB.noPropertyInData=uW;function uB($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}hB.allSchemaProperties=uB;function cu($,w){return uB(w).filter((E)=>!(0,yW.alwaysValidSchema)($,w[E]))}hB.schemaProperties=cu;function nu({schemaCode:$,data:w,it:{gen:E,topSchemaRef:X,schemaPath:G,errorPath:J},it:A},D,N,W){let O=W?h0._`${$}, ${w}, ${X}${G}`:w,Y=[[EE.default.instancePath,(0,h0.strConcat)(EE.default.instancePath,J)],[EE.default.parentData,A.parentData],[EE.default.parentDataProperty,A.parentDataProperty],[EE.default.rootData,EE.default.rootData]];if(A.opts.dynamicRef)Y.push([EE.default.dynamicAnchors,EE.default.dynamicAnchors]);let H=h0._`${O}, ${E.object(...Y)}`;return N!==h0.nil?h0._`${D}.call(${N}, ${H})`:h0._`${D}(${H})`}hB.callValidateCode=nu;var mu=h0._`new RegExp`;function ru({gen:$,it:{opts:w}},E){let X=w.unicodeRegExp?"u":"",{regExp:G}=w.code,J=G(E,X);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:h0._`${G.code==="new RegExp"?mu:(0,xu.useFunc)($,G)}(${E}, ${X})`})}hB.usePattern=ru;function pu($){let{gen:w,data:E,keyword:X,it:G}=$,J=w.name("valid");if(G.allErrors){let D=w.let("valid",!0);return A(()=>w.assign(D,!1)),D}return w.var(J,!0),A(()=>w.break()),J;function A(D){let N=w.const("len",h0._`${E}.length`);w.forRange("i",0,N,(W)=>{$.subschema({keyword:X,dataProp:W,dataPropType:yW.Type.Num},J),w.if((0,h0.not)(J),D)})}}hB.validateArray=pu;function ou($){let{gen:w,schema:E,keyword:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(E.some((N)=>(0,yW.alwaysValidSchema)(G,N))&&!G.opts.unevaluated)return;let A=w.let("valid",!1),D=w.name("_valid");w.block(()=>E.forEach((N,W)=>{let O=$.subschema({keyword:X,schemaProp:W,compositeRule:!0},D);if(w.assign(A,h0._`${A} || ${D}`),!$.mergeValidEvaluated(O,D))w.if((0,h0.not)(A))})),$.result(A,()=>$.reset(),()=>$.error(!0))}hB.validateUnion=ou});var oB=Z((rB)=>{Object.defineProperty(rB,"__esModule",{value:!0});rB.validateKeywordUsage=rB.validSchemaType=rB.funcKeywordCode=rB.macroKeywordCode=void 0;var n$=W0(),ZE=qw(),Jh=I1(),Ah=c6();function Dh($,w){let{gen:E,keyword:X,schema:G,parentSchema:J,it:A}=$,D=w.macro.call(A.self,G,J,A),N=mB(E,X,D);if(A.opts.validateSchema!==!1)A.self.validateSchema(D,!0);let W=E.name("valid");$.subschema({schema:D,schemaPath:n$.nil,errSchemaPath:`${A.errSchemaPath}/${X}`,topSchemaRef:N,compositeRule:!0},W),$.pass(W,()=>$.error(!0))}rB.macroKeywordCode=Dh;function Nh($,w){var E;let{gen:X,keyword:G,schema:J,parentSchema:A,$data:D,it:N}=$;Oh(N,w);let W=!D&&w.compile?w.compile.call(N.self,J,A,N):w.validate,O=mB(X,G,W),Y=X.let("valid");$.block$data(Y,H),$.ok((E=w.valid)!==null&&E!==void 0?E:Y);function H(){if(w.errors===!1){if(j(),w.modifying)nB($);M(()=>$.error())}else{let z=w.async?L():F();if(w.modifying)nB($);M(()=>Wh($,z))}}function L(){let z=X.let("ruleErrs",null);return X.try(()=>j(n$._`await `),(B)=>X.assign(Y,!1).if(n$._`${B} instanceof ${N.ValidationError}`,()=>X.assign(z,n$._`${B}.errors`),()=>X.throw(B))),z}function F(){let z=n$._`${O}.errors`;return X.assign(z,null),j(n$.nil),z}function j(z=w.async?n$._`await `:n$.nil){let B=N.opts.passContext?ZE.default.this:ZE.default.self,Q=!(("compile"in w)&&!D||w.schema===!1);X.assign(Y,n$._`${z}${(0,Jh.callValidateCode)($,O,B,Q)}`,w.modifying)}function M(z){var B;X.if((0,n$.not)((B=w.valid)!==null&&B!==void 0?B:Y),z)}}rB.funcKeywordCode=Nh;function nB($){let{gen:w,data:E,it:X}=$;w.if(X.parentData,()=>w.assign(E,n$._`${X.parentData}[${X.parentDataProperty}]`))}function Wh($,w){let{gen:E}=$;E.if(n$._`Array.isArray(${w})`,()=>{E.assign(ZE.default.vErrors,n$._`${ZE.default.vErrors} === null ? ${w} : ${ZE.default.vErrors}.concat(${w})`).assign(ZE.default.errors,n$._`${ZE.default.vErrors}.length`),(0,Ah.extendErrors)($)},()=>$.error())}function Oh({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function mB($,w,E){if(E===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof E=="function"?{ref:E}:{ref:E,code:(0,n$.stringify)(E)})}function Uh($,w,E=!1){return!w.length||w.some((X)=>X==="array"?Array.isArray($):X==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==X||E&&typeof $>"u")}rB.validSchemaType=Uh;function Yh({schema:$,opts:w,self:E,errSchemaPath:X},G,J){if(Array.isArray(G.keyword)?!G.keyword.includes(J):G.keyword!==J)throw Error("ajv implementation error");let A=G.dependencies;if(A===null||A===void 0?void 0:A.some((D)=>!Object.prototype.hasOwnProperty.call($,D)))throw Error(`parent schema must have dependencies of ${J}: ${A.join(",")}`);if(G.validateSchema){if(!G.validateSchema($[J])){let N=`keyword "${J}" value is invalid at path "${X}": `+E.errorsText(G.validateSchema.errors);if(w.validateSchema==="log")E.logger.error(N);else throw Error(N)}}}rB.validateKeywordUsage=Yh});var lB=Z((iB)=>{Object.defineProperty(iB,"__esModule",{value:!0});iB.extendSubschemaMode=iB.extendSubschemaData=iB.getSubschema=void 0;var Aw=W0(),tB=R0();function jh($,{keyword:w,schemaProp:E,schema:X,schemaPath:G,errSchemaPath:J,topSchemaRef:A}){if(w!==void 0&&X!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let D=$.schema[w];return E===void 0?{schema:D,schemaPath:Aw._`${$.schemaPath}${(0,Aw.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:D[E],schemaPath:Aw._`${$.schemaPath}${(0,Aw.getProperty)(w)}${(0,Aw.getProperty)(E)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,tB.escapeFragment)(E)}`}}if(X!==void 0){if(G===void 0||J===void 0||A===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:X,schemaPath:G,topSchemaRef:A,errSchemaPath:J}}throw Error('either "keyword" or "schema" must be passed')}iB.getSubschema=jh;function Mh($,w,{dataProp:E,dataPropType:X,data:G,dataTypes:J,propertyName:A}){if(G!==void 0&&E!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:D}=w;if(E!==void 0){let{errorPath:W,dataPathArr:O,opts:Y}=w,H=D.let("data",Aw._`${w.data}${(0,Aw.getProperty)(E)}`,!0);N(H),$.errorPath=Aw.str`${W}${(0,tB.getErrorPath)(E,X,Y.jsPropertySyntax)}`,$.parentDataProperty=Aw._`${E}`,$.dataPathArr=[...O,$.parentDataProperty]}if(G!==void 0){let W=G instanceof Aw.Name?G:D.let("data",G,!0);if(N(W),A!==void 0)$.propertyName=A}if(J)$.dataTypes=J;function N(W){$.data=W,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,W]}}iB.extendSubschemaData=Mh;function Rh($,{jtdDiscriminator:w,jtdMetadata:E,compositeRule:X,createErrors:G,allErrors:J}){if(X!==void 0)$.compositeRule=X;if(G!==void 0)$.createErrors=G;if(J!==void 0)$.allErrors=J;$.jtdDiscriminator=w,$.jtdMetadata=E}iB.extendSubschemaMode=Rh});var hW=Z((h80,sB)=>{sB.exports=function $(w,E){if(w===E)return!0;if(w&&E&&typeof w=="object"&&typeof E=="object"){if(w.constructor!==E.constructor)return!1;var X,G,J;if(Array.isArray(w)){if(X=w.length,X!=E.length)return!1;for(G=X;G--!==0;)if(!$(w[G],E[G]))return!1;return!0}if(w.constructor===RegExp)return w.source===E.source&&w.flags===E.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===E.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===E.toString();if(J=Object.keys(w),X=J.length,X!==Object.keys(E).length)return!1;for(G=X;G--!==0;)if(!Object.prototype.hasOwnProperty.call(E,J[G]))return!1;for(G=X;G--!==0;){var A=J[G];if(!$(w[A],E[A]))return!1}return!0}return w!==w&&E!==E}});var eB=Z((c80,aB)=>{var XE=aB.exports=function($,w,E){if(typeof w=="function")E=w,w={};E=w.cb||E;var X=typeof E=="function"?E:E.pre||function(){},G=E.post||function(){};s4(w,X,G,$,"",$)};XE.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};XE.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};XE.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};XE.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function s4($,w,E,X,G,J,A,D,N,W){if(X&&typeof X=="object"&&!Array.isArray(X)){w(X,G,J,A,D,N,W);for(var O in X){var Y=X[O];if(Array.isArray(Y)){if(O in XE.arrayKeywords)for(var H=0;H<Y.length;H++)s4($,w,E,Y[H],G+"/"+O+"/"+H,J,G,O,X,H)}else if(O in XE.propsKeywords){if(Y&&typeof Y=="object")for(var L in Y)s4($,w,E,Y[L],G+"/"+O+"/"+Bh(L),J,G,O,X,L)}else if(O in XE.keywords||$.allKeys&&!(O in XE.skipKeywords))s4($,w,E,Y,G+"/"+O,J,G,O,X)}E(X,G,J,A,D,N,W)}}function Bh($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var m6=Z((XQ)=>{Object.defineProperty(XQ,"__esModule",{value:!0});XQ.getSchemaRefs=XQ.resolveUrl=XQ.normalizeId=XQ._getFullPath=XQ.getFullPath=XQ.inlineRef=void 0;var Qh=R0(),Ih=hW(),Kh=eB(),Vh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Ph($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!cW($);if(!w)return!1;return $Q($)<=w}XQ.inlineRef=Ph;var qh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cW($){for(let w in $){if(qh.has(w))return!0;let E=$[w];if(Array.isArray(E)&&E.some(cW))return!0;if(typeof E=="object"&&cW(E))return!0}return!1}function $Q($){let w=0;for(let E in $){if(E==="$ref")return 1/0;if(w++,Vh.has(E))continue;if(typeof $[E]=="object")(0,Qh.eachItem)($[E],(X)=>w+=$Q(X));if(w===1/0)return 1/0}return w}function wQ($,w="",E){if(E!==!1)w=tX(w);let X=$.parse(w);return EQ($,X)}XQ.getFullPath=wQ;function EQ($,w){return $.serialize(w).split("#")[0]+"#"}XQ._getFullPath=EQ;var Sh=/#\/?$/;function tX($){return $?$.replace(Sh,""):""}XQ.normalizeId=tX;function kh($,w,E){return E=tX(E),$.resolve(w,E)}XQ.resolveUrl=kh;var bh=/^[a-z_][-a-z0-9._]*$/i;function Zh($,w){if(typeof $=="boolean")return{};let{schemaId:E,uriResolver:X}=this.opts,G=tX($[E]||w),J={"":G},A=wQ(X,G,!1),D={},N=new Set;return Kh($,{allKeys:!0},(Y,H,L,F)=>{if(F===void 0)return;let j=A+H,M=J[F];if(typeof Y[E]=="string")M=z.call(this,Y[E]);B.call(this,Y.$anchor),B.call(this,Y.$dynamicAnchor),J[H]=M;function z(Q){let k=this.opts.uriResolver.resolve;if(Q=tX(M?k(M,Q):Q),N.has(Q))throw O(Q);N.add(Q);let v=this.refs[Q];if(typeof v=="string")v=this.refs[v];if(typeof v=="object")W(Y,v.schema,Q);else if(Q!==tX(j))if(Q[0]==="#")W(Y,D[Q],Q),D[Q]=Y;else this.refs[Q]=j;return Q}function B(Q){if(typeof Q=="string"){if(!bh.test(Q))throw Error(`invalid anchor "${Q}"`);z.call(this,`#${Q}`)}}}),D;function W(Y,H,L){if(H!==void 0&&!Ih(Y,H))throw O(L)}function O(Y){return Error(`reference "${Y}" resolves to more than one schema`)}}XQ.getSchemaRefs=Zh});var o6=Z((zQ)=>{Object.defineProperty(zQ,"__esModule",{value:!0});zQ.getData=zQ.KeywordCxt=zQ.validateFunctionCode=void 0;var WQ=QB(),JQ=n6(),mW=_W(),a4=n6(),yh=yB(),p6=oB(),nW=lB(),o=W0(),w0=qw(),gh=m6(),Sw=R0(),r6=c6();function uh($){if(YQ($)){if(HQ($),UQ($)){nh($);return}}OQ($,()=>(0,WQ.topBoolOrEmptySchema)($))}zQ.validateFunctionCode=uh;function OQ({gen:$,validateName:w,schema:E,schemaEnv:X,opts:G},J){if(G.code.es5)$.func(w,o._`${w0.default.data}, ${w0.default.valCxt}`,X.$async,()=>{$.code(o._`"use strict"; ${AQ(E,G)}`),ch($,G),$.code(J)});else $.func(w,o._`${w0.default.data}, ${hh(G)}`,X.$async,()=>$.code(AQ(E,G)).code(J))}function hh($){return o._`{${w0.default.instancePath}="", ${w0.default.parentData}, ${w0.default.parentDataProperty}, ${w0.default.rootData}=${w0.default.data}${$.dynamicRef?o._`, ${w0.default.dynamicAnchors}={}`:o.nil}}={}`}function ch($,w){$.if(w0.default.valCxt,()=>{if($.var(w0.default.instancePath,o._`${w0.default.valCxt}.${w0.default.instancePath}`),$.var(w0.default.parentData,o._`${w0.default.valCxt}.${w0.default.parentData}`),$.var(w0.default.parentDataProperty,o._`${w0.default.valCxt}.${w0.default.parentDataProperty}`),$.var(w0.default.rootData,o._`${w0.default.valCxt}.${w0.default.rootData}`),w.dynamicRef)$.var(w0.default.dynamicAnchors,o._`${w0.default.valCxt}.${w0.default.dynamicAnchors}`)},()=>{if($.var(w0.default.instancePath,o._`""`),$.var(w0.default.parentData,o._`undefined`),$.var(w0.default.parentDataProperty,o._`undefined`),$.var(w0.default.rootData,w0.default.data),w.dynamicRef)$.var(w0.default.dynamicAnchors,o._`{}`)})}function nh($){let{schema:w,opts:E,gen:X}=$;OQ($,()=>{if(E.$comment&&w.$comment)FQ($);if(th($),X.let(w0.default.vErrors,null),X.let(w0.default.errors,0),E.unevaluated)mh($);LQ($),lh($)});return}function mh($){let{gen:w,validateName:E}=$;$.evaluated=w.const("evaluated",o._`${E}.evaluated`),w.if(o._`${$.evaluated}.dynamicProps`,()=>w.assign(o._`${$.evaluated}.props`,o._`undefined`)),w.if(o._`${$.evaluated}.dynamicItems`,()=>w.assign(o._`${$.evaluated}.items`,o._`undefined`))}function AQ($,w){let E=typeof $=="object"&&$[w.schemaId];return E&&(w.code.source||w.code.process)?o._`/*# sourceURL=${E} */`:o.nil}function rh($,w){if(YQ($)){if(HQ($),UQ($)){ph($,w);return}}(0,WQ.boolOrEmptySchema)($,w)}function UQ({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let E in $)if(w.RULES.all[E])return!0;return!1}function YQ($){return typeof $.schema!="boolean"}function ph($,w){let{schema:E,gen:X,opts:G}=$;if(G.$comment&&E.$comment)FQ($);ih($),dh($);let J=X.const("_errs",w0.default.errors);LQ($,J),X.var(w,o._`${J} === ${w0.default.errors}`)}function HQ($){(0,Sw.checkUnknownRules)($),oh($)}function LQ($,w){if($.opts.jtd)return DQ($,[],!1,w);let E=(0,JQ.getSchemaTypes)($.schema),X=(0,JQ.coerceAndCheckDataType)($,E);DQ($,E,!X,w)}function oh($){let{schema:w,errSchemaPath:E,opts:X,self:G}=$;if(w.$ref&&X.ignoreKeywordsWithRef&&(0,Sw.schemaHasRulesButRef)(w,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${E}"`)}function th($){let{schema:w,opts:E}=$;if(w.default!==void 0&&E.useDefaults&&E.strictSchema)(0,Sw.checkStrictMode)($,"default is ignored in the schema root")}function ih($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,gh.resolveUrl)($.opts.uriResolver,$.baseId,w)}function dh($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function FQ({gen:$,schemaEnv:w,schema:E,errSchemaPath:X,opts:G}){let J=E.$comment;if(G.$comment===!0)$.code(o._`${w0.default.self}.logger.log(${J})`);else if(typeof G.$comment=="function"){let A=o.str`${X}/$comment`,D=$.scopeValue("root",{ref:w.root});$.code(o._`${w0.default.self}.opts.$comment(${J}, ${A}, ${D}.schema)`)}}function lh($){let{gen:w,schemaEnv:E,validateName:X,ValidationError:G,opts:J}=$;if(E.$async)w.if(o._`${w0.default.errors} === 0`,()=>w.return(w0.default.data),()=>w.throw(o._`new ${G}(${w0.default.vErrors})`));else{if(w.assign(o._`${X}.errors`,w0.default.vErrors),J.unevaluated)sh($);w.return(o._`${w0.default.errors} === 0`)}}function sh({gen:$,evaluated:w,props:E,items:X}){if(E instanceof o.Name)$.assign(o._`${w}.props`,E);if(X instanceof o.Name)$.assign(o._`${w}.items`,X)}function DQ($,w,E,X){let{gen:G,schema:J,data:A,allErrors:D,opts:N,self:W}=$,{RULES:O}=W;if(J.$ref&&(N.ignoreKeywordsWithRef||!(0,Sw.schemaHasRulesButRef)(J,O))){G.block(()=>MQ($,"$ref",O.all.$ref.definition));return}if(!N.jtd)ah($,w);G.block(()=>{for(let H of O.rules)Y(H);Y(O.post)});function Y(H){if(!(0,mW.shouldUseGroup)(J,H))return;if(H.type){if(G.if((0,a4.checkDataType)(H.type,A,N.strictNumbers)),NQ($,H),w.length===1&&w[0]===H.type&&E)G.else(),(0,a4.reportTypeError)($);G.endIf()}else NQ($,H);if(!D)G.if(o._`${w0.default.errors} === ${X||0}`)}}function NQ($,w){let{gen:E,schema:X,opts:{useDefaults:G}}=$;if(G)(0,yh.assignDefaults)($,w.type);E.block(()=>{for(let J of w.rules)if((0,mW.shouldUseRule)(X,J))MQ($,J.keyword,J.definition,w.type)})}function ah($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(eh($,w),!$.opts.allowUnionTypes)$c($,w);wc($,$.dataTypes)}function eh($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((E)=>{if(!jQ($.dataTypes,E))rW($,`type "${E}" not allowed by context "${$.dataTypes.join(",")}"`)}),Xc($,w)}function $c($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))rW($,"use allowUnionTypes to allow union type keyword")}function wc($,w){let E=$.self.RULES.all;for(let X in E){let G=E[X];if(typeof G=="object"&&(0,mW.shouldUseRule)($.schema,G)){let{type:J}=G.definition;if(J.length&&!J.some((A)=>Ec(w,A)))rW($,`missing type "${J.join(",")}" for keyword "${X}"`)}}}function Ec($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function jQ($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function Xc($,w){let E=[];for(let X of $.dataTypes)if(jQ(w,X))E.push(X);else if(w.includes("integer")&&X==="number")E.push("integer");$.dataTypes=E}function rW($,w){let E=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${E}" (strictTypes)`,(0,Sw.checkStrictMode)($,w,$.opts.strictTypes)}class pW{constructor($,w,E){if((0,p6.validateKeywordUsage)($,w,E),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=E,this.data=$.data,this.schema=$.schema[E],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Sw.schemaRefOrVal)($,this.schema,E,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",RQ(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,p6.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${E} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",w0.default.errors)}result($,w,E){this.failResult((0,o.not)($),w,E)}failResult($,w,E){if(this.gen.if($),E)E();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,o.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(o._`${w} !== undefined && (${(0,o.or)(this.invalid$data(),$)})`)}error($,w,E){if(w){this.setParams(w),this._error($,E),this.setParams({});return}this._error($,E)}_error($,w){($?r6.reportExtraError:r6.reportError)(this,this.def.error,w)}$dataError(){(0,r6.reportError)(this,this.def.$dataError||r6.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,r6.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,E=o.nil){this.gen.block(()=>{this.check$data($,E),w()})}check$data($=o.nil,w=o.nil){if(!this.$data)return;let{gen:E,schemaCode:X,schemaType:G,def:J}=this;if(E.if((0,o.or)(o._`${X} === undefined`,w)),$!==o.nil)E.assign($,!0);if(G.length||J.validateSchema){if(E.elseIf(this.invalid$data()),this.$dataError(),$!==o.nil)E.assign($,!1)}E.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:E,def:X,it:G}=this;return(0,o.or)(J(),A());function J(){if(E.length){if(!(w instanceof o.Name))throw Error("ajv implementation error");let D=Array.isArray(E)?E:[E];return o._`${(0,a4.checkDataTypes)(D,w,G.opts.strictNumbers,a4.DataType.Wrong)}`}return o.nil}function A(){if(X.validateSchema){let D=$.scopeValue("validate$data",{ref:X.validateSchema});return o._`!${D}(${w})`}return o.nil}}subschema($,w){let E=(0,nW.getSubschema)(this.it,$);(0,nW.extendSubschemaData)(E,this.it,$),(0,nW.extendSubschemaMode)(E,$);let X={...this.it,...E,items:void 0,props:void 0};return rh(X,w),X}mergeEvaluated($,w){let{it:E,gen:X}=this;if(!E.opts.unevaluated)return;if(E.props!==!0&&$.props!==void 0)E.props=Sw.mergeEvaluated.props(X,$.props,E.props,w);if(E.items!==!0&&$.items!==void 0)E.items=Sw.mergeEvaluated.items(X,$.items,E.items,w)}mergeValidEvaluated($,w){let{it:E,gen:X}=this;if(E.opts.unevaluated&&(E.props!==!0||E.items!==!0))return X.if(w,()=>this.mergeEvaluated($,o.Name)),!0}}zQ.KeywordCxt=pW;function MQ($,w,E,X){let G=new pW($,E,w);if("code"in E)E.code(G,X);else if(G.$data&&E.validate)(0,p6.funcKeywordCode)(G,E);else if("macro"in E)(0,p6.macroKeywordCode)(G,E);else if(E.compile||E.validate)(0,p6.funcKeywordCode)(G,E)}var Gc=/^\/(?:[^~]|~0|~1)*$/,Jc=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function RQ($,{dataLevel:w,dataNames:E,dataPathArr:X}){let G,J;if($==="")return w0.default.rootData;if($[0]==="/"){if(!Gc.test($))throw Error(`Invalid JSON-pointer: ${$}`);G=$,J=w0.default.rootData}else{let W=Jc.exec($);if(!W)throw Error(`Invalid JSON-pointer: ${$}`);let O=+W[1];if(G=W[2],G==="#"){if(O>=w)throw Error(N("property/index",O));return X[w-O]}if(O>w)throw Error(N("data",O));if(J=E[w-O],!G)return J}let A=J,D=G.split("/");for(let W of D)if(W)J=o._`${J}${(0,o.getProperty)((0,Sw.unescapeJsonPointer)(W))}`,A=o._`${A} && ${J}`;return A;function N(W,O){return`Cannot access ${W} ${O} levels up, current level is ${w}`}}zQ.getData=RQ});var e4=Z((QQ)=>{Object.defineProperty(QQ,"__esModule",{value:!0});class BQ extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}QQ.default=BQ});var t6=Z((KQ)=>{Object.defineProperty(KQ,"__esModule",{value:!0});var oW=m6();class IQ extends Error{constructor($,w,E,X){super(X||`can't resolve reference ${E} from id ${w}`);this.missingRef=(0,oW.resolveUrl)($,w,E),this.missingSchema=(0,oW.normalizeId)((0,oW.getFullPath)($,this.missingRef))}}KQ.default=IQ});var wD=Z((qQ)=>{Object.defineProperty(qQ,"__esModule",{value:!0});qQ.resolveSchema=qQ.getCompilingSchema=qQ.resolveRef=qQ.compileSchema=qQ.SchemaEnv=void 0;var n1=W0(),Oc=e4(),CE=qw(),m1=m6(),VQ=R0(),Uc=o6();class i6{constructor($){var w;this.refs={},this.dynamicAnchors={};let E;if(typeof $.schema=="object")E=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,m1.normalizeId)(E===null||E===void 0?void 0:E[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=E===null||E===void 0?void 0:E.$async,this.refs={}}}qQ.SchemaEnv=i6;function iW($){let w=PQ.call(this,$);if(w)return w;let E=(0,m1.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:X,lines:G}=this.opts.code,{ownProperties:J}=this.opts,A=new n1.CodeGen(this.scope,{es5:X,lines:G,ownProperties:J}),D;if($.$async)D=A.scopeValue("Error",{ref:Oc.default,code:n1._`require("ajv/dist/runtime/validation_error").default`});let N=A.scopeName("validate");$.validateName=N;let W={gen:A,allErrors:this.opts.allErrors,data:CE.default.data,parentData:CE.default.parentData,parentDataProperty:CE.default.parentDataProperty,dataNames:[CE.default.data],dataPathArr:[n1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:A.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,n1.stringify)($.schema)}:{ref:$.schema}),validateName:N,ValidationError:D,schema:$.schema,schemaEnv:$,rootId:E,baseId:$.baseId||E,schemaPath:n1.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:n1._`""`,opts:this.opts,self:this},O;try{this._compilations.add($),(0,Uc.validateFunctionCode)(W),A.optimize(this.opts.code.optimize);let Y=A.toString();if(O=`${A.scopeRefs(CE.default.scope)}return ${Y}`,this.opts.code.process)O=this.opts.code.process(O,$);let L=Function(`${CE.default.self}`,`${CE.default.scope}`,O)(this,this.scope.get());if(this.scope.value(N,{ref:L}),L.errors=null,L.schema=$.schema,L.schemaEnv=$,$.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:N,validateCode:Y,scopeValues:A._values};if(this.opts.unevaluated){let{props:F,items:j}=W;if(L.evaluated={props:F instanceof n1.Name?void 0:F,items:j instanceof n1.Name?void 0:j,dynamicProps:F instanceof n1.Name,dynamicItems:j instanceof n1.Name},L.source)L.source.evaluated=(0,n1.stringify)(L.evaluated)}return $.validate=L,$}catch(Y){if(delete $.validate,delete $.validateName,O)this.logger.error("Error compiling schema, function code:",O);throw Y}finally{this._compilations.delete($)}}qQ.compileSchema=iW;function Yc($,w,E){var X;E=(0,m1.resolveUrl)(this.opts.uriResolver,w,E);let G=$.refs[E];if(G)return G;let J=Fc.call(this,$,E);if(J===void 0){let A=(X=$.localRefs)===null||X===void 0?void 0:X[E],{schemaId:D}=this.opts;if(A)J=new i6({schema:A,schemaId:D,root:$,baseId:w})}if(J===void 0)return;return $.refs[E]=Hc.call(this,J)}qQ.resolveRef=Yc;function Hc($){if((0,m1.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:iW.call(this,$)}function PQ($){for(let w of this._compilations)if(Lc(w,$))return w}qQ.getCompilingSchema=PQ;function Lc($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function Fc($,w){let E;while(typeof(E=this.refs[w])=="string")w=E;return E||this.schemas[w]||$D.call(this,$,w)}function $D($,w){let E=this.opts.uriResolver.parse(w),X=(0,m1._getFullPath)(this.opts.uriResolver,E),G=(0,m1.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&X===G)return tW.call(this,E,$);let J=(0,m1.normalizeId)(X),A=this.refs[J]||this.schemas[J];if(typeof A=="string"){let D=$D.call(this,$,A);if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;return tW.call(this,E,D)}if(typeof(A===null||A===void 0?void 0:A.schema)!=="object")return;if(!A.validate)iW.call(this,A);if(J===(0,m1.normalizeId)(w)){let{schema:D}=A,{schemaId:N}=this.opts,W=D[N];if(W)G=(0,m1.resolveUrl)(this.opts.uriResolver,G,W);return new i6({schema:D,schemaId:N,root:$,baseId:G})}return tW.call(this,E,A)}qQ.resolveSchema=$D;var jc=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tW($,{baseId:w,schema:E,root:X}){var G;if(((G=$.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let D of $.fragment.slice(1).split("/")){if(typeof E==="boolean")return;let N=E[(0,VQ.unescapeFragment)(D)];if(N===void 0)return;E=N;let W=typeof E==="object"&&E[this.opts.schemaId];if(!jc.has(D)&&W)w=(0,m1.resolveUrl)(this.opts.uriResolver,w,W)}let J;if(typeof E!="boolean"&&E.$ref&&!(0,VQ.schemaHasRulesButRef)(E,this.RULES)){let D=(0,m1.resolveUrl)(this.opts.uriResolver,w,E.$ref);J=$D.call(this,X,D)}let{schemaId:A}=this.opts;if(J=J||new i6({schema:E,schemaId:A,root:X,baseId:w}),J.schema!==J.root.schema)return J;return}});var kQ=Z((t80,Bc)=>{Bc.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var lW=Z((i80,_Q)=>{var Qc=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ZQ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function dW($){let w="",E=0,X=0;for(X=0;X<$.length;X++){if(E=$[X].charCodeAt(0),E===48)continue;if(!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X];break}for(X+=1;X<$.length;X++){if(E=$[X].charCodeAt(0),!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X]}return w}var Ic=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function bQ($){return $.length=0,!0}function Kc($,w,E){if($.length){let X=dW($);if(X!=="")w.push(X);else return E.error=!0,!1;$.length=0}return!0}function Vc($){let w=0,E={error:!1,address:"",zone:""},X=[],G=[],J=!1,A=!1,D=Kc;for(let N=0;N<$.length;N++){let W=$[N];if(W==="["||W==="]")continue;if(W===":"){if(J===!0)A=!0;if(!D(G,X,E))break;if(++w>7){E.error=!0;break}if(N>0&&$[N-1]===":")J=!0;X.push(":");continue}else if(W==="%"){if(!D(G,X,E))break;D=bQ}else{G.push(W);continue}}if(G.length)if(D===bQ)E.zone=G.join("");else if(A)X.push(G.join(""));else X.push(dW(G));return E.address=X.join(""),E}function CQ($){if(Pc($,":")<2)return{host:$,isIPV6:!1};let w=Vc($);if(!w.error){let{address:E,address:X}=w;if(w.zone)E+="%"+w.zone,X+="%25"+w.zone;return{host:E,isIPV6:!0,escapedHost:X}}else return{host:$,isIPV6:!1}}function Pc($,w){let E=0;for(let X=0;X<$.length;X++)if($[X]===w)E++;return E}function qc($){let w=$,E=[],X=-1,G=0;while(G=w.length){if(G===1)if(w===".")break;else if(w==="/"){E.push("/");break}else{E.push(w);break}else if(G===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){E.push("/");break}}}else if(G===3){if(w==="/.."){if(E.length!==0)E.pop();E.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),E.length!==0)E.pop();continue}}}}if((X=w.indexOf("/",1))===-1){E.push(w);break}else E.push(w.slice(0,X)),w=w.slice(X)}return E.join("")}function Sc($,w){let E=w!==!0?escape:unescape;if($.scheme!==void 0)$.scheme=E($.scheme);if($.userinfo!==void 0)$.userinfo=E($.userinfo);if($.host!==void 0)$.host=E($.host);if($.path!==void 0)$.path=E($.path);if($.query!==void 0)$.query=E($.query);if($.fragment!==void 0)$.fragment=E($.fragment);return $}function kc($){let w=[];if($.userinfo!==void 0)w.push($.userinfo),w.push("@");if($.host!==void 0){let E=unescape($.host);if(!ZQ(E)){let X=CQ(E);if(X.isIPV6===!0)E=`[${X.escapedHost}]`;else E=$.host}w.push(E)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}_Q.exports={nonSimpleDomain:Ic,recomposeAuthority:kc,normalizeComponentEncoding:Sc,removeDotSegments:qc,isIPv4:ZQ,isUUID:Qc,normalizeIPv6:CQ,stringArrayToHexStripped:dW}});var gQ=Z((d80,yQ)=>{var{isUUID:bc}=lW(),Zc=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Cc=["http","https","ws","wss","urn","urn:uuid"];function _c($){return Cc.indexOf($)!==-1}function sW($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function vQ($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function fQ($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function vc($){return $.secure=sW($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function fc($){if($.port===(sW($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[w,E]=$.resourceName.split("?");$.path=w&&w!=="/"?w:void 0,$.query=E,$.resourceName=void 0}return $.fragment=void 0,$}function xc($,w){if(!$.path)return $.error="URN can not be parsed",$;let E=$.path.match(Zc);if(E){let X=w.scheme||$.scheme||"urn";$.nid=E[1].toLowerCase(),$.nss=E[2];let G=`${X}:${w.nid||$.nid}`,J=aW(G);if($.path=void 0,J)$=J.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function yc($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let E=w.scheme||$.scheme||"urn",X=$.nid.toLowerCase(),G=`${E}:${w.nid||X}`,J=aW(G);if(J)$=J.serialize($,w);let A=$,D=$.nss;return A.path=`${X||w.nid}:${D}`,w.skipEscape=!0,A}function gc($,w){let E=$;if(E.uuid=E.nss,E.nss=void 0,!w.tolerant&&(!E.uuid||!bc(E.uuid)))E.error=E.error||"UUID is not valid.";return E}function uc($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var xQ={scheme:"http",domainHost:!0,parse:vQ,serialize:fQ},hc={scheme:"https",domainHost:xQ.domainHost,parse:vQ,serialize:fQ},ED={scheme:"ws",domainHost:!0,parse:vc,serialize:fc},cc={scheme:"wss",domainHost:ED.domainHost,parse:ED.parse,serialize:ED.serialize},nc={scheme:"urn",parse:xc,serialize:yc,skipNormalize:!0},mc={scheme:"urn:uuid",parse:gc,serialize:uc,skipNormalize:!0},XD={http:xQ,https:hc,ws:ED,wss:cc,urn:nc,"urn:uuid":mc};Object.setPrototypeOf(XD,null);function aW($){return $&&(XD[$]||XD[$.toLowerCase()])||void 0}yQ.exports={wsIsSecure:sW,SCHEMES:XD,isValidSchemeName:_c,getSchemeHandler:aW}});var cQ=Z((l80,JD)=>{var{normalizeIPv6:rc,removeDotSegments:d6,recomposeAuthority:pc,normalizeComponentEncoding:GD,isIPv4:oc,nonSimpleDomain:tc}=lW(),{SCHEMES:ic,getSchemeHandler:uQ}=gQ();function dc($,w){if(typeof $==="string")$=Dw(kw($,w),w);else if(typeof $==="object")$=kw(Dw($,w),w);return $}function lc($,w,E){let X=E?Object.assign({scheme:"null"},E):{scheme:"null"},G=hQ(kw($,X),kw(w,X),X,!0);return X.skipEscape=!0,Dw(G,X)}function hQ($,w,E,X){let G={};if(!X)$=kw(Dw($,E),E),w=kw(Dw(w,E),E);if(E=E||{},!E.tolerant&&w.scheme)G.scheme=w.scheme,G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=d6(w.path||""),G.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=d6(w.path||""),G.query=w.query;else{if(!w.path)if(G.path=$.path,w.query!==void 0)G.query=w.query;else G.query=$.query;else{if(w.path[0]==="/")G.path=d6(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)G.path="/"+w.path;else if(!$.path)G.path=w.path;else G.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;G.path=d6(G.path)}G.query=w.query}G.userinfo=$.userinfo,G.host=$.host,G.port=$.port}G.scheme=$.scheme}return G.fragment=w.fragment,G}function sc($,w,E){if(typeof $==="string")$=unescape($),$=Dw(GD(kw($,E),!0),{...E,skipEscape:!0});else if(typeof $==="object")$=Dw(GD($,!0),{...E,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=Dw(GD(kw(w,E),!0),{...E,skipEscape:!0});else if(typeof w==="object")w=Dw(GD(w,!0),{...E,skipEscape:!0});return $.toLowerCase()===w.toLowerCase()}function Dw($,w){let E={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},X=Object.assign({},w),G=[],J=uQ(X.scheme||E.scheme);if(J&&J.serialize)J.serialize(E,X);if(E.path!==void 0)if(!X.skipEscape){if(E.path=escape(E.path),E.scheme!==void 0)E.path=E.path.split("%3A").join(":")}else E.path=unescape(E.path);if(X.reference!=="suffix"&&E.scheme)G.push(E.scheme,":");let A=pc(E);if(A!==void 0){if(X.reference!=="suffix")G.push("//");if(G.push(A),E.path&&E.path[0]!=="/")G.push("/")}if(E.path!==void 0){let D=E.path;if(!X.absolutePath&&(!J||!J.absolutePath))D=d6(D);if(A===void 0&&D[0]==="/"&&D[1]==="/")D="/%2F"+D.slice(2);G.push(D)}if(E.query!==void 0)G.push("?",E.query);if(E.fragment!==void 0)G.push("#",E.fragment);return G.join("")}var ac=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kw($,w){let E=Object.assign({},w),X={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(E.reference==="suffix")if(E.scheme)$=E.scheme+":"+$;else $="//"+$;let J=$.match(ac);if(J){if(X.scheme=J[1],X.userinfo=J[3],X.host=J[4],X.port=parseInt(J[5],10),X.path=J[6]||"",X.query=J[7],X.fragment=J[8],isNaN(X.port))X.port=J[5];if(X.host)if(oc(X.host)===!1){let N=rc(X.host);X.host=N.host.toLowerCase(),G=N.isIPV6}else G=!0;if(X.scheme===void 0&&X.userinfo===void 0&&X.host===void 0&&X.port===void 0&&X.query===void 0&&!X.path)X.reference="same-document";else if(X.scheme===void 0)X.reference="relative";else if(X.fragment===void 0)X.reference="absolute";else X.reference="uri";if(E.reference&&E.reference!=="suffix"&&E.reference!==X.reference)X.error=X.error||"URI is not a "+E.reference+" reference.";let A=uQ(E.scheme||X.scheme);if(!E.unicodeSupport&&(!A||!A.unicodeSupport)){if(X.host&&(E.domainHost||A&&A.domainHost)&&G===!1&&tc(X.host))try{X.host=URL.domainToASCII(X.host.toLowerCase())}catch(D){X.error=X.error||"Host's domain name can not be converted to ASCII: "+D}}if(!A||A&&!A.skipNormalize){if($.indexOf("%")!==-1){if(X.scheme!==void 0)X.scheme=unescape(X.scheme);if(X.host!==void 0)X.host=unescape(X.host)}if(X.path)X.path=escape(unescape(X.path));if(X.fragment)X.fragment=encodeURI(decodeURIComponent(X.fragment))}if(A&&A.parse)A.parse(X,E)}else X.error=X.error||"URI can not be parsed.";return X}var eW={SCHEMES:ic,normalize:dc,resolve:lc,resolveComponent:hQ,equal:sc,serialize:Dw,parse:kw};JD.exports=eW;JD.exports.default=eW;JD.exports.fastUri=eW});var rQ=Z((mQ)=>{Object.defineProperty(mQ,"__esModule",{value:!0});var nQ=cQ();nQ.code='require("ajv/dist/runtime/uri").default';mQ.default=nQ});var aQ=Z((bw)=>{Object.defineProperty(bw,"__esModule",{value:!0});bw.CodeGen=bw.Name=bw.nil=bw.stringify=bw.str=bw._=bw.KeywordCxt=void 0;var $n=o6();Object.defineProperty(bw,"KeywordCxt",{enumerable:!0,get:function(){return $n.KeywordCxt}});var iX=W0();Object.defineProperty(bw,"_",{enumerable:!0,get:function(){return iX._}});Object.defineProperty(bw,"str",{enumerable:!0,get:function(){return iX.str}});Object.defineProperty(bw,"stringify",{enumerable:!0,get:function(){return iX.stringify}});Object.defineProperty(bw,"nil",{enumerable:!0,get:function(){return iX.nil}});Object.defineProperty(bw,"Name",{enumerable:!0,get:function(){return iX.Name}});Object.defineProperty(bw,"CodeGen",{enumerable:!0,get:function(){return iX.CodeGen}});var wn=e4(),dQ=t6(),En=CW(),l6=wD(),Xn=W0(),s6=m6(),AD=n6(),wO=R0(),pQ=kQ(),Gn=rQ(),lQ=($,w)=>new RegExp($,w);lQ.code="new RegExp";var Jn=["removeAdditional","useDefaults","coerceTypes"],An=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Dn={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Nn={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},oQ=200;function Wn($){var w,E,X,G,J,A,D,N,W,O,Y,H,L,F,j,M,z,B,Q,k,v,C,n,T0,f0;let c0=$.strict,d0=(w=$.code)===null||w===void 0?void 0:w.optimize,K0=d0===!0||d0===void 0?1:d0||0,U$=(X=(E=$.code)===null||E===void 0?void 0:E.regExp)!==null&&X!==void 0?X:lQ,O1=(G=$.uriResolver)!==null&&G!==void 0?G:Gn.default;return{strictSchema:(A=(J=$.strictSchema)!==null&&J!==void 0?J:c0)!==null&&A!==void 0?A:!0,strictNumbers:(N=(D=$.strictNumbers)!==null&&D!==void 0?D:c0)!==null&&N!==void 0?N:!0,strictTypes:(O=(W=$.strictTypes)!==null&&W!==void 0?W:c0)!==null&&O!==void 0?O:"log",strictTuples:(H=(Y=$.strictTuples)!==null&&Y!==void 0?Y:c0)!==null&&H!==void 0?H:"log",strictRequired:(F=(L=$.strictRequired)!==null&&L!==void 0?L:c0)!==null&&F!==void 0?F:!1,code:$.code?{...$.code,optimize:K0,regExp:U$}:{optimize:K0,regExp:U$},loopRequired:(j=$.loopRequired)!==null&&j!==void 0?j:oQ,loopEnum:(M=$.loopEnum)!==null&&M!==void 0?M:oQ,meta:(z=$.meta)!==null&&z!==void 0?z:!0,messages:(B=$.messages)!==null&&B!==void 0?B:!0,inlineRefs:(Q=$.inlineRefs)!==null&&Q!==void 0?Q:!0,schemaId:(k=$.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=$.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(C=$.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(n=$.validateFormats)!==null&&n!==void 0?n:!0,unicodeRegExp:(T0=$.unicodeRegExp)!==null&&T0!==void 0?T0:!0,int32range:(f0=$.int32range)!==null&&f0!==void 0?f0:!0,uriResolver:O1}}class DD{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...Wn($)};let{es5:w,lines:E}=this.opts.code;this.scope=new Xn.ValueScope({scope:{},prefixes:An,es5:w,lines:E}),this.logger=Fn($.logger);let X=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,En.getRules)(),tQ.call(this,Dn,$,"NOT SUPPORTED"),tQ.call(this,Nn,$,"DEPRECATED","warn"),this._metaOpts=Hn.call(this),$.formats)Un.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)Yn.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);On.call(this),$.validateFormats=X}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:E}=this.opts,X=pQ;if(E==="id")X={...pQ},X.id=X.$id,delete X.$id;if(w&&$)this.addMetaSchema(X,X[E],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let E;if(typeof $=="string"){if(E=this.getSchema($),!E)throw Error(`no schema with key or ref "${$}"`)}else E=this.compile($);let X=E(w);if(!("$async"in E))this.errors=E.errors;return X}compile($,w){let E=this._addSchema($,w);return E.validate||this._compileSchemaEnv(E)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:E}=this.opts;return X.call(this,$,w);async function X(W,O){await G.call(this,W.$schema);let Y=this._addSchema(W,O);return Y.validate||J.call(this,Y)}async function G(W){if(W&&!this.getSchema(W))await X.call(this,{$ref:W},!0)}async function J(W){try{return this._compileSchemaEnv(W)}catch(O){if(!(O instanceof dQ.default))throw O;return A.call(this,O),await D.call(this,O.missingSchema),J.call(this,W)}}function A({missingSchema:W,missingRef:O}){if(this.refs[W])throw Error(`AnySchema ${W} is loaded but ${O} cannot be resolved`)}async function D(W){let O=await N.call(this,W);if(!this.refs[W])await G.call(this,O.$schema);if(!this.refs[W])this.addSchema(O,W,w)}async function N(W){let O=this._loading[W];if(O)return O;try{return await(this._loading[W]=E(W))}finally{delete this._loading[W]}}}addSchema($,w,E,X=this.opts.validateSchema){if(Array.isArray($)){for(let J of $)this.addSchema(J,void 0,E,X);return this}let G;if(typeof $==="object"){let{schemaId:J}=this.opts;if(G=$[J],G!==void 0&&typeof G!="string")throw Error(`schema ${J} must be string`)}return w=(0,s6.normalizeId)(w||G),this._checkUnique(w),this.schemas[w]=this._addSchema($,E,w,X,!0),this}addMetaSchema($,w,E=this.opts.validateSchema){return this.addSchema($,w,!0,E),this}validateSchema($,w){if(typeof $=="boolean")return!0;let E;if(E=$.$schema,E!==void 0&&typeof E!="string")throw Error("$schema must be a string");if(E=E||this.opts.defaultMeta||this.defaultMeta(),!E)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let X=this.validate(E,$);if(!X&&w){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return X}getSchema($){let w;while(typeof(w=iQ.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:E}=this.opts,X=new l6.SchemaEnv({schema:{},schemaId:E});if(w=l6.resolveSchema.call(this,X,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=iQ.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let E=$[this.opts.schemaId];if(E)E=(0,s6.normalizeId)(E),delete this.schemas[E],delete this.refs[E];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let E;if(typeof $=="string"){if(E=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=E}else if(typeof $=="object"&&w===void 0){if(w=$,E=w.keyword,Array.isArray(E)&&!E.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Mn.call(this,E,w),!w)return(0,wO.eachItem)(E,(G)=>$O.call(this,G)),this;zn.call(this,w);let X={...w,type:(0,AD.getJSONTypes)(w.type),schemaType:(0,AD.getJSONTypes)(w.schemaType)};return(0,wO.eachItem)(E,X.type.length===0?(G)=>$O.call(this,G,X):(G)=>X.type.forEach((J)=>$O.call(this,G,X,J))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let E of w.rules){let X=E.rules.findIndex((G)=>G.keyword===$);if(X>=0)E.rules.splice(X,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:E="data"}={}){if(!$||$.length===0)return"No errors";return $.map((X)=>`${E}${X.instancePath} ${X.message}`).reduce((X,G)=>X+w+G)}$dataMetaSchema($,w){let E=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let X of w){let G=X.split("/").slice(1),J=$;for(let A of G)J=J[A];for(let A in E){let D=E[A];if(typeof D!="object")continue;let{$data:N}=D.definition,W=J[A];if(N&&W)J[A]=sQ(W)}}return $}_removeAllSchemas($,w){for(let E in $){let X=$[E];if(!w||w.test(E)){if(typeof X=="string")delete $[E];else if(X&&!X.meta)this._cache.delete(X.schema),delete $[E]}}}_addSchema($,w,E,X=this.opts.validateSchema,G=this.opts.addUsedSchema){let J,{schemaId:A}=this.opts;if(typeof $=="object")J=$[A];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let D=this._cache.get($);if(D!==void 0)return D;E=(0,s6.normalizeId)(J||E);let N=s6.getSchemaRefs.call(this,$,E);if(D=new l6.SchemaEnv({schema:$,schemaId:A,meta:w,baseId:E,localRefs:N}),this._cache.set(D.schema,D),G&&!E.startsWith("#")){if(E)this._checkUnique(E);this.refs[E]=D}if(X)this.validateSchema($,!0);return D}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else l6.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{l6.compileSchema.call(this,$)}finally{this.opts=w}}}DD.ValidationError=wn.default;DD.MissingRefError=dQ.default;bw.default=DD;function tQ($,w,E,X="error"){for(let G in $){let J=G;if(J in w)this.logger[X](`${E}: option ${G}. ${$[J]}`)}}function iQ($){return $=(0,s6.normalizeId)($),this.schemas[$]||this.refs[$]}function On(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function Un(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function Yn($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let E=$[w];if(!E.keyword)E.keyword=w;this.addKeyword(E)}}function Hn(){let $={...this.opts};for(let w of Jn)delete $[w];return $}var Ln={log(){},warn(){},error(){}};function Fn($){if($===!1)return Ln;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var jn=/^[a-z_$][a-z0-9_$:-]*$/i;function Mn($,w){let{RULES:E}=this;if((0,wO.eachItem)($,(X)=>{if(E.keywords[X])throw Error(`Keyword ${X} is already defined`);if(!jn.test(X))throw Error(`Keyword ${X} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function $O($,w,E){var X;let G=w===null||w===void 0?void 0:w.post;if(E&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:J}=this,A=G?J.post:J.rules.find(({type:N})=>N===E);if(!A)A={type:E,rules:[]},J.rules.push(A);if(J.keywords[$]=!0,!w)return;let D={keyword:$,definition:{...w,type:(0,AD.getJSONTypes)(w.type),schemaType:(0,AD.getJSONTypes)(w.schemaType)}};if(w.before)Rn.call(this,A,D,w.before);else A.rules.push(D);J.all[$]=D,(X=w.implements)===null||X===void 0||X.forEach((N)=>this.addKeyword(N))}function Rn($,w,E){let X=$.rules.findIndex((G)=>G.keyword===E);if(X>=0)$.rules.splice(X,0,w);else $.rules.push(w),this.logger.warn(`rule ${E} is not defined`)}function zn($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=sQ(w);$.validateSchema=this.compile(w,!0)}var Tn={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function sQ($){return{anyOf:[$,Tn]}}});var $I=Z((eQ)=>{Object.defineProperty(eQ,"__esModule",{value:!0});var In={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eQ.default=In});var AI=Z((GI)=>{Object.defineProperty(GI,"__esModule",{value:!0});GI.callRef=GI.getValidate=void 0;var Vn=t6(),wI=I1(),w1=W0(),dX=qw(),EI=wD(),ND=R0(),Pn={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:E,it:X}=$,{baseId:G,schemaEnv:J,validateName:A,opts:D,self:N}=X,{root:W}=J;if((E==="#"||E==="#/")&&G===W.baseId)return Y();let O=EI.resolveRef.call(N,W,G,E);if(O===void 0)throw new Vn.default(X.opts.uriResolver,G,E);if(O instanceof EI.SchemaEnv)return H(O);return L(O);function Y(){if(J===W)return WD($,A,J,J.$async);let F=w.scopeValue("root",{ref:W});return WD($,w1._`${F}.validate`,W,W.$async)}function H(F){let j=XI($,F);WD($,j,F,F.$async)}function L(F){let j=w.scopeValue("schema",D.code.source===!0?{ref:F,code:(0,w1.stringify)(F)}:{ref:F}),M=w.name("valid"),z=$.subschema({schema:F,dataTypes:[],schemaPath:w1.nil,topSchemaRef:j,errSchemaPath:E},M);$.mergeEvaluated(z),$.ok(M)}}};function XI($,w){let{gen:E}=$;return w.validate?E.scopeValue("validate",{ref:w.validate}):w1._`${E.scopeValue("wrapper",{ref:w})}.validate`}GI.getValidate=XI;function WD($,w,E,X){let{gen:G,it:J}=$,{allErrors:A,schemaEnv:D,opts:N}=J,W=N.passContext?dX.default.this:w1.nil;if(X)O();else Y();function O(){if(!D.$async)throw Error("async schema referenced by sync schema");let F=G.let("valid");G.try(()=>{if(G.code(w1._`await ${(0,wI.callValidateCode)($,w,W)}`),L(w),!A)G.assign(F,!0)},(j)=>{if(G.if(w1._`!(${j} instanceof ${J.ValidationError})`,()=>G.throw(j)),H(j),!A)G.assign(F,!1)}),$.ok(F)}function Y(){$.result((0,wI.callValidateCode)($,w,W),()=>L(w),()=>H(w))}function H(F){let j=w1._`${F}.errors`;G.assign(dX.default.vErrors,w1._`${dX.default.vErrors} === null ? ${j} : ${dX.default.vErrors}.concat(${j})`),G.assign(dX.default.errors,w1._`${dX.default.vErrors}.length`)}function L(F){var j;if(!J.opts.unevaluated)return;let M=(j=E===null||E===void 0?void 0:E.validate)===null||j===void 0?void 0:j.evaluated;if(J.props!==!0)if(M&&!M.dynamicProps){if(M.props!==void 0)J.props=ND.mergeEvaluated.props(G,M.props,J.props)}else{let z=G.var("props",w1._`${F}.evaluated.props`);J.props=ND.mergeEvaluated.props(G,z,J.props,w1.Name)}if(J.items!==!0)if(M&&!M.dynamicItems){if(M.items!==void 0)J.items=ND.mergeEvaluated.items(G,M.items,J.items)}else{let z=G.var("items",w1._`${F}.evaluated.items`);J.items=ND.mergeEvaluated.items(G,z,J.items,w1.Name)}}}GI.callRef=WD;GI.default=Pn});var NI=Z((DI)=>{Object.defineProperty(DI,"__esModule",{value:!0});var kn=$I(),bn=AI(),Zn=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",kn.default,bn.default];DI.default=Zn});var OI=Z((WI)=>{Object.defineProperty(WI,"__esModule",{value:!0});var OD=W0(),GE=OD.operators,UD={maximum:{okStr:"<=",ok:GE.LTE,fail:GE.GT},minimum:{okStr:">=",ok:GE.GTE,fail:GE.LT},exclusiveMaximum:{okStr:"<",ok:GE.LT,fail:GE.GTE},exclusiveMinimum:{okStr:">",ok:GE.GT,fail:GE.LTE}},_n={message:({keyword:$,schemaCode:w})=>OD.str`must be ${UD[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>OD._`{comparison: ${UD[$].okStr}, limit: ${w}}`},vn={keyword:Object.keys(UD),type:"number",schemaType:"number",$data:!0,error:_n,code($){let{keyword:w,data:E,schemaCode:X}=$;$.fail$data(OD._`${E} ${UD[w].fail} ${X} || isNaN(${E})`)}};WI.default=vn});var YI=Z((UI)=>{Object.defineProperty(UI,"__esModule",{value:!0});var a6=W0(),xn={message:({schemaCode:$})=>a6.str`must be multiple of ${$}`,params:({schemaCode:$})=>a6._`{multipleOf: ${$}}`},yn={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:xn,code($){let{gen:w,data:E,schemaCode:X,it:G}=$,J=G.opts.multipleOfPrecision,A=w.let("res"),D=J?a6._`Math.abs(Math.round(${A}) - ${A}) > 1e-${J}`:a6._`${A} !== parseInt(${A})`;$.fail$data(a6._`(${X} === 0 || (${A} = ${E}/${X}, ${D}))`)}};UI.default=yn});var FI=Z((LI)=>{Object.defineProperty(LI,"__esModule",{value:!0});function HI($){let w=$.length,E=0,X=0,G;while(X<w)if(E++,G=$.charCodeAt(X++),G>=55296&&G<=56319&&X<w){if(G=$.charCodeAt(X),(G&64512)===56320)X++}return E}LI.default=HI;HI.code='require("ajv/dist/runtime/ucs2length").default'});var MI=Z((jI)=>{Object.defineProperty(jI,"__esModule",{value:!0});var _E=W0(),hn=R0(),cn=FI(),nn={message({keyword:$,schemaCode:w}){let E=$==="maxLength"?"more":"fewer";return _E.str`must NOT have ${E} than ${w} characters`},params:({schemaCode:$})=>_E._`{limit: ${$}}`},mn={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:nn,code($){let{keyword:w,data:E,schemaCode:X,it:G}=$,J=w==="maxLength"?_E.operators.GT:_E.operators.LT,A=G.opts.unicode===!1?_E._`${E}.length`:_E._`${(0,hn.useFunc)($.gen,cn.default)}(${E})`;$.fail$data(_E._`${A} ${J} ${X}`)}};jI.default=mn});var zI=Z((RI)=>{Object.defineProperty(RI,"__esModule",{value:!0});var pn=I1(),on=R0(),lX=W0(),tn={message:({schemaCode:$})=>lX.str`must match pattern "${$}"`,params:({schemaCode:$})=>lX._`{pattern: ${$}}`},dn={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:tn,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:J,it:A}=$,D=A.opts.unicodeRegExp?"u":"";if(X){let{regExp:N}=A.opts.code,W=N.code==="new RegExp"?lX._`new RegExp`:(0,on.useFunc)(w,N),O=w.let("valid");w.try(()=>w.assign(O,lX._`${W}(${J}, ${D}).test(${E})`),()=>w.assign(O,!1)),$.fail$data(lX._`!${O}`)}else{let N=(0,pn.usePattern)($,G);$.fail$data(lX._`!${N}.test(${E})`)}}};RI.default=dn});var BI=Z((TI)=>{Object.defineProperty(TI,"__esModule",{value:!0});var e6=W0(),sn={message({keyword:$,schemaCode:w}){let E=$==="maxProperties"?"more":"fewer";return e6.str`must NOT have ${E} than ${w} properties`},params:({schemaCode:$})=>e6._`{limit: ${$}}`},an={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:sn,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxProperties"?e6.operators.GT:e6.operators.LT;$.fail$data(e6._`Object.keys(${E}).length ${G} ${X}`)}};TI.default=an});var II=Z((QI)=>{Object.defineProperty(QI,"__esModule",{value:!0});var $J=I1(),wJ=W0(),$m=R0(),wm={message:({params:{missingProperty:$}})=>wJ.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>wJ._`{missingProperty: ${$}}`},Em={keyword:"required",type:"object",schemaType:"array",$data:!0,error:wm,code($){let{gen:w,schema:E,schemaCode:X,data:G,$data:J,it:A}=$,{opts:D}=A;if(!J&&E.length===0)return;let N=E.length>=D.loopRequired;if(A.allErrors)W();else O();if(D.strictRequired){let L=$.parentSchema.properties,{definedProperties:F}=$.it;for(let j of E)if((L===null||L===void 0?void 0:L[j])===void 0&&!F.has(j)){let M=A.schemaEnv.baseId+A.errSchemaPath,z=`required property "${j}" is not defined at "${M}" (strictRequired)`;(0,$m.checkStrictMode)(A,z,A.opts.strictRequired)}}function W(){if(N||J)$.block$data(wJ.nil,Y);else for(let L of E)(0,$J.checkReportMissingProp)($,L)}function O(){let L=w.let("missing");if(N||J){let F=w.let("valid",!0);$.block$data(F,()=>H(L,F)),$.ok(F)}else w.if((0,$J.checkMissingProp)($,E,L)),(0,$J.reportMissingProp)($,L),w.else()}function Y(){w.forOf("prop",X,(L)=>{$.setParams({missingProperty:L}),w.if((0,$J.noPropertyInData)(w,G,L,D.ownProperties),()=>$.error())})}function H(L,F){$.setParams({missingProperty:L}),w.forOf(L,X,()=>{w.assign(F,(0,$J.propertyInData)(w,G,L,D.ownProperties)),w.if((0,wJ.not)(F),()=>{$.error(),w.break()})},wJ.nil)}}};QI.default=Em});var VI=Z((KI)=>{Object.defineProperty(KI,"__esModule",{value:!0});var EJ=W0(),Gm={message({keyword:$,schemaCode:w}){let E=$==="maxItems"?"more":"fewer";return EJ.str`must NOT have ${E} than ${w} items`},params:({schemaCode:$})=>EJ._`{limit: ${$}}`},Jm={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Gm,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxItems"?EJ.operators.GT:EJ.operators.LT;$.fail$data(EJ._`${E}.length ${G} ${X}`)}};KI.default=Jm});var YD=Z((qI)=>{Object.defineProperty(qI,"__esModule",{value:!0});var PI=hW();PI.code='require("ajv/dist/runtime/equal").default';qI.default=PI});var kI=Z((SI)=>{Object.defineProperty(SI,"__esModule",{value:!0});var EO=n6(),K$=W0(),Nm=R0(),Wm=YD(),Om={message:({params:{i:$,j:w}})=>K$.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>K$._`{i: ${$}, j: ${w}}`},Um={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Om,code($){let{gen:w,data:E,$data:X,schema:G,parentSchema:J,schemaCode:A,it:D}=$;if(!X&&!G)return;let N=w.let("valid"),W=J.items?(0,EO.getSchemaTypes)(J.items):[];$.block$data(N,O,K$._`${A} === false`),$.ok(N);function O(){let F=w.let("i",K$._`${E}.length`),j=w.let("j");$.setParams({i:F,j}),w.assign(N,!0),w.if(K$._`${F} > 1`,()=>(Y()?H:L)(F,j))}function Y(){return W.length>0&&!W.some((F)=>F==="object"||F==="array")}function H(F,j){let M=w.name("item"),z=(0,EO.checkDataTypes)(W,M,D.opts.strictNumbers,EO.DataType.Wrong),B=w.const("indices",K$._`{}`);w.for(K$._`;${F}--;`,()=>{if(w.let(M,K$._`${E}[${F}]`),w.if(z,K$._`continue`),W.length>1)w.if(K$._`typeof ${M} == "string"`,K$._`${M} += "_"`);w.if(K$._`typeof ${B}[${M}] == "number"`,()=>{w.assign(j,K$._`${B}[${M}]`),$.error(),w.assign(N,!1).break()}).code(K$._`${B}[${M}] = ${F}`)})}function L(F,j){let M=(0,Nm.useFunc)(w,Wm.default),z=w.name("outer");w.label(z).for(K$._`;${F}--;`,()=>w.for(K$._`${j} = ${F}; ${j}--;`,()=>w.if(K$._`${M}(${E}[${F}], ${E}[${j}])`,()=>{$.error(),w.assign(N,!1).break(z)})))}}};SI.default=Um});var ZI=Z((bI)=>{Object.defineProperty(bI,"__esModule",{value:!0});var XO=W0(),Hm=R0(),Lm=YD(),Fm={message:"must be equal to constant",params:({schemaCode:$})=>XO._`{allowedValue: ${$}}`},jm={keyword:"const",$data:!0,error:Fm,code($){let{gen:w,data:E,$data:X,schemaCode:G,schema:J}=$;if(X||J&&typeof J=="object")$.fail$data(XO._`!${(0,Hm.useFunc)(w,Lm.default)}(${E}, ${G})`);else $.fail(XO._`${J} !== ${E}`)}};bI.default=jm});var _I=Z((CI)=>{Object.defineProperty(CI,"__esModule",{value:!0});var XJ=W0(),Rm=R0(),zm=YD(),Tm={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>XJ._`{allowedValues: ${$}}`},Bm={keyword:"enum",schemaType:"array",$data:!0,error:Tm,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:J,it:A}=$;if(!X&&G.length===0)throw Error("enum must have non-empty array");let D=G.length>=A.opts.loopEnum,N,W=()=>N!==null&&N!==void 0?N:N=(0,Rm.useFunc)(w,zm.default),O;if(D||X)O=w.let("valid"),$.block$data(O,Y);else{if(!Array.isArray(G))throw Error("ajv implementation error");let L=w.const("vSchema",J);O=(0,XJ.or)(...G.map((F,j)=>H(L,j)))}$.pass(O);function Y(){w.assign(O,!1),w.forOf("v",J,(L)=>w.if(XJ._`${W()}(${E}, ${L})`,()=>w.assign(O,!0).break()))}function H(L,F){let j=G[F];return typeof j==="object"&&j!==null?XJ._`${W()}(${E}, ${L}[${F}])`:XJ._`${E} === ${j}`}}};CI.default=Bm});var fI=Z((vI)=>{Object.defineProperty(vI,"__esModule",{value:!0});var Im=OI(),Km=YI(),Vm=MI(),Pm=zI(),qm=BI(),Sm=II(),km=VI(),bm=kI(),Zm=ZI(),Cm=_I(),_m=[Im.default,Km.default,Vm.default,Pm.default,qm.default,Sm.default,km.default,bm.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Zm.default,Cm.default];vI.default=_m});var JO=Z((yI)=>{Object.defineProperty(yI,"__esModule",{value:!0});yI.validateAdditionalItems=void 0;var vE=W0(),GO=R0(),fm={message:({params:{len:$}})=>vE.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>vE._`{limit: ${$}}`},xm={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:fm,code($){let{parentSchema:w,it:E}=$,{items:X}=w;if(!Array.isArray(X)){(0,GO.checkStrictMode)(E,'"additionalItems" is ignored when "items" is not an array of schemas');return}xI($,X)}};function xI($,w){let{gen:E,schema:X,data:G,keyword:J,it:A}=$;A.items=!0;let D=E.const("len",vE._`${G}.length`);if(X===!1)$.setParams({len:w.length}),$.pass(vE._`${D} <= ${w.length}`);else if(typeof X=="object"&&!(0,GO.alwaysValidSchema)(A,X)){let W=E.var("valid",vE._`${D} <= ${w.length}`);E.if((0,vE.not)(W),()=>N(W)),$.ok(W)}function N(W){E.forRange("i",w.length,D,(O)=>{if($.subschema({keyword:J,dataProp:O,dataPropType:GO.Type.Num},W),!A.allErrors)E.if((0,vE.not)(W),()=>E.break())})}}yI.validateAdditionalItems=xI;yI.default=xm});var AO=Z((cI)=>{Object.defineProperty(cI,"__esModule",{value:!0});cI.validateTuple=void 0;var uI=W0(),HD=R0(),gm=I1(),um={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:E}=$;if(Array.isArray(w))return hI($,"additionalItems",w);if(E.items=!0,(0,HD.alwaysValidSchema)(E,w))return;$.ok((0,gm.validateArray)($))}};function hI($,w,E=$.schema){let{gen:X,parentSchema:G,data:J,keyword:A,it:D}=$;if(O(G),D.opts.unevaluated&&E.length&&D.items!==!0)D.items=HD.mergeEvaluated.items(X,E.length,D.items);let N=X.name("valid"),W=X.const("len",uI._`${J}.length`);E.forEach((Y,H)=>{if((0,HD.alwaysValidSchema)(D,Y))return;X.if(uI._`${W} > ${H}`,()=>$.subschema({keyword:A,schemaProp:H,dataProp:H},N)),$.ok(N)});function O(Y){let{opts:H,errSchemaPath:L}=D,F=E.length,j=F===Y.minItems&&(F===Y.maxItems||Y[w]===!1);if(H.strictTuples&&!j){let M=`"${A}" is ${F}-tuple, but minItems or maxItems/${w} are not specified or different at path "${L}"`;(0,HD.checkStrictMode)(D,M,H.strictTuples)}}}cI.validateTuple=hI;cI.default=um});var rI=Z((mI)=>{Object.defineProperty(mI,"__esModule",{value:!0});var cm=AO(),nm={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,cm.validateTuple)($,"items")};mI.default=nm});var tI=Z((oI)=>{Object.defineProperty(oI,"__esModule",{value:!0});var pI=W0(),rm=R0(),pm=I1(),om=JO(),tm={message:({params:{len:$}})=>pI.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>pI._`{limit: ${$}}`},im={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:tm,code($){let{schema:w,parentSchema:E,it:X}=$,{prefixItems:G}=E;if(X.items=!0,(0,rm.alwaysValidSchema)(X,w))return;if(G)(0,om.validateAdditionalItems)($,G);else $.ok((0,pm.validateArray)($))}};oI.default=im});var dI=Z((iI)=>{Object.defineProperty(iI,"__esModule",{value:!0});var K1=W0(),LD=R0(),lm={message:({params:{min:$,max:w}})=>w===void 0?K1.str`must contain at least ${$} valid item(s)`:K1.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?K1._`{minContains: ${$}}`:K1._`{minContains: ${$}, maxContains: ${w}}`},sm={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lm,code($){let{gen:w,schema:E,parentSchema:X,data:G,it:J}=$,A,D,{minContains:N,maxContains:W}=X;if(J.opts.next)A=N===void 0?1:N,D=W;else A=1;let O=w.const("len",K1._`${G}.length`);if($.setParams({min:A,max:D}),D===void 0&&A===0){(0,LD.checkStrictMode)(J,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(D!==void 0&&A>D){(0,LD.checkStrictMode)(J,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,LD.alwaysValidSchema)(J,E)){let j=K1._`${O} >= ${A}`;if(D!==void 0)j=K1._`${j} && ${O} <= ${D}`;$.pass(j);return}J.items=!0;let Y=w.name("valid");if(D===void 0&&A===1)L(Y,()=>w.if(Y,()=>w.break()));else if(A===0){if(w.let(Y,!0),D!==void 0)w.if(K1._`${G}.length > 0`,H)}else w.let(Y,!1),H();$.result(Y,()=>$.reset());function H(){let j=w.name("_valid"),M=w.let("count",0);L(j,()=>w.if(j,()=>F(M)))}function L(j,M){w.forRange("i",0,O,(z)=>{$.subschema({keyword:"contains",dataProp:z,dataPropType:LD.Type.Num,compositeRule:!0},j),M()})}function F(j){if(w.code(K1._`${j}++`),D===void 0)w.if(K1._`${j} >= ${A}`,()=>w.assign(Y,!0).break());else if(w.if(K1._`${j} > ${D}`,()=>w.assign(Y,!1).break()),A===1)w.assign(Y,!0);else w.if(K1._`${j} >= ${A}`,()=>w.assign(Y,!0))}}};iI.default=sm});var wK=Z((aI)=>{Object.defineProperty(aI,"__esModule",{value:!0});aI.validateSchemaDeps=aI.validatePropertyDeps=aI.error=void 0;var DO=W0(),em=R0(),GJ=I1();aI.error={message:({params:{property:$,depsCount:w,deps:E}})=>{let X=w===1?"property":"properties";return DO.str`must have ${X} ${E} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:E,missingProperty:X}})=>DO._`{property: ${$},
553
+ path: iss.path ? [${S1(B)}, ...iss.path] : [${S1(B)}]
554
+ })));`),H.write(`newResult[${S1(B)}] = ${I}.value`)}H.write("payload.value = newResult;"),H.write("return payload;");let R=H.compile();return(B,I)=>R(Y,B,I)},G,A=xX,N=!X6.jitless,O=N&&t4.value,W=w.catchall,J;$._zod.parse=(Y,H)=>{J??(J=E.value);let L=Y.value;if(!A(L))return Y.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),Y;let F=[];if(N&&O&&H?.async===!1&&H.jitless!==!0){if(!G)G=X(w.shape);Y=G(Y,H)}else{Y.value={};let I=J.shape;for(let C of J.keys){let v=I[C],k=v._zod.run({value:L[C],issues:[]},H),n=v._zod.optin==="optional"&&v._zod.optout==="optional";if(k instanceof Promise)F.push(k.then((H0)=>n?sM(H0,Y,C,L):U6(H0,Y,C)));else if(n)sM(k,Y,C,L);else U6(k,Y,C)}}if(!W)return F.length?Promise.all(F).then(()=>Y):Y;let j=[],M=J.keySet,R=W._zod,B=R.def.type;for(let I of Object.keys(L)){if(M.has(I))continue;if(B==="never"){j.push(I);continue}let C=R.run({value:L[I],issues:[]},H);if(C instanceof Promise)F.push(C.then((v)=>U6(v,Y,I)));else U6(C,Y,I)}if(j.length)Y.issues.push({code:"unrecognized_keys",keys:j,input:L,inst:$});if(!F.length)return Y;return Promise.all(F).then(()=>{return Y})}});W8=S("$ZodUnion",($,w)=>{v0.init($,w),f0($._zod,"optin",()=>w.options.some((E)=>E._zod.optin==="optional")?"optional":void 0),f0($._zod,"optout",()=>w.options.some((E)=>E._zod.optout==="optional")?"optional":void 0),f0($._zod,"values",()=>{if(w.options.every((E)=>E._zod.values))return new Set(w.options.flatMap((E)=>Array.from(E._zod.values)));return}),f0($._zod,"pattern",()=>{if(w.options.every((E)=>E._zod.pattern)){let E=w.options.map((X)=>X._zod.pattern);return new RegExp(`^(${E.map((X)=>BA(X.source)).join("|")})$`)}return}),$._zod.parse=(E,X)=>{let G=!1,A=[];for(let N of w.options){let D=N._zod.run({value:E.value,issues:[]},X);if(D instanceof Promise)A.push(D),G=!0;else{if(D.issues.length===0)return D;A.push(D)}}if(!G)return aM(A,E,$,X);return Promise.all(A).then((N)=>{return aM(N,E,$,X)})}}),xT=S("$ZodDiscriminatedUnion",($,w)=>{W8.init($,w);let E=$._zod.parse;f0($._zod,"propValues",()=>{let G={};for(let A of w.options){let N=A._zod.propValues;if(!N||Object.keys(N).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(A)}"`);for(let[D,O]of Object.entries(N)){if(!G[D])G[D]=new Set;for(let W of O)G[D].add(W)}}return G});let X=RA(()=>{let G=w.options,A=new Map;for(let N of G){let D=N._zod.propValues[w.discriminator];if(!D||D.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(N)}"`);for(let O of D){if(A.has(O))throw Error(`Duplicate discriminator value "${String(O)}"`);A.set(O,N)}}return A});$._zod.parse=(G,A)=>{let N=G.value;if(!xX(N))return G.issues.push({code:"invalid_type",expected:"object",input:N,inst:$}),G;let D=X.value.get(N?.[w.discriminator]);if(D)return D._zod.run(G,A);if(w.unionFallback)return E(G,A);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:N,path:[w.discriminator],inst:$}),G}}),yT=S("$ZodIntersection",($,w)=>{v0.init($,w),$._zod.parse=(E,X)=>{let G=E.value,A=w.left._zod.run({value:G,issues:[]},X),N=w.right._zod.run({value:G,issues:[]},X);if(A instanceof Promise||N instanceof Promise)return Promise.all([A,N]).then(([O,W])=>{return eM(E,O,W)});return eM(E,A,N)}});gT=S("$ZodRecord",($,w)=>{v0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!yX(G))return E.issues.push({expected:"record",code:"invalid_type",input:G,inst:$}),E;let A=[];if(w.keyType._zod.values){let N=w.keyType._zod.values;E.value={};for(let O of N)if(typeof O==="string"||typeof O==="number"||typeof O==="symbol"){let W=w.valueType._zod.run({value:G[O],issues:[]},X);if(W instanceof Promise)A.push(W.then((J)=>{if(J.issues.length)E.issues.push(...GE(O,J.issues));E.value[O]=J.value}));else{if(W.issues.length)E.issues.push(...GE(O,W.issues));E.value[O]=W.value}}let D;for(let O in G)if(!N.has(O))D=D??[],D.push(O);if(D&&D.length>0)E.issues.push({code:"unrecognized_keys",input:G,inst:$,keys:D})}else{E.value={};for(let N of Reflect.ownKeys(G)){if(N==="__proto__")continue;let D=w.keyType._zod.run({value:N,issues:[]},X);if(D instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(D.issues.length){E.issues.push({origin:"record",code:"invalid_key",issues:D.issues.map((W)=>gw(W,X,Mw())),input:N,path:[N],inst:$}),E.value[D.value]=D.value;continue}let O=w.valueType._zod.run({value:G[N],issues:[]},X);if(O instanceof Promise)A.push(O.then((W)=>{if(W.issues.length)E.issues.push(...GE(N,W.issues));E.value[D.value]=W.value}));else{if(O.issues.length)E.issues.push(...GE(N,O.issues));E.value[D.value]=O.value}}}if(A.length)return Promise.all(A).then(()=>E);return E}}),uT=S("$ZodEnum",($,w)=>{v0.init($,w);let E=n4(w.entries);$._zod.values=new Set(E),$._zod.pattern=new RegExp(`^(${E.filter((X)=>o4.has(typeof X)).map((X)=>typeof X==="string"?lE(X):X.toString()).join("|")})$`),$._zod.parse=(X,G)=>{let A=X.value;if($._zod.values.has(A))return X;return X.issues.push({code:"invalid_value",values:E,input:A,inst:$}),X}}),nT=S("$ZodLiteral",($,w)=>{v0.init($,w),$._zod.values=new Set(w.values),$._zod.pattern=new RegExp(`^(${w.values.map((E)=>typeof E==="string"?lE(E):E?E.toString():String(E)).join("|")})$`),$._zod.parse=(E,X)=>{let G=E.value;if($._zod.values.has(G))return E;return E.issues.push({code:"invalid_value",values:w.values,input:G,inst:$}),E}}),hT=S("$ZodTransform",($,w)=>{v0.init($,w),$._zod.parse=(E,X)=>{let G=w.transform(E.value,E);if(X.async)return(G instanceof Promise?G:Promise.resolve(G)).then((N)=>{return E.value=N,E});if(G instanceof Promise)throw new dE;return E.value=G,E}}),cT=S("$ZodOptional",($,w)=>{v0.init($,w),$._zod.optin="optional",$._zod.optout="optional",f0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),f0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${BA(E.source)})?$`):void 0}),$._zod.parse=(E,X)=>{if(w.innerType._zod.optin==="optional")return w.innerType._zod.run(E,X);if(E.value===void 0)return E;return w.innerType._zod.run(E,X)}}),rT=S("$ZodNullable",($,w)=>{v0.init($,w),f0($._zod,"optin",()=>w.innerType._zod.optin),f0($._zod,"optout",()=>w.innerType._zod.optout),f0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${BA(E.source)}|null)$`):void 0}),f0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),$._zod.parse=(E,X)=>{if(E.value===null)return E;return w.innerType._zod.run(E,X)}}),tT=S("$ZodDefault",($,w)=>{v0.init($,w),$._zod.optin="optional",f0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)return E.value=w.defaultValue,E;let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((A)=>$T(A,w));return $T(G,w)}});oT=S("$ZodPrefault",($,w)=>{v0.init($,w),$._zod.optin="optional",f0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)E.value=w.defaultValue;return w.innerType._zod.run(E,X)}}),mT=S("$ZodNonOptional",($,w)=>{v0.init($,w),f0($._zod,"values",()=>{let E=w.innerType._zod.values;return E?new Set([...E].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((A)=>wT(A,$));return wT(G,$)}});iT=S("$ZodCatch",($,w)=>{v0.init($,w),$._zod.optin="optional",f0($._zod,"optout",()=>w.innerType._zod.optout),f0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((A)=>{if(E.value=A.value,A.issues.length)E.value=w.catchValue({...E,error:{issues:A.issues.map((N)=>gw(N,X,Mw()))},input:E.value}),E.issues=[];return E});if(E.value=G.value,G.issues.length)E.value=w.catchValue({...E,error:{issues:G.issues.map((A)=>gw(A,X,Mw()))},input:E.value}),E.issues=[];return E}}),pT=S("$ZodPipe",($,w)=>{v0.init($,w),f0($._zod,"values",()=>w.in._zod.values),f0($._zod,"optin",()=>w.in._zod.optin),f0($._zod,"optout",()=>w.out._zod.optout),$._zod.parse=(E,X)=>{let G=w.in._zod.run(E,X);if(G instanceof Promise)return G.then((A)=>ET(A,w,X));return ET(G,w,X)}});dT=S("$ZodReadonly",($,w)=>{v0.init($,w),f0($._zod,"propValues",()=>w.innerType._zod.propValues),f0($._zod,"values",()=>w.innerType._zod.values),f0($._zod,"optin",()=>w.innerType._zod.optin),f0($._zod,"optout",()=>w.innerType._zod.optout),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then(XT);return XT(G)}});lT=S("$ZodCustom",($,w)=>{y$.init($,w),v0.init($,w),$._zod.parse=(E,X)=>{return E},$._zod.check=(E)=>{let X=E.value,G=w.fn(X);if(G instanceof Promise)return G.then((A)=>GT(A,E,X,$));GT(G,E,X,$);return}})});function J8(){return{localeError:Wv()}}var Ov=($)=>{let w=typeof $;switch(w){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return w},Wv=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(X){return $[X]??null}let E={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${Ov(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${N6(X.values[0])}`;return`Invalid option: expected one of ${G6(X.values,"|")}`;case"too_big":{let G=X.inclusive?"<=":"<",A=w(X.origin);if(A)return`Too big: expected ${X.origin??"value"} to have ${G}${X.maximum.toString()} ${A.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${G}${X.maximum.toString()}`}case"too_small":{let G=X.inclusive?">=":">",A=w(X.origin);if(A)return`Too small: expected ${X.origin} to have ${G}${X.minimum.toString()} ${A.unit}`;return`Too small: expected ${X.origin} to be ${G}${X.minimum.toString()}`}case"invalid_format":{let G=X;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${E[G.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${G6(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};var aT=T(()=>{KE()});var H6=()=>{};class eT{constructor(){this._map=new Map,this._idmap=new Map}add($,...w){let E=w[0];if(this._map.set($,E),E&&typeof E==="object"&&"id"in E){if(this._idmap.has(E.id))throw Error(`ID ${E.id} already exists in the registry`);this._idmap.set(E.id,$)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove($){let w=this._map.get($);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete($),this}get($){let w=$._zod.parent;if(w){let E={...this.get(w)??{}};return delete E.id,{...E,...this._map.get($)}}return this._map.get($)}has($){return this._map.has($)}}function Jv(){return new eT}var mA0,iA0,VA;var $R=T(()=>{mA0=Symbol("ZodOutput"),iA0=Symbol("ZodInput");VA=Jv()});function wR($,w){return new $({type:"string",...s(w)})}function ER($,w){return new $({type:"string",format:"email",check:"string_format",abort:!1,...s(w)})}function Y8($,w){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...s(w)})}function XR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...s(w)})}function GR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...s(w)})}function AR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...s(w)})}function NR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...s(w)})}function DR($,w){return new $({type:"string",format:"url",check:"string_format",abort:!1,...s(w)})}function OR($,w){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...s(w)})}function WR($,w){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...s(w)})}function JR($,w){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...s(w)})}function UR($,w){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...s(w)})}function YR($,w){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...s(w)})}function HR($,w){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...s(w)})}function LR($,w){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...s(w)})}function FR($,w){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...s(w)})}function jR($,w){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...s(w)})}function MR($,w){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...s(w)})}function TR($,w){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...s(w)})}function RR($,w){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...s(w)})}function zR($,w){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...s(w)})}function BR($,w){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...s(w)})}function IR($,w){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...s(w)})}function QR($,w){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...s(w)})}function KR($,w){return new $({type:"string",format:"date",check:"string_format",...s(w)})}function VR($,w){return new $({type:"string",format:"time",check:"string_format",precision:null,...s(w)})}function PR($,w){return new $({type:"string",format:"duration",check:"string_format",...s(w)})}function qR($,w){return new $({type:"number",checks:[],...s(w)})}function SR($,w){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...s(w)})}function kR($,w){return new $({type:"boolean",...s(w)})}function bR($,w){return new $({type:"null",...s(w)})}function _R($){return new $({type:"unknown"})}function ZR($,w){return new $({type:"never",...s(w)})}function L6($,w){return new X8({check:"less_than",...s(w),value:$,inclusive:!1})}function PA($,w){return new X8({check:"less_than",...s(w),value:$,inclusive:!0})}function F6($,w){return new G8({check:"greater_than",...s(w),value:$,inclusive:!1})}function qA($,w){return new G8({check:"greater_than",...s(w),value:$,inclusive:!0})}function j6($,w){return new xM({check:"multiple_of",...s(w),value:$})}function M6($,w){return new gM({check:"max_length",...s(w),maximum:$})}function gX($,w){return new uM({check:"min_length",...s(w),minimum:$})}function T6($,w){return new nM({check:"length_equals",...s(w),length:$})}function H8($,w){return new hM({check:"string_format",format:"regex",...s(w),pattern:$})}function L8($){return new cM({check:"string_format",format:"lowercase",...s($)})}function F8($){return new rM({check:"string_format",format:"uppercase",...s($)})}function j8($,w){return new tM({check:"string_format",format:"includes",...s(w),includes:$})}function M8($,w){return new oM({check:"string_format",format:"starts_with",...s(w),prefix:$})}function T8($,w){return new mM({check:"string_format",format:"ends_with",...s(w),suffix:$})}function b1($){return new iM({check:"overwrite",tx:$})}function R8($){return b1((w)=>w.normalize($))}function z8(){return b1(($)=>$.trim())}function B8(){return b1(($)=>$.toLowerCase())}function I8(){return b1(($)=>$.toUpperCase())}function CR($,w,E){return new $({type:"array",element:w,...s(E)})}function fR($,w,E){let X=s(E);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:w,...X})}function vR($,w,E){return new $({type:"custom",check:"custom",fn:w,...s(E)})}var xR=T(()=>{J6();KE()});var yR=()=>{};var gR=()=>{};var uR=()=>{};var Tw=T(()=>{KE();W6();H6();uR();vX();e4();l4();sT();J6();N8();$R();yR();xR();gR()});var nR=T(()=>{Tw()});var hR=()=>{};var cR=()=>{};var rR=()=>{};var tR=()=>{};var oR=T(()=>{Tw();H6();rR();tR();nR();hR();cR()});var mR=T(()=>{oR()});var iR=T(()=>{mR()});function nX($){return!!$._zod}function sE($,w){if(nX($))return QA($,w);return $.safeParse(w)}function R6($){if(!$)return;let w;if(nX($))w=$._zod?.def?.shape;else w=$.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function pR($){if(nX($)){let A=$._zod?.def;if(A){if(A.value!==void 0)return A.value;if(Array.isArray(A.values)&&A.values.length>0)return A.values[0]}}let E=$._def;if(E){if(E.value!==void 0)return E.value;if(Array.isArray(E.values)&&E.values.length>0)return E.values[0]}let X=$.value;if(X!==void 0)return X;return}var z6=T(()=>{iR()});var Q8=T(()=>{Tw()});var SA={};OE(SA,{time:()=>P8,duration:()=>q8,datetime:()=>K8,date:()=>V8,ZodISOTime:()=>sR,ZodISODuration:()=>aR,ZodISODateTime:()=>dR,ZodISODate:()=>lR});function K8($){return QR(dR,$)}function V8($){return KR(lR,$)}function P8($){return VR(sR,$)}function q8($){return PR(aR,$)}var dR,lR,sR,aR;var S8=T(()=>{Tw();k8();dR=S("ZodISODateTime",($,w)=>{jT.init($,w),i0.init($,w)});lR=S("ZodISODate",($,w)=>{MT.init($,w),i0.init($,w)});sR=S("ZodISOTime",($,w)=>{TT.init($,w),i0.init($,w)});aR=S("ZodISODuration",($,w)=>{RT.init($,w),i0.init($,w)})});var eR=($,w)=>{D6.init($,w),$.name="ZodError",Object.defineProperties($,{format:{value:(E)=>XM($,E)},flatten:{value:(E)=>EM($,E)},addIssue:{value:(E)=>$.issues.push(E)},addIssues:{value:(E)=>$.issues.push(...E)},isEmpty:{get(){return $.issues.length===0}}})},yN0,kA;var b8=T(()=>{Tw();Tw();yN0=S("ZodError",eR),kA=S("ZodError",eR,{Parent:Error})});var $z,wz,Ez,Xz;var _8=T(()=>{Tw();b8();$z=GM(kA),wz=AM(kA),Ez=s4(kA),Xz=a4(kA)});function P($){return wR(Bv,$)}function k0($){return qR(Oz,$)}function Az($){return SR(uv,$)}function M$($){return kR(nv,$)}function f8($){return bR(hv,$)}function p0(){return _R(cv)}function tv($){return ZR(rv,$)}function j0($,w){return CR(ov,$,w)}function u($,w){let E={type:"object",get shape(){return Q0.assignProp(this,"shape",{...$}),this.shape},...Q0.normalizeParams(w)};return new Wz(E)}function t$($,w){return new Wz({type:"object",get shape(){return Q0.assignProp(this,"shape",{...$}),this.shape},catchall:p0(),...Q0.normalizeParams(w)})}function x0($,w){return new Jz({type:"union",options:$,...Q0.normalizeParams(w)})}function v8($,w,E){return new mv({type:"union",options:w,discriminator:$,...Q0.normalizeParams(E)})}function I6($,w){return new iv({type:"intersection",left:$,right:w})}function d0($,w,E){return new pv({type:"record",keyType:$,valueType:w,...Q0.normalizeParams(E)})}function e$($,w){let E=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new Z8({type:"enum",entries:E,...Q0.normalizeParams(w)})}function o($,w){return new dv({type:"literal",values:Array.isArray($)?$:[$],...Q0.normalizeParams(w)})}function Uz($){return new lv({type:"transform",transform:$})}function $$($){return new Yz({type:"optional",innerType:$})}function Nz($){return new sv({type:"nullable",innerType:$})}function ev($,w){return new av({type:"default",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function wx($,w){return new $x({type:"prefault",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function Ex($,w){return new Hz({type:"nonoptional",innerType:$,...Q0.normalizeParams(w)})}function Gx($,w){return new Xx({type:"catch",innerType:$,catchValue:typeof w==="function"?w:()=>w})}function C8($,w){return new Ax({type:"pipe",in:$,out:w})}function Dx($){return new Nx({type:"readonly",innerType:$})}function Ox($){let w=new y$({check:"custom"});return w._zod.check=$,w}function Fz($,w){return fR(Lz,$??(()=>!0),w)}function Wx($,w={}){return vR(Lz,$,w)}function Jx($){let w=Ox((E)=>{return E.addIssue=(X)=>{if(typeof X==="string")E.issues.push(Q0.issue(X,E.value,w._zod.def));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=E.value),G.inst??(G.inst=w),G.continue??(G.continue=!w._zod.def.abort),E.issues.push(Q0.issue(G))}},$(E.value,E)});return w}function x8($,w){return C8(Uz($),w)}var w$,Dz,Bv,i0,Iv,Gz,B6,Qv,Kv,Vv,Pv,qv,Sv,kv,bv,_v,Zv,Cv,fv,vv,xv,yv,gv,Oz,uv,nv,hv,cv,rv,ov,Wz,Jz,mv,iv,pv,Z8,dv,lv,Yz,sv,av,$x,Hz,Xx,Ax,Nx,Lz;var k8=T(()=>{Tw();Tw();Q8();S8();_8();w$=S("ZodType",($,w)=>{return v0.init($,w),$.def=w,Object.defineProperty($,"_def",{value:w}),$.check=(...E)=>{return $.clone({...w,checks:[...w.checks??[],...E.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]})},$.clone=(E,X)=>XE($,E,X),$.brand=()=>$,$.register=(E,X)=>{return E.add($,X),$},$.parse=(E,X)=>$z($,E,X,{callee:$.parse}),$.safeParse=(E,X)=>Ez($,E,X),$.parseAsync=async(E,X)=>wz($,E,X,{callee:$.parseAsync}),$.safeParseAsync=async(E,X)=>Xz($,E,X),$.spa=$.safeParseAsync,$.refine=(E,X)=>$.check(Wx(E,X)),$.superRefine=(E)=>$.check(Jx(E)),$.overwrite=(E)=>$.check(b1(E)),$.optional=()=>$$($),$.nullable=()=>Nz($),$.nullish=()=>$$(Nz($)),$.nonoptional=(E)=>Ex($,E),$.array=()=>j0($),$.or=(E)=>x0([$,E]),$.and=(E)=>I6($,E),$.transform=(E)=>C8($,Uz(E)),$.default=(E)=>ev($,E),$.prefault=(E)=>wx($,E),$.catch=(E)=>Gx($,E),$.pipe=(E)=>C8($,E),$.readonly=()=>Dx($),$.describe=(E)=>{let X=$.clone();return VA.add(X,{description:E}),X},Object.defineProperty($,"description",{get(){return VA.get($)?.description},configurable:!0}),$.meta=(...E)=>{if(E.length===0)return VA.get($);let X=$.clone();return VA.add(X,E[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),Dz=S("_ZodString",($,w)=>{Y6.init($,w),w$.init($,w);let E=$._zod.bag;$.format=E.format??null,$.minLength=E.minimum??null,$.maxLength=E.maximum??null,$.regex=(...X)=>$.check(H8(...X)),$.includes=(...X)=>$.check(j8(...X)),$.startsWith=(...X)=>$.check(M8(...X)),$.endsWith=(...X)=>$.check(T8(...X)),$.min=(...X)=>$.check(gX(...X)),$.max=(...X)=>$.check(M6(...X)),$.length=(...X)=>$.check(T6(...X)),$.nonempty=(...X)=>$.check(gX(1,...X)),$.lowercase=(X)=>$.check(L8(X)),$.uppercase=(X)=>$.check(F8(X)),$.trim=()=>$.check(z8()),$.normalize=(...X)=>$.check(R8(...X)),$.toLowerCase=()=>$.check(B8()),$.toUpperCase=()=>$.check(I8())}),Bv=S("ZodString",($,w)=>{Y6.init($,w),Dz.init($,w),$.email=(E)=>$.check(ER(Iv,E)),$.url=(E)=>$.check(DR(Qv,E)),$.jwt=(E)=>$.check(IR(gv,E)),$.emoji=(E)=>$.check(OR(Kv,E)),$.guid=(E)=>$.check(Y8(Gz,E)),$.uuid=(E)=>$.check(XR(B6,E)),$.uuidv4=(E)=>$.check(GR(B6,E)),$.uuidv6=(E)=>$.check(AR(B6,E)),$.uuidv7=(E)=>$.check(NR(B6,E)),$.nanoid=(E)=>$.check(WR(Vv,E)),$.guid=(E)=>$.check(Y8(Gz,E)),$.cuid=(E)=>$.check(JR(Pv,E)),$.cuid2=(E)=>$.check(UR(qv,E)),$.ulid=(E)=>$.check(YR(Sv,E)),$.base64=(E)=>$.check(RR(vv,E)),$.base64url=(E)=>$.check(zR(xv,E)),$.xid=(E)=>$.check(HR(kv,E)),$.ksuid=(E)=>$.check(LR(bv,E)),$.ipv4=(E)=>$.check(FR(_v,E)),$.ipv6=(E)=>$.check(jR(Zv,E)),$.cidrv4=(E)=>$.check(MR(Cv,E)),$.cidrv6=(E)=>$.check(TR(fv,E)),$.e164=(E)=>$.check(BR(yv,E)),$.datetime=(E)=>$.check(K8(E)),$.date=(E)=>$.check(V8(E)),$.time=(E)=>$.check(P8(E)),$.duration=(E)=>$.check(q8(E))});i0=S("ZodStringFormat",($,w)=>{n0.init($,w),Dz.init($,w)}),Iv=S("ZodEmail",($,w)=>{DT.init($,w),i0.init($,w)}),Gz=S("ZodGUID",($,w)=>{AT.init($,w),i0.init($,w)}),B6=S("ZodUUID",($,w)=>{NT.init($,w),i0.init($,w)}),Qv=S("ZodURL",($,w)=>{OT.init($,w),i0.init($,w)}),Kv=S("ZodEmoji",($,w)=>{WT.init($,w),i0.init($,w)}),Vv=S("ZodNanoID",($,w)=>{JT.init($,w),i0.init($,w)}),Pv=S("ZodCUID",($,w)=>{UT.init($,w),i0.init($,w)}),qv=S("ZodCUID2",($,w)=>{YT.init($,w),i0.init($,w)}),Sv=S("ZodULID",($,w)=>{HT.init($,w),i0.init($,w)}),kv=S("ZodXID",($,w)=>{LT.init($,w),i0.init($,w)}),bv=S("ZodKSUID",($,w)=>{FT.init($,w),i0.init($,w)}),_v=S("ZodIPv4",($,w)=>{zT.init($,w),i0.init($,w)}),Zv=S("ZodIPv6",($,w)=>{BT.init($,w),i0.init($,w)}),Cv=S("ZodCIDRv4",($,w)=>{IT.init($,w),i0.init($,w)}),fv=S("ZodCIDRv6",($,w)=>{QT.init($,w),i0.init($,w)}),vv=S("ZodBase64",($,w)=>{VT.init($,w),i0.init($,w)}),xv=S("ZodBase64URL",($,w)=>{PT.init($,w),i0.init($,w)}),yv=S("ZodE164",($,w)=>{qT.init($,w),i0.init($,w)}),gv=S("ZodJWT",($,w)=>{ST.init($,w),i0.init($,w)}),Oz=S("ZodNumber",($,w)=>{O8.init($,w),w$.init($,w),$.gt=(X,G)=>$.check(F6(X,G)),$.gte=(X,G)=>$.check(qA(X,G)),$.min=(X,G)=>$.check(qA(X,G)),$.lt=(X,G)=>$.check(L6(X,G)),$.lte=(X,G)=>$.check(PA(X,G)),$.max=(X,G)=>$.check(PA(X,G)),$.int=(X)=>$.check(Az(X)),$.safe=(X)=>$.check(Az(X)),$.positive=(X)=>$.check(F6(0,X)),$.nonnegative=(X)=>$.check(qA(0,X)),$.negative=(X)=>$.check(L6(0,X)),$.nonpositive=(X)=>$.check(PA(0,X)),$.multipleOf=(X,G)=>$.check(j6(X,G)),$.step=(X,G)=>$.check(j6(X,G)),$.finite=()=>$;let E=$._zod.bag;$.minValue=Math.max(E.minimum??Number.NEGATIVE_INFINITY,E.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(E.maximum??Number.POSITIVE_INFINITY,E.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(E.format??"").includes("int")||Number.isSafeInteger(E.multipleOf??0.5),$.isFinite=!0,$.format=E.format??null});uv=S("ZodNumberFormat",($,w)=>{kT.init($,w),Oz.init($,w)});nv=S("ZodBoolean",($,w)=>{bT.init($,w),w$.init($,w)});hv=S("ZodNull",($,w)=>{_T.init($,w),w$.init($,w)});cv=S("ZodUnknown",($,w)=>{ZT.init($,w),w$.init($,w)});rv=S("ZodNever",($,w)=>{CT.init($,w),w$.init($,w)});ov=S("ZodArray",($,w)=>{fT.init($,w),w$.init($,w),$.element=w.element,$.min=(E,X)=>$.check(gX(E,X)),$.nonempty=(E)=>$.check(gX(1,E)),$.max=(E,X)=>$.check(M6(E,X)),$.length=(E,X)=>$.check(T6(E,X)),$.unwrap=()=>$.element});Wz=S("ZodObject",($,w)=>{vT.init($,w),w$.init($,w),Q0.defineLazy($,"shape",()=>w.shape),$.keyof=()=>e$(Object.keys($._zod.def.shape)),$.catchall=(E)=>$.clone({...$._zod.def,catchall:E}),$.passthrough=()=>$.clone({...$._zod.def,catchall:p0()}),$.loose=()=>$.clone({...$._zod.def,catchall:p0()}),$.strict=()=>$.clone({...$._zod.def,catchall:tv()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(E)=>{return Q0.extend($,E)},$.merge=(E)=>Q0.merge($,E),$.pick=(E)=>Q0.pick($,E),$.omit=(E)=>Q0.omit($,E),$.partial=(...E)=>Q0.partial(Yz,$,E[0]),$.required=(...E)=>Q0.required(Hz,$,E[0])});Jz=S("ZodUnion",($,w)=>{W8.init($,w),w$.init($,w),$.options=w.options});mv=S("ZodDiscriminatedUnion",($,w)=>{Jz.init($,w),xT.init($,w)});iv=S("ZodIntersection",($,w)=>{yT.init($,w),w$.init($,w)});pv=S("ZodRecord",($,w)=>{gT.init($,w),w$.init($,w),$.keyType=w.keyType,$.valueType=w.valueType});Z8=S("ZodEnum",($,w)=>{uT.init($,w),w$.init($,w),$.enum=w.entries,$.options=Object.values(w.entries);let E=new Set(Object.keys(w.entries));$.extract=(X,G)=>{let A={};for(let N of X)if(E.has(N))A[N]=w.entries[N];else throw Error(`Key ${N} not found in enum`);return new Z8({...w,checks:[],...Q0.normalizeParams(G),entries:A})},$.exclude=(X,G)=>{let A={...w.entries};for(let N of X)if(E.has(N))delete A[N];else throw Error(`Key ${N} not found in enum`);return new Z8({...w,checks:[],...Q0.normalizeParams(G),entries:A})}});dv=S("ZodLiteral",($,w)=>{nT.init($,w),w$.init($,w),$.values=new Set(w.values),Object.defineProperty($,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});lv=S("ZodTransform",($,w)=>{hT.init($,w),w$.init($,w),$._zod.parse=(E,X)=>{E.addIssue=(A)=>{if(typeof A==="string")E.issues.push(Q0.issue(A,E.value,w));else{let N=A;if(N.fatal)N.continue=!1;N.code??(N.code="custom"),N.input??(N.input=E.value),N.inst??(N.inst=$),N.continue??(N.continue=!0),E.issues.push(Q0.issue(N))}};let G=w.transform(E.value,E);if(G instanceof Promise)return G.then((A)=>{return E.value=A,E});return E.value=G,E}});Yz=S("ZodOptional",($,w)=>{cT.init($,w),w$.init($,w),$.unwrap=()=>$._zod.def.innerType});sv=S("ZodNullable",($,w)=>{rT.init($,w),w$.init($,w),$.unwrap=()=>$._zod.def.innerType});av=S("ZodDefault",($,w)=>{tT.init($,w),w$.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});$x=S("ZodPrefault",($,w)=>{oT.init($,w),w$.init($,w),$.unwrap=()=>$._zod.def.innerType});Hz=S("ZodNonOptional",($,w)=>{mT.init($,w),w$.init($,w),$.unwrap=()=>$._zod.def.innerType});Xx=S("ZodCatch",($,w)=>{iT.init($,w),w$.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});Ax=S("ZodPipe",($,w)=>{pT.init($,w),w$.init($,w),$.in=w.in,$.out=w.out});Nx=S("ZodReadonly",($,w)=>{dT.init($,w),w$.init($,w)});Lz=S("ZodCustom",($,w)=>{lT.init($,w),w$.init($,w)})});var jz=()=>{};var Mz=()=>{};var Tz=T(()=>{Tw();Tw();aT();H6();S8();Mz();k8();Q8();b8();_8();jz();Mw(J8())});var Rz=T(()=>{Tz()});var zz=T(()=>{Rz()});var y8="2025-11-25",Bz,aE="io.modelcontextprotocol/related-task",K6="2.0",V$,Iz,Qz,ZD0,Hx,Lx,g8,Ww,bA,Kz=($)=>bA.safeParse($).success,P$,Rw,zw,q$,V6,Vz,u8=($)=>Vz.safeParse($).success,Pz,qz=($)=>Pz.safeParse($).success,n8,_A=($)=>n8.safeParse($).success,F0,h8,Sz=($)=>h8.safeParse($).success,kz,CD0,P6,Fx,q6,jx,ZA,hX,bz,Mx,Tx,Rx,zx,Bx,Ix,c8,Qx,Kx,r8,S6,Vx,Px,k6,qx,CA,fA,Sx,vA,cX,kx,xA,b6,_6,Z6,fD0,C6,f6,v6,_z,Zz,Cz,t8,fz,yA,rX,vz,bx,_x,Zx,Cx,fx,o8,vx,xx,yx,gx,ux,nx,hx,cx,rx,tx,ox,mx,ix,px,dx,lx,m8,i8,p8,sx,ax,ex,d8,$y,wy,Ey,Xy,Gy,xz,l8,Ay,x6,vD0,Ny,gA,Dy,xD0,uA,Oy,s8,Wy,Jy,Uy,Yy,Hy,Ly,Fy,Q6,jy,My,Ty,nA,a8,Ry,zy,By,Iy,Qy,Ky,Vy,Py,qy,Sy,ky,by,_y,Zy,Cy,fy,vy,xy,tX,yy,gy,uy,ny,hy,cy,ry,e8,ty,yD0,gD0,uD0,nD0,hD0,cD0,D0,yz;var oX=T(()=>{zz();Bz=[y8,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],V$=Fz(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Iz=x0([P(),k0().int()]),Qz=P(),ZD0=t$({ttl:x0([k0(),f8()]).optional(),pollInterval:k0().optional()}),Hx=u({ttl:k0().optional()}),Lx=u({taskId:P()}),g8=t$({progressToken:Iz.optional(),[aE]:Lx.optional()}),Ww=u({_meta:g8.optional()}),bA=Ww.extend({task:Hx.optional()}),P$=u({method:P(),params:Ww.loose().optional()}),Rw=u({_meta:g8.optional()}),zw=u({method:P(),params:Rw.loose().optional()}),q$=t$({_meta:g8.optional()}),V6=x0([P(),k0().int()]),Vz=u({jsonrpc:o(K6),id:V6,...P$.shape}).strict(),Pz=u({jsonrpc:o(K6),...zw.shape}).strict(),n8=u({jsonrpc:o(K6),id:V6,result:q$}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(F0||(F0={}));h8=u({jsonrpc:o(K6),id:V6.optional(),error:u({code:k0().int(),message:P(),data:p0().optional()})}).strict(),kz=x0([Vz,Pz,n8,h8]),CD0=x0([n8,h8]),P6=q$.strict(),Fx=Rw.extend({requestId:V6.optional(),reason:P().optional()}),q6=zw.extend({method:o("notifications/cancelled"),params:Fx}),jx=u({src:P(),mimeType:P().optional(),sizes:j0(P()).optional(),theme:e$(["light","dark"]).optional()}),ZA=u({icons:j0(jx).optional()}),hX=u({name:P(),title:P().optional()}),bz=hX.extend({...hX.shape,...ZA.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),Mx=I6(u({applyDefaults:M$().optional()}),d0(P(),p0())),Tx=x8(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},I6(u({form:Mx.optional(),url:V$.optional()}),d0(P(),p0()).optional())),Rx=t$({list:V$.optional(),cancel:V$.optional(),requests:t$({sampling:t$({createMessage:V$.optional()}).optional(),elicitation:t$({create:V$.optional()}).optional()}).optional()}),zx=t$({list:V$.optional(),cancel:V$.optional(),requests:t$({tools:t$({call:V$.optional()}).optional()}).optional()}),Bx=u({experimental:d0(P(),V$).optional(),sampling:u({context:V$.optional(),tools:V$.optional()}).optional(),elicitation:Tx.optional(),roots:u({listChanged:M$().optional()}).optional(),tasks:Rx.optional()}),Ix=Ww.extend({protocolVersion:P(),capabilities:Bx,clientInfo:bz}),c8=P$.extend({method:o("initialize"),params:Ix}),Qx=u({experimental:d0(P(),V$).optional(),logging:V$.optional(),completions:V$.optional(),prompts:u({listChanged:M$().optional()}).optional(),resources:u({subscribe:M$().optional(),listChanged:M$().optional()}).optional(),tools:u({listChanged:M$().optional()}).optional(),tasks:zx.optional()}),Kx=q$.extend({protocolVersion:P(),capabilities:Qx,serverInfo:bz,instructions:P().optional()}),r8=zw.extend({method:o("notifications/initialized"),params:Rw.optional()}),S6=P$.extend({method:o("ping"),params:Ww.optional()}),Vx=u({progress:k0(),total:$$(k0()),message:$$(P())}),Px=u({...Rw.shape,...Vx.shape,progressToken:Iz}),k6=zw.extend({method:o("notifications/progress"),params:Px}),qx=Ww.extend({cursor:Qz.optional()}),CA=P$.extend({params:qx.optional()}),fA=q$.extend({nextCursor:Qz.optional()}),Sx=e$(["working","input_required","completed","failed","cancelled"]),vA=u({taskId:P(),status:Sx,ttl:x0([k0(),f8()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:$$(k0()),statusMessage:$$(P())}),cX=q$.extend({task:vA}),kx=Rw.merge(vA),xA=zw.extend({method:o("notifications/tasks/status"),params:kx}),b6=P$.extend({method:o("tasks/get"),params:Ww.extend({taskId:P()})}),_6=q$.merge(vA),Z6=P$.extend({method:o("tasks/result"),params:Ww.extend({taskId:P()})}),fD0=q$.loose(),C6=CA.extend({method:o("tasks/list")}),f6=fA.extend({tasks:j0(vA)}),v6=P$.extend({method:o("tasks/cancel"),params:Ww.extend({taskId:P()})}),_z=q$.merge(vA),Zz=u({uri:P(),mimeType:$$(P()),_meta:d0(P(),p0()).optional()}),Cz=Zz.extend({text:P()}),t8=P().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),fz=Zz.extend({blob:t8}),yA=e$(["user","assistant"]),rX=u({audience:j0(yA).optional(),priority:k0().min(0).max(1).optional(),lastModified:SA.datetime({offset:!0}).optional()}),vz=u({...hX.shape,...ZA.shape,uri:P(),description:$$(P()),mimeType:$$(P()),annotations:rX.optional(),_meta:$$(t$({}))}),bx=u({...hX.shape,...ZA.shape,uriTemplate:P(),description:$$(P()),mimeType:$$(P()),annotations:rX.optional(),_meta:$$(t$({}))}),_x=CA.extend({method:o("resources/list")}),Zx=fA.extend({resources:j0(vz)}),Cx=CA.extend({method:o("resources/templates/list")}),fx=fA.extend({resourceTemplates:j0(bx)}),o8=Ww.extend({uri:P()}),vx=o8,xx=P$.extend({method:o("resources/read"),params:vx}),yx=q$.extend({contents:j0(x0([Cz,fz]))}),gx=zw.extend({method:o("notifications/resources/list_changed"),params:Rw.optional()}),ux=o8,nx=P$.extend({method:o("resources/subscribe"),params:ux}),hx=o8,cx=P$.extend({method:o("resources/unsubscribe"),params:hx}),rx=Rw.extend({uri:P()}),tx=zw.extend({method:o("notifications/resources/updated"),params:rx}),ox=u({name:P(),description:$$(P()),required:$$(M$())}),mx=u({...hX.shape,...ZA.shape,description:$$(P()),arguments:$$(j0(ox)),_meta:$$(t$({}))}),ix=CA.extend({method:o("prompts/list")}),px=fA.extend({prompts:j0(mx)}),dx=Ww.extend({name:P(),arguments:d0(P(),P()).optional()}),lx=P$.extend({method:o("prompts/get"),params:dx}),m8=u({type:o("text"),text:P(),annotations:rX.optional(),_meta:d0(P(),p0()).optional()}),i8=u({type:o("image"),data:t8,mimeType:P(),annotations:rX.optional(),_meta:d0(P(),p0()).optional()}),p8=u({type:o("audio"),data:t8,mimeType:P(),annotations:rX.optional(),_meta:d0(P(),p0()).optional()}),sx=u({type:o("tool_use"),name:P(),id:P(),input:d0(P(),p0()),_meta:d0(P(),p0()).optional()}),ax=u({type:o("resource"),resource:x0([Cz,fz]),annotations:rX.optional(),_meta:d0(P(),p0()).optional()}),ex=vz.extend({type:o("resource_link")}),d8=x0([m8,i8,p8,ex,ax]),$y=u({role:yA,content:d8}),wy=q$.extend({description:P().optional(),messages:j0($y)}),Ey=zw.extend({method:o("notifications/prompts/list_changed"),params:Rw.optional()}),Xy=u({title:P().optional(),readOnlyHint:M$().optional(),destructiveHint:M$().optional(),idempotentHint:M$().optional(),openWorldHint:M$().optional()}),Gy=u({taskSupport:e$(["required","optional","forbidden"]).optional()}),xz=u({...hX.shape,...ZA.shape,description:P().optional(),inputSchema:u({type:o("object"),properties:d0(P(),V$).optional(),required:j0(P()).optional()}).catchall(p0()),outputSchema:u({type:o("object"),properties:d0(P(),V$).optional(),required:j0(P()).optional()}).catchall(p0()).optional(),annotations:Xy.optional(),execution:Gy.optional(),_meta:d0(P(),p0()).optional()}),l8=CA.extend({method:o("tools/list")}),Ay=fA.extend({tools:j0(xz)}),x6=q$.extend({content:j0(d8).default([]),structuredContent:d0(P(),p0()).optional(),isError:M$().optional()}),vD0=x6.or(q$.extend({toolResult:p0()})),Ny=bA.extend({name:P(),arguments:d0(P(),p0()).optional()}),gA=P$.extend({method:o("tools/call"),params:Ny}),Dy=zw.extend({method:o("notifications/tools/list_changed"),params:Rw.optional()}),xD0=u({autoRefresh:M$().default(!0),debounceMs:k0().int().nonnegative().default(300)}),uA=e$(["debug","info","notice","warning","error","critical","alert","emergency"]),Oy=Ww.extend({level:uA}),s8=P$.extend({method:o("logging/setLevel"),params:Oy}),Wy=Rw.extend({level:uA,logger:P().optional(),data:p0()}),Jy=zw.extend({method:o("notifications/message"),params:Wy}),Uy=u({name:P().optional()}),Yy=u({hints:j0(Uy).optional(),costPriority:k0().min(0).max(1).optional(),speedPriority:k0().min(0).max(1).optional(),intelligencePriority:k0().min(0).max(1).optional()}),Hy=u({mode:e$(["auto","required","none"]).optional()}),Ly=u({type:o("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:j0(d8).default([]),structuredContent:u({}).loose().optional(),isError:M$().optional(),_meta:d0(P(),p0()).optional()}),Fy=v8("type",[m8,i8,p8]),Q6=v8("type",[m8,i8,p8,sx,Ly]),jy=u({role:yA,content:x0([Q6,j0(Q6)]),_meta:d0(P(),p0()).optional()}),My=bA.extend({messages:j0(jy),modelPreferences:Yy.optional(),systemPrompt:P().optional(),includeContext:e$(["none","thisServer","allServers"]).optional(),temperature:k0().optional(),maxTokens:k0().int(),stopSequences:j0(P()).optional(),metadata:V$.optional(),tools:j0(xz).optional(),toolChoice:Hy.optional()}),Ty=P$.extend({method:o("sampling/createMessage"),params:My}),nA=q$.extend({model:P(),stopReason:$$(e$(["endTurn","stopSequence","maxTokens"]).or(P())),role:yA,content:Fy}),a8=q$.extend({model:P(),stopReason:$$(e$(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:yA,content:x0([Q6,j0(Q6)])}),Ry=u({type:o("boolean"),title:P().optional(),description:P().optional(),default:M$().optional()}),zy=u({type:o("string"),title:P().optional(),description:P().optional(),minLength:k0().optional(),maxLength:k0().optional(),format:e$(["email","uri","date","date-time"]).optional(),default:P().optional()}),By=u({type:e$(["number","integer"]),title:P().optional(),description:P().optional(),minimum:k0().optional(),maximum:k0().optional(),default:k0().optional()}),Iy=u({type:o("string"),title:P().optional(),description:P().optional(),enum:j0(P()),default:P().optional()}),Qy=u({type:o("string"),title:P().optional(),description:P().optional(),oneOf:j0(u({const:P(),title:P()})),default:P().optional()}),Ky=u({type:o("string"),title:P().optional(),description:P().optional(),enum:j0(P()),enumNames:j0(P()).optional(),default:P().optional()}),Vy=x0([Iy,Qy]),Py=u({type:o("array"),title:P().optional(),description:P().optional(),minItems:k0().optional(),maxItems:k0().optional(),items:u({type:o("string"),enum:j0(P())}),default:j0(P()).optional()}),qy=u({type:o("array"),title:P().optional(),description:P().optional(),minItems:k0().optional(),maxItems:k0().optional(),items:u({anyOf:j0(u({const:P(),title:P()}))}),default:j0(P()).optional()}),Sy=x0([Py,qy]),ky=x0([Ky,Vy,Sy]),by=x0([ky,Ry,zy,By]),_y=bA.extend({mode:o("form").optional(),message:P(),requestedSchema:u({type:o("object"),properties:d0(P(),by),required:j0(P()).optional()})}),Zy=bA.extend({mode:o("url"),message:P(),elicitationId:P(),url:P().url()}),Cy=x0([_y,Zy]),fy=P$.extend({method:o("elicitation/create"),params:Cy}),vy=Rw.extend({elicitationId:P()}),xy=zw.extend({method:o("notifications/elicitation/complete"),params:vy}),tX=q$.extend({action:e$(["accept","decline","cancel"]),content:x8(($)=>$===null?void 0:$,d0(P(),x0([P(),k0(),M$(),j0(P())])).optional())}),yy=u({type:o("ref/resource"),uri:P()}),gy=u({type:o("ref/prompt"),name:P()}),uy=Ww.extend({ref:x0([gy,yy]),argument:u({name:P(),value:P()}),context:u({arguments:d0(P(),P()).optional()}).optional()}),ny=P$.extend({method:o("completion/complete"),params:uy}),hy=q$.extend({completion:t$({values:j0(P()).max(100),total:$$(k0().int()),hasMore:$$(M$())})}),cy=u({uri:P().startsWith("file://"),name:P().optional(),_meta:d0(P(),p0()).optional()}),ry=P$.extend({method:o("roots/list"),params:Ww.optional()}),e8=q$.extend({roots:j0(cy)}),ty=zw.extend({method:o("notifications/roots/list_changed"),params:Rw.optional()}),yD0=x0([S6,c8,ny,s8,lx,ix,_x,Cx,xx,nx,cx,gA,l8,b6,Z6,C6,v6]),gD0=x0([q6,k6,r8,ty,xA]),uD0=x0([P6,nA,a8,tX,e8,_6,f6,cX]),nD0=x0([S6,Ty,fy,ry,b6,Z6,C6,v6]),hD0=x0([q6,k6,Jy,tx,gx,Dy,Ey,xA,xy]),cD0=x0([P6,Kx,hy,wy,px,Zx,fx,yx,x6,Ay,_6,f6,cX]);D0=class D0 extends Error{constructor($,w,E){super(`MCP error ${$}: ${w}`);this.code=$,this.data=E,this.name="McpError"}static fromError($,w,E){if($===F0.UrlElicitationRequired&&E){let X=E;if(X.elicitations)return new yz(X.elicitations,w)}return new D0($,w,E)}};yz=class yz extends D0{constructor($,w=`URL elicitation${$.length>1?"s":""} required`){super(F0.UrlElicitationRequired,w,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});function eE($){return $==="completed"||$==="failed"||$==="cancelled"}var oy;var y6=T(()=>{oy=Symbol("Let zodToJsonSchema decide on which parser to use")});var $U=T(()=>{y6()});var Bw=()=>{};var wU=T(()=>{D$()});var EU=()=>{};var g6=T(()=>{D$()});var XU=T(()=>{D$()});var GU=()=>{};var AU=T(()=>{D$()});var NU=T(()=>{D$();Bw()});var DU=T(()=>{D$()});var B60;var u6=T(()=>{B60=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});var n6=T(()=>{D$();u6();g6();Bw()});var OU=T(()=>{D$();n6();Bw()});var WU=T(()=>{Bw()});var h6=T(()=>{D$()});var JU=T(()=>{D$();h6()});var UU=()=>{};var YU=T(()=>{D$()});var HU=T(()=>{D$();Bw()});var LU=T(()=>{D$()});var FU=T(()=>{D$()});var jU=T(()=>{D$()});var MU=T(()=>{D$()});var TU=T(()=>{Bw()});var RU=T(()=>{Bw()});var zU=T(()=>{D$()});var BU=T(()=>{Bw();wU();EU();g6();XU();GU();AU();NU();DU();OU();WU();JU();UU();YU();HU();LU();FU();n6();jU();u6();MU();TU();h6();RU();zU()});var D$=T(()=>{y6();BU();Bw()});var gz=()=>{};var IU=T(()=>{D$();$U();Bw()});var uz=T(()=>{IU();y6();$U();D$();gz();Bw();wU();EU();g6();XU();GU();AU();NU();DU();OU();WU();JU();UU();YU();HU();LU();FU();zU();n6();jU();u6();MU();TU();h6();RU();BU();IU()});function QU($){let E=R6($)?.method;if(!E)throw Error("Schema is missing a method literal");let X=pR(E);if(typeof X!=="string")throw Error("Schema method literal must be a string");return X}function KU($,w){let E=sE($,w);if(!E.success)throw E.error;return E.data}var nz=T(()=>{z6();uz()});class VU{constructor($){if(this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(q6,(w)=>{this._oncancel(w)}),this.setNotificationHandler(k6,(w)=>{this._onprogress(w)}),this.setRequestHandler(S6,(w)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(b6,async(w,E)=>{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new D0(F0.InvalidParams,"Failed to retrieve task: Task not found");return{...X}}),this.setRequestHandler(Z6,async(w,E)=>{let X=async()=>{let G=w.params.taskId;if(this._taskMessageQueue){let N;while(N=await this._taskMessageQueue.dequeue(G,E.sessionId)){if(N.type==="response"||N.type==="error"){let D=N.message,O=D.id,W=this._requestResolvers.get(O);if(W)if(this._requestResolvers.delete(O),N.type==="response")W(D);else{let J=D,Y=new D0(J.error.code,J.error.message,J.error.data);W(Y)}else{let J=N.type==="response"?"Response":"Error";this._onerror(Error(`${J} handler missing for request ${O}`))}continue}await this._transport?.send(N.message,{relatedRequestId:E.requestId})}}let A=await this._taskStore.getTask(G,E.sessionId);if(!A)throw new D0(F0.InvalidParams,`Task not found: ${G}`);if(!eE(A.status))return await this._waitForTaskUpdate(G,E.signal),await X();if(eE(A.status)){let N=await this._taskStore.getTaskResult(G,E.sessionId);return this._clearTaskQueue(G),{...N,_meta:{...N._meta,[aE]:{taskId:G}}}}return await X()};return await X()}),this.setRequestHandler(C6,async(w,E)=>{try{let{tasks:X,nextCursor:G}=await this._taskStore.listTasks(w.params?.cursor,E.sessionId);return{tasks:X,nextCursor:G,_meta:{}}}catch(X){throw new D0(F0.InvalidParams,`Failed to list tasks: ${X instanceof Error?X.message:String(X)}`)}}),this.setRequestHandler(v6,async(w,E)=>{try{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new D0(F0.InvalidParams,`Task not found: ${w.params.taskId}`);if(eE(X.status))throw new D0(F0.InvalidParams,`Cannot cancel task in terminal status: ${X.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",E.sessionId),this._clearTaskQueue(w.params.taskId);let G=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!G)throw new D0(F0.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...G}}catch(X){if(X instanceof D0)throw X;throw new D0(F0.InvalidRequest,`Failed to cancel task: ${X instanceof Error?X.message:String(X)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,w,E,X,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(X,w),startTime:Date.now(),timeout:w,maxTotalTimeout:E,resetTimeoutOnProgress:G,onTimeout:X})}_resetTimeout($){let w=this._timeoutInfo.get($);if(!w)return!1;let E=Date.now()-w.startTime;if(w.maxTotalTimeout&&E>=w.maxTotalTimeout)throw this._timeoutInfo.delete($),D0.fromError(F0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:E});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout($){let w=this._timeoutInfo.get($);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let E=this.transport?.onerror;this._transport.onerror=(G)=>{E?.(G),this._onerror(G)};let X=this._transport?.onmessage;this._transport.onmessage=(G,A)=>{if(X?.(G,A),_A(G)||Sz(G))this._onresponse(G);else if(u8(G))this._onrequest(G,A);else if(qz(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let E of this._requestHandlerAbortControllers.values())E.abort();this._requestHandlerAbortControllers.clear();let w=D0.fromError(F0.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let E of $.values())E(w)}_onerror($){this.onerror?.($)}_onnotification($){let w=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w($)).catch((E)=>this._onerror(Error(`Uncaught error in notification handler: ${E}`)))}_onrequest($,w){let E=this._requestHandlers.get($.method)??this.fallbackRequestHandler,X=this._transport,G=$.params?._meta?.[aE]?.taskId;if(E===void 0){let W={jsonrpc:"2.0",id:$.id,error:{code:F0.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:W,timestamp:Date.now()},X?.sessionId).catch((J)=>this._onerror(Error(`Failed to enqueue error response: ${J}`)));else X?.send(W).catch((J)=>this._onerror(Error(`Failed to send an error response: ${J}`)));return}let A=new AbortController;this._requestHandlerAbortControllers.set($.id,A);let N=Kz($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,X?.sessionId):void 0,O={signal:A.signal,sessionId:X?.sessionId,_meta:$.params?._meta,sendNotification:async(W)=>{if(A.signal.aborted)return;let J={relatedRequestId:$.id};if(G)J.relatedTask={taskId:G};await this.notification(W,J)},sendRequest:async(W,J,Y)=>{if(A.signal.aborted)throw new D0(F0.ConnectionClosed,"Request was cancelled");let H={...Y,relatedRequestId:$.id};if(G&&!H.relatedTask)H.relatedTask={taskId:G};let L=H.relatedTask?.taskId??G;if(L&&D)await D.updateTaskStatus(L,"input_required");return await this.request(W,J,H)},authInfo:w?.authInfo,requestId:$.id,requestInfo:w?.requestInfo,taskId:G,taskStore:D,taskRequestedTtl:N?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(N)this.assertTaskHandlerCapability($.method)}).then(()=>E($,O)).then(async(W)=>{if(A.signal.aborted)return;let J={result:W,jsonrpc:"2.0",id:$.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:J,timestamp:Date.now()},X?.sessionId);else await X?.send(J)},async(W)=>{if(A.signal.aborted)return;let J={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(W.code)?W.code:F0.InternalError,message:W.message??"Internal error",...W.data!==void 0&&{data:W.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:J,timestamp:Date.now()},X?.sessionId);else await X?.send(J)}).catch((W)=>this._onerror(Error(`Failed to send response: ${W}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:w,...E}=$.params,X=Number(w),G=this._progressHandlers.get(X);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let A=this._responseHandlers.get(X),N=this._timeoutInfo.get(X);if(N&&A&&N.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(D){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),A(D);return}G(E)}_onresponse($){let w=Number($.id),E=this._requestResolvers.get(w);if(E){if(this._requestResolvers.delete(w),_A($))E($);else{let A=new D0($.error.code,$.error.message,$.error.data);E(A)}return}let X=this._responseHandlers.get(w);if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let G=!1;if(_A($)&&$.result&&typeof $.result==="object"){let A=$.result;if(A.task&&typeof A.task==="object"){let N=A.task;if(typeof N.taskId==="string")G=!0,this._taskProgressTokens.set(N.taskId,w)}}if(!G)this._progressHandlers.delete(w);if(_A($))X($);else{let A=D0.fromError($.error.code,$.error.message,$.error.data);X(A)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,w,E){let{task:X}=E??{};if(!X){try{yield{type:"result",result:await this.request($,w,E)}}catch(A){yield{type:"error",error:A instanceof D0?A:new D0(F0.InternalError,String(A))}}return}let G;try{let A=await this.request($,cX,E);if(A.task)G=A.task.taskId,yield{type:"taskCreated",task:A.task};else throw new D0(F0.InternalError,"Task creation did not return a task");while(!0){let N=await this.getTask({taskId:G},E);if(yield{type:"taskStatus",task:N},eE(N.status)){if(N.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};else if(N.status==="failed")yield{type:"error",error:new D0(F0.InternalError,`Task ${G} failed`)};else if(N.status==="cancelled")yield{type:"error",error:new D0(F0.InternalError,`Task ${G} was cancelled`)};return}if(N.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};return}let D=N.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((O)=>setTimeout(O,D)),E?.signal?.throwIfAborted()}}catch(A){yield{type:"error",error:A instanceof D0?A:new D0(F0.InternalError,String(A))}}}request($,w,E){let{relatedRequestId:X,resumptionToken:G,onresumptiontoken:A,task:N,relatedTask:D}=E??{};return new Promise((O,W)=>{let J=(R)=>{W(R)};if(!this._transport){J(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),N)this.assertTaskCapability($.method)}catch(R){J(R);return}E?.signal?.throwIfAborted();let Y=this._requestMessageId++,H={...$,jsonrpc:"2.0",id:Y};if(E?.onprogress)this._progressHandlers.set(Y,E.onprogress),H.params={...$.params,_meta:{...$.params?._meta||{},progressToken:Y}};if(N)H.params={...H.params,task:N};if(D)H.params={...H.params,_meta:{...H.params?._meta||{},[aE]:D}};let L=(R)=>{this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:Y,reason:String(R)}},{relatedRequestId:X,resumptionToken:G,onresumptiontoken:A}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let B=R instanceof D0?R:new D0(F0.RequestTimeout,String(R));W(B)};this._responseHandlers.set(Y,(R)=>{if(E?.signal?.aborted)return;if(R instanceof Error)return W(R);try{let B=sE(w,R.result);if(!B.success)W(B.error);else O(B.data)}catch(B){W(B)}}),E?.signal?.addEventListener("abort",()=>{L(E?.signal?.reason)});let F=E?.timeout??sy,j=()=>L(D0.fromError(F0.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(Y,F,E?.maxTotalTimeout,j,E?.resetTimeoutOnProgress??!1);let M=D?.taskId;if(M){let R=(B)=>{let I=this._responseHandlers.get(Y);if(I)I(B);else this._onerror(Error(`Response handler missing for side-channeled request ${Y}`))};this._requestResolvers.set(Y,R),this._enqueueTaskMessage(M,{type:"request",message:H,timestamp:Date.now()}).catch((B)=>{this._cleanupTimeout(Y),W(B)})}else this._transport.send(H,{relatedRequestId:X,resumptionToken:G,onresumptiontoken:A}).catch((R)=>{this._cleanupTimeout(Y),W(R)})})}async getTask($,w){return this.request({method:"tasks/get",params:$},_6,w)}async getTaskResult($,w,E){return this.request({method:"tasks/result",params:$},w,E)}async listTasks($,w){return this.request({method:"tasks/list",params:$},f6,w)}async cancelTask($,w){return this.request({method:"tasks/cancel",params:$},_z,w)}async notification($,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let E=w?.relatedTask?.taskId;if(E){let N={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[aE]:w.relatedTask}}};await this._enqueueTaskMessage(E,{type:"notification",message:N,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let N={...$,jsonrpc:"2.0"};if(w?.relatedTask)N={...N,params:{...N.params,_meta:{...N.params?._meta||{},[aE]:w.relatedTask}}};this._transport?.send(N,w).catch((D)=>this._onerror(D))});return}let A={...$,jsonrpc:"2.0"};if(w?.relatedTask)A={...A,params:{...A.params,_meta:{...A.params?._meta||{},[aE]:w.relatedTask}}};await this._transport.send(A,w)}setRequestHandler($,w){let E=QU($);this.assertRequestHandlerCapability(E),this._requestHandlers.set(E,(X,G)=>{let A=KU($,X);return Promise.resolve(w(A,G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,w){let E=QU($);this._notificationHandlers.set(E,(X)=>{let G=KU($,X);return Promise.resolve(w(G))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let w=this._taskProgressTokens.get($);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,w,E){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let X=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,w,E,X)}async _clearTaskQueue($,w){if(this._taskMessageQueue){let E=await this._taskMessageQueue.dequeueAll($,w);for(let X of E)if(X.type==="request"&&u8(X.message)){let G=X.message.id,A=this._requestResolvers.get(G);if(A)A(new D0(F0.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,w){let E=this._options?.defaultTaskPollInterval??1000;try{let X=await this._taskStore?.getTask($);if(X?.pollInterval)E=X.pollInterval}catch{}return new Promise((X,G)=>{if(w.aborted){G(new D0(F0.InvalidRequest,"Request cancelled"));return}let A=setTimeout(X,E);w.addEventListener("abort",()=>{clearTimeout(A),G(new D0(F0.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,w){let E=this._taskStore;if(!E)throw Error("No task store configured");return{createTask:async(X)=>{if(!$)throw Error("No request provided");return await E.createTask(X,$.id,{method:$.method,params:$.params},w)},getTask:async(X)=>{let G=await E.getTask(X,w);if(!G)throw new D0(F0.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(X,G,A)=>{await E.storeTaskResult(X,G,A,w);let N=await E.getTask(X,w);if(N){let D=xA.parse({method:"notifications/tasks/status",params:N});if(await this.notification(D),eE(N.status))this._cleanupTaskProgressHandler(X)}},getTaskResult:(X)=>{return E.getTaskResult(X,w)},updateTaskStatus:async(X,G,A)=>{let N=await E.getTask(X,w);if(!N)throw new D0(F0.InvalidParams,`Task "${X}" not found - it may have been cleaned up`);if(eE(N.status))throw new D0(F0.InvalidParams,`Cannot update task "${X}" from terminal status "${N.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await E.updateTaskStatus(X,G,A,w);let D=await E.getTask(X,w);if(D){let O=xA.parse({method:"notifications/tasks/status",params:D});if(await this.notification(O),eE(D.status))this._cleanupTaskProgressHandler(X)}},listTasks:(X)=>{return E.listTasks(X,w)}}}}function hz($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function cz($,w){let E={...$};for(let X in w){let G=X,A=w[G];if(A===void 0)continue;let N=E[G];if(hz(N)&&hz(A))E[G]={...N,...A};else E[G]=A}return E}var sy=60000;var rz=T(()=>{z6();oX();nz()});var rA=_((mz)=>{Object.defineProperty(mz,"__esModule",{value:!0});mz.regexpCode=mz.getEsmExportName=mz.getProperty=mz.safeStringify=mz.stringify=mz.strConcat=mz.addCodeArg=mz.str=mz._=mz.nil=mz._Code=mz.Name=mz.IDENTIFIER=mz._CodeOrName=void 0;class c6{}mz._CodeOrName=c6;mz.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class mX extends c6{constructor($){super();if(!mz.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}mz.Name=mX;class uw extends c6{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,E)=>`${w}${E}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,E)=>{if(E instanceof mX)w[E.str]=(w[E.str]||0)+1;return w},{})}}mz._Code=uw;mz.nil=new uw("");function tz($,...w){let E=[$[0]],X=0;while(X<w.length)qU(E,w[X]),E.push($[++X]);return new uw(E)}mz._=tz;var PU=new uw("+");function oz($,...w){let E=[cA($[0])],X=0;while(X<w.length)E.push(PU),qU(E,w[X]),E.push(PU,cA($[++X]));return ay(E),new uw(E)}mz.str=oz;function qU($,w){if(w instanceof uw)$.push(...w._items);else if(w instanceof mX)$.push(w);else $.push(wg(w))}mz.addCodeArg=qU;function ay($){let w=1;while(w<$.length-1){if($[w]===PU){let E=ey($[w-1],$[w+1]);if(E!==void 0){$.splice(w-1,3,E);continue}$[w++]="+"}w++}}function ey($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof mX||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof mX))return`"${$}${w.slice(1)}`;return}function $g($,w){return w.emptyStr()?$:$.emptyStr()?w:oz`${$}${w}`}mz.strConcat=$g;function wg($){return typeof $=="number"||typeof $=="boolean"||$===null?$:cA(Array.isArray($)?$.join(","):$)}function Eg($){return new uw(cA($))}mz.stringify=Eg;function cA($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}mz.safeStringify=cA;function Xg($){return typeof $=="string"&&mz.IDENTIFIER.test($)?new uw(`.${$}`):tz`[${$}]`}mz.getProperty=Xg;function Gg($){if(typeof $=="string"&&mz.IDENTIFIER.test($))return new uw(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}mz.getEsmExportName=Gg;function Ag($){return new uw($.toString())}mz.regexpCode=Ag});var _U=_((lz)=>{Object.defineProperty(lz,"__esModule",{value:!0});lz.ValueScope=lz.ValueScopeName=lz.Scope=lz.varKinds=lz.UsedValueState=void 0;var $w=rA();class pz extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var t6;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(t6||(lz.UsedValueState=t6={}));lz.varKinds={const:new $w.Name("const"),let:new $w.Name("let"),var:new $w.Name("var")};class kU{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof $w.Name?$:this.name($)}name($){return new $w.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,E;if(((E=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||E===void 0?void 0:E.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}lz.Scope=kU;class bU extends $w.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:E}){this.value=$,this.scopePath=$w._`.${new $w.Name(w)}[${E}]`}}lz.ValueScopeName=bU;var Tg=$w._`\n`;class dz extends kU{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?Tg:$w.nil}}get(){return this._scope}name($){return new bU($,this._newName($))}value($,w){var E;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName($),{prefix:G}=X,A=(E=w.key)!==null&&E!==void 0?E:w.ref,N=this._values[G];if(N){let W=N.get(A);if(W)return W}else N=this._values[G]=new Map;N.set(A,X);let D=this._scope[G]||(this._scope[G]=[]),O=D.length;return D[O]=w.ref,X.setValue(w,{property:G,itemIndex:O}),X}getValue($,w){let E=this._values[$];if(!E)return;return E.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(E)=>{if(E.scopePath===void 0)throw Error(`CodeGen: name "${E}" has no value`);return $w._`${$}${E.scopePath}`})}scopeCode($=this._values,w,E){return this._reduceValues($,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},w,E)}_reduceValues($,w,E={},X){let G=$w.nil;for(let A in $){let N=$[A];if(!N)continue;let D=E[A]=E[A]||new Map;N.forEach((O)=>{if(D.has(O))return;D.set(O,t6.Started);let W=w(O);if(W){let J=this.opts.es5?lz.varKinds.var:lz.varKinds.const;G=$w._`${G}${J} ${O} = ${W};${this.opts._n}`}else if(W=X===null||X===void 0?void 0:X(O))G=$w._`${G}${W}${this.opts._n}`;else throw new pz(O);D.set(O,t6.Completed)})}return G}}lz.ValueScope=dz});var J0=_((ww)=>{Object.defineProperty(ww,"__esModule",{value:!0});ww.or=ww.and=ww.not=ww.CodeGen=ww.operators=ww.varKinds=ww.ValueScopeName=ww.ValueScope=ww.Scope=ww.Name=ww.regexpCode=ww.stringify=ww.getProperty=ww.nil=ww.strConcat=ww.str=ww._=void 0;var M0=rA(),nw=_U(),$1=rA();Object.defineProperty(ww,"_",{enumerable:!0,get:function(){return $1._}});Object.defineProperty(ww,"str",{enumerable:!0,get:function(){return $1.str}});Object.defineProperty(ww,"strConcat",{enumerable:!0,get:function(){return $1.strConcat}});Object.defineProperty(ww,"nil",{enumerable:!0,get:function(){return $1.nil}});Object.defineProperty(ww,"getProperty",{enumerable:!0,get:function(){return $1.getProperty}});Object.defineProperty(ww,"stringify",{enumerable:!0,get:function(){return $1.stringify}});Object.defineProperty(ww,"regexpCode",{enumerable:!0,get:function(){return $1.regexpCode}});Object.defineProperty(ww,"Name",{enumerable:!0,get:function(){return $1.Name}});var l6=_U();Object.defineProperty(ww,"Scope",{enumerable:!0,get:function(){return l6.Scope}});Object.defineProperty(ww,"ValueScope",{enumerable:!0,get:function(){return l6.ValueScope}});Object.defineProperty(ww,"ValueScopeName",{enumerable:!0,get:function(){return l6.ValueScopeName}});Object.defineProperty(ww,"varKinds",{enumerable:!0,get:function(){return l6.varKinds}});ww.operators={GT:new M0._Code(">"),GTE:new M0._Code(">="),LT:new M0._Code("<"),LTE:new M0._Code("<="),EQ:new M0._Code("==="),NEQ:new M0._Code("!=="),NOT:new M0._Code("!"),OR:new M0._Code("||"),AND:new M0._Code("&&"),ADD:new M0._Code("+")};class w1{optimizeNodes(){return this}optimizeNames($,w){return this}}class az extends w1{constructor($,w,E){super();this.varKind=$,this.name=w,this.rhs=E}render({es5:$,_n:w}){let E=$?nw.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${X};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=pX(this.rhs,$,w);return this}get names(){return this.rhs instanceof M0._CodeOrName?this.rhs.names:{}}}class fU extends w1{constructor($,w,E){super();this.lhs=$,this.rhs=w,this.sideEffects=E}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof M0.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=pX(this.rhs,$,w),this}get names(){let $=this.lhs instanceof M0.Name?{}:{...this.lhs.names};return d6($,this.rhs)}}class ez extends fU{constructor($,w,E,X){super($,E,X);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class $B extends w1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class wB extends w1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class EB extends w1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class XB extends w1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=pX(this.code,$,w),this}get names(){return this.code instanceof M0._CodeOrName?this.code.names:{}}}class s6 extends w1{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,E)=>w+E.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let E=$[w].optimizeNodes();if(Array.isArray(E))$.splice(w,1,...E);else if(E)$[w]=E;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:E}=this,X=E.length;while(X--){let G=E[X];if(G.optimizeNames($,w))continue;Ig($,G.names),E.splice(X,1)}return E.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>_1($,w.names),{})}}class E1 extends s6{render($){return"{"+$._n+super.render($)+"}"+$._n}}class GB extends s6{}class tA extends E1{}tA.kind="else";class PE extends E1{constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let E=w.optimizeNodes();w=this.else=Array.isArray(E)?new tA(E):E}if(w){if($===!1)return w instanceof PE?w:w.nodes;if(this.nodes.length)return this;return new PE(WB($),w instanceof PE?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=pX(this.condition,$,w),this}get names(){let $=super.names;if(d6($,this.condition),this.else)_1($,this.else.names);return $}}PE.kind="if";class iX extends E1{}iX.kind="for";class AB extends iX{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=pX(this.iteration,$,w),this}get names(){return _1(super.names,this.iteration.names)}}class NB extends iX{constructor($,w,E,X){super();this.varKind=$,this.name=w,this.from=E,this.to=X}render($){let w=$.es5?nw.varKinds.var:this.varKind,{name:E,from:X,to:G}=this;return`for(${w} ${E}=${X}; ${E}<${G}; ${E}++)`+super.render($)}get names(){let $=d6(super.names,this.from);return d6($,this.to)}}class ZU extends iX{constructor($,w,E,X){super();this.loop=$,this.varKind=w,this.name=E,this.iterable=X}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=pX(this.iterable,$,w),this}get names(){return _1(super.names,this.iterable.names)}}class o6 extends E1{constructor($,w,E){super();this.name=$,this.args=w,this.async=E}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}o6.kind="func";class m6 extends s6{render($){return"return "+super.render($)}}m6.kind="return";class DB extends E1{render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var E,X;return super.optimizeNames($,w),(E=this.catch)===null||E===void 0||E.optimizeNames($,w),(X=this.finally)===null||X===void 0||X.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)_1($,this.catch.names);if(this.finally)_1($,this.finally.names);return $}}class i6 extends E1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}i6.kind="catch";class p6 extends E1{render($){return"finally"+super.render($)}}p6.kind="finally";class OB{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
555
+ `:""},this._extScope=$,this._scope=new nw.Scope({parent:$}),this._nodes=[new GB]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let E=this._extScope.value($,w);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,E,X){let G=this._scope.toName(w);if(E!==void 0&&X)this._constants[G.str]=E;return this._leafNode(new az($,G,E)),G}const($,w,E){return this._def(nw.varKinds.const,$,w,E)}let($,w,E){return this._def(nw.varKinds.let,$,w,E)}var($,w,E){return this._def(nw.varKinds.var,$,w,E)}assign($,w,E){return this._leafNode(new fU($,w,E))}add($,w){return this._leafNode(new ez($,ww.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==M0.nil)this._leafNode(new XB($));return this}object(...$){let w=["{"];for(let[E,X]of $){if(w.length>1)w.push(",");if(w.push(E),E!==X||this.opts.es5)w.push(":"),(0,M0.addCodeArg)(w,X)}return w.push("}"),new M0._Code(w)}if($,w,E){if(this._blockNode(new PE($)),w&&E)this.code(w).else().code(E).endIf();else if(w)this.code(w).endIf();else if(E)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new PE($))}else(){return this._elseNode(new tA)}endIf(){return this._endBlockNode(PE,tA)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new AB($),w)}forRange($,w,E,X,G=this.opts.es5?nw.varKinds.var:nw.varKinds.let){let A=this._scope.toName($);return this._for(new NB(G,A,w,E),()=>X(A))}forOf($,w,E,X=nw.varKinds.const){let G=this._scope.toName($);if(this.opts.es5){let A=w instanceof M0.Name?w:this.var("_arr",w);return this.forRange("_i",0,M0._`${A}.length`,(N)=>{this.var(G,M0._`${A}[${N}]`),E(G)})}return this._for(new ZU("of",X,G,w),()=>E(G))}forIn($,w,E,X=this.opts.es5?nw.varKinds.var:nw.varKinds.const){if(this.opts.ownProperties)return this.forOf($,M0._`Object.keys(${w})`,E);let G=this._scope.toName($);return this._for(new ZU("in",X,G,w),()=>E(G))}endFor(){return this._endBlockNode(iX)}label($){return this._leafNode(new $B($))}break($){return this._leafNode(new wB($))}return($){let w=new m6;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(m6)}try($,w,E){if(!w&&!E)throw Error('CodeGen: "try" without "catch" and "finally"');let X=new DB;if(this._blockNode(X),this.code($),w){let G=this.name("e");this._currNode=X.catch=new i6(G),w(G)}if(E)this._currNode=X.finally=new p6,this.code(E);return this._endBlockNode(i6,p6)}throw($){return this._leafNode(new EB($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let E=this._nodes.length-w;if(E<0||$!==void 0&&E!==$)throw Error(`CodeGen: wrong number of nodes: ${E} vs ${$} expected`);return this._nodes.length=w,this}func($,w=M0.nil,E,X){if(this._blockNode(new o6($,w,E)),X)this.code(X).endFunc();return this}endFunc(){return this._endBlockNode(o6)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let E=this._currNode;if(E instanceof $||w&&E instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof PE))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}ww.CodeGen=OB;function _1($,w){for(let E in w)$[E]=($[E]||0)+(w[E]||0);return $}function d6($,w){return w instanceof M0._CodeOrName?_1($,w.names):$}function pX($,w,E){if($ instanceof M0.Name)return X($);if(!G($))return $;return new M0._Code($._items.reduce((A,N)=>{if(N instanceof M0.Name)N=X(N);if(N instanceof M0._Code)A.push(...N._items);else A.push(N);return A},[]));function X(A){let N=E[A.str];if(N===void 0||w[A.str]!==1)return A;return delete w[A.str],N}function G(A){return A instanceof M0._Code&&A._items.some((N)=>N instanceof M0.Name&&w[N.str]===1&&E[N.str]!==void 0)}}function Ig($,w){for(let E in w)$[E]=($[E]||0)-(w[E]||0)}function WB($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:M0._`!${CU($)}`}ww.not=WB;var Qg=JB(ww.operators.AND);function Kg(...$){return $.reduce(Qg)}ww.and=Kg;var Vg=JB(ww.operators.OR);function Pg(...$){return $.reduce(Vg)}ww.or=Pg;function JB($){return(w,E)=>w===M0.nil?E:E===M0.nil?w:M0._`${CU(w)} ${$} ${CU(E)}`}function CU($){return $ instanceof M0.Name?$:M0._`(${$})`}});var T0=_((RB)=>{Object.defineProperty(RB,"__esModule",{value:!0});RB.checkStrictMode=RB.getErrorPath=RB.Type=RB.useFunc=RB.setEvaluated=RB.evaluatedPropsToName=RB.mergeEvaluated=RB.eachItem=RB.unescapeJsonPointer=RB.escapeJsonPointer=RB.escapeFragment=RB.unescapeFragment=RB.schemaRefOrVal=RB.schemaHasRulesButRef=RB.schemaHasRules=RB.checkUnknownRules=RB.alwaysValidSchema=RB.toHash=void 0;var C0=J0(),bg=rA();function _g($){let w={};for(let E of $)w[E]=!0;return w}RB.toHash=_g;function Zg($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return LB($,w),!FB(w,$.self.RULES.all)}RB.alwaysValidSchema=Zg;function LB($,w=$.schema){let{opts:E,self:X}=$;if(!E.strictSchema)return;if(typeof w==="boolean")return;let G=X.RULES.keywords;for(let A in w)if(!G[A])TB($,`unknown keyword: "${A}"`)}RB.checkUnknownRules=LB;function FB($,w){if(typeof $=="boolean")return!$;for(let E in $)if(w[E])return!0;return!1}RB.schemaHasRules=FB;function Cg($,w){if(typeof $=="boolean")return!$;for(let E in $)if(E!=="$ref"&&w.all[E])return!0;return!1}RB.schemaHasRulesButRef=Cg;function fg({topSchemaRef:$,schemaPath:w},E,X,G){if(!G){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return C0._`${E}`}return C0._`${$}${w}${(0,C0.getProperty)(X)}`}RB.schemaRefOrVal=fg;function vg($){return jB(decodeURIComponent($))}RB.unescapeFragment=vg;function xg($){return encodeURIComponent(xU($))}RB.escapeFragment=xg;function xU($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}RB.escapeJsonPointer=xU;function jB($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}RB.unescapeJsonPointer=jB;function yg($,w){if(Array.isArray($))for(let E of $)w(E);else w($)}RB.eachItem=yg;function YB({mergeNames:$,mergeToName:w,mergeValues:E,resultToName:X}){return(G,A,N,D)=>{let O=N===void 0?A:N instanceof C0.Name?(A instanceof C0.Name?$(G,A,N):w(G,A,N),N):A instanceof C0.Name?(w(G,N,A),A):E(A,N);return D===C0.Name&&!(O instanceof C0.Name)?X(G,O):O}}RB.mergeEvaluated={props:YB({mergeNames:($,w,E)=>$.if(C0._`${E} !== true && ${w} !== undefined`,()=>{$.if(C0._`${w} === true`,()=>$.assign(E,!0),()=>$.assign(E,C0._`${E} || {}`).code(C0._`Object.assign(${E}, ${w})`))}),mergeToName:($,w,E)=>$.if(C0._`${E} !== true`,()=>{if(w===!0)$.assign(E,!0);else $.assign(E,C0._`${E} || {}`),yU($,E,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:MB}),items:YB({mergeNames:($,w,E)=>$.if(C0._`${E} !== true && ${w} !== undefined`,()=>$.assign(E,C0._`${w} === true ? true : ${E} > ${w} ? ${E} : ${w}`)),mergeToName:($,w,E)=>$.if(C0._`${E} !== true`,()=>$.assign(E,w===!0?!0:C0._`${E} > ${w} ? ${E} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function MB($,w){if(w===!0)return $.var("props",!0);let E=$.var("props",C0._`{}`);if(w!==void 0)yU($,E,w);return E}RB.evaluatedPropsToName=MB;function yU($,w,E){Object.keys(E).forEach((X)=>$.assign(C0._`${w}${(0,C0.getProperty)(X)}`,!0))}RB.setEvaluated=yU;var HB={};function gg($,w){return $.scopeValue("func",{ref:w,code:HB[w.code]||(HB[w.code]=new bg._Code(w.code))})}RB.useFunc=gg;var vU;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(vU||(RB.Type=vU={}));function ug($,w,E){if($ instanceof C0.Name){let X=w===vU.Num;return E?X?C0._`"[" + ${$} + "]"`:C0._`"['" + ${$} + "']"`:X?C0._`"/" + ${$}`:C0._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,C0.getProperty)($).toString():"/"+xU($)}RB.getErrorPath=ug;function TB($,w,E=$.opts.strictSchema){if(!E)return;if(w=`strict mode: ${w}`,E===!0)throw Error(w);$.self.logger.warn(w)}RB.checkStrictMode=TB});var qE=_((BB)=>{Object.defineProperty(BB,"__esModule",{value:!0});var g$=J0(),Xu={data:new g$.Name("data"),valCxt:new g$.Name("valCxt"),instancePath:new g$.Name("instancePath"),parentData:new g$.Name("parentData"),parentDataProperty:new g$.Name("parentDataProperty"),rootData:new g$.Name("rootData"),dynamicAnchors:new g$.Name("dynamicAnchors"),vErrors:new g$.Name("vErrors"),errors:new g$.Name("errors"),this:new g$.Name("this"),self:new g$.Name("self"),scope:new g$.Name("scope"),json:new g$.Name("json"),jsonPos:new g$.Name("jsonPos"),jsonLen:new g$.Name("jsonLen"),jsonPart:new g$.Name("jsonPart")};BB.default=Xu});var oA=_((VB)=>{Object.defineProperty(VB,"__esModule",{value:!0});VB.extendErrors=VB.resetErrorsCount=VB.reportExtraError=VB.reportError=VB.keyword$DataError=VB.keywordError=void 0;var R0=J0(),e6=T0(),o$=qE();VB.keywordError={message:({keyword:$})=>R0.str`must pass "${$}" keyword validation`};VB.keyword$DataError={message:({keyword:$,schemaType:w})=>w?R0.str`"${$}" keyword must be ${w} ($data)`:R0.str`"${$}" keyword is invalid ($data)`};function Au($,w=VB.keywordError,E,X){let{it:G}=$,{gen:A,compositeRule:N,allErrors:D}=G,O=KB($,w,E);if(X!==null&&X!==void 0?X:N||D)IB(A,O);else QB(G,R0._`[${O}]`)}VB.reportError=Au;function Nu($,w=VB.keywordError,E){let{it:X}=$,{gen:G,compositeRule:A,allErrors:N}=X,D=KB($,w,E);if(IB(G,D),!(A||N))QB(X,o$.default.vErrors)}VB.reportExtraError=Nu;function Du($,w){$.assign(o$.default.errors,w),$.if(R0._`${o$.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(R0._`${o$.default.vErrors}.length`,w),()=>$.assign(o$.default.vErrors,null)))}VB.resetErrorsCount=Du;function Ou({gen:$,keyword:w,schemaValue:E,data:X,errsCount:G,it:A}){if(G===void 0)throw Error("ajv implementation error");let N=$.name("err");$.forRange("i",G,o$.default.errors,(D)=>{if($.const(N,R0._`${o$.default.vErrors}[${D}]`),$.if(R0._`${N}.instancePath === undefined`,()=>$.assign(R0._`${N}.instancePath`,(0,R0.strConcat)(o$.default.instancePath,A.errorPath))),$.assign(R0._`${N}.schemaPath`,R0.str`${A.errSchemaPath}/${w}`),A.opts.verbose)$.assign(R0._`${N}.schema`,E),$.assign(R0._`${N}.data`,X)})}VB.extendErrors=Ou;function IB($,w){let E=$.const("err",w);$.if(R0._`${o$.default.vErrors} === null`,()=>$.assign(o$.default.vErrors,R0._`[${E}]`),R0._`${o$.default.vErrors}.push(${E})`),$.code(R0._`${o$.default.errors}++`)}function QB($,w){let{gen:E,validateName:X,schemaEnv:G}=$;if(G.$async)E.throw(R0._`new ${$.ValidationError}(${w})`);else E.assign(R0._`${X}.errors`,w),E.return(!1)}var Z1={keyword:new R0.Name("keyword"),schemaPath:new R0.Name("schemaPath"),params:new R0.Name("params"),propertyName:new R0.Name("propertyName"),message:new R0.Name("message"),schema:new R0.Name("schema"),parentSchema:new R0.Name("parentSchema")};function KB($,w,E){let{createErrors:X}=$.it;if(X===!1)return R0._`{}`;return Wu($,w,E)}function Wu($,w,E={}){let{gen:X,it:G}=$,A=[Ju(G,E),Uu($,E)];return Yu($,w,A),X.object(...A)}function Ju({errorPath:$},{instancePath:w}){let E=w?R0.str`${$}${(0,e6.getErrorPath)(w,e6.Type.Str)}`:$;return[o$.default.instancePath,(0,R0.strConcat)(o$.default.instancePath,E)]}function Uu({keyword:$,it:{errSchemaPath:w}},{schemaPath:E,parentSchema:X}){let G=X?w:R0.str`${w}/${$}`;if(E)G=R0.str`${G}${(0,e6.getErrorPath)(E,e6.Type.Str)}`;return[Z1.schemaPath,G]}function Yu($,{params:w,message:E},X){let{keyword:G,data:A,schemaValue:N,it:D}=$,{opts:O,propertyName:W,topSchemaRef:J,schemaPath:Y}=D;if(X.push([Z1.keyword,G],[Z1.params,typeof w=="function"?w($):w||R0._`{}`]),O.messages)X.push([Z1.message,typeof E=="function"?E($):E]);if(O.verbose)X.push([Z1.schema,N],[Z1.parentSchema,R0._`${J}${Y}`],[o$.default.data,A]);if(W)X.push([Z1.propertyName,W])}});var bB=_((SB)=>{Object.defineProperty(SB,"__esModule",{value:!0});SB.boolOrEmptySchema=SB.topBoolOrEmptySchema=void 0;var Mu=oA(),Tu=J0(),Ru=qE(),zu={message:"boolean schema is false"};function Bu($){let{gen:w,schema:E,validateName:X}=$;if(E===!1)qB($,!1);else if(typeof E=="object"&&E.$async===!0)w.return(Ru.default.data);else w.assign(Tu._`${X}.errors`,null),w.return(!0)}SB.topBoolOrEmptySchema=Bu;function Iu($,w){let{gen:E,schema:X}=$;if(X===!1)E.var(w,!1),qB($);else E.var(w,!0)}SB.boolOrEmptySchema=Iu;function qB($,w){let{gen:E,data:X}=$,G={gen:E,keyword:"false schema",data:X,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,Mu.reportError)(G,zu,void 0,w)}});var uU=_((_B)=>{Object.defineProperty(_B,"__esModule",{value:!0});_B.getRules=_B.isJSONType=void 0;var Ku=["string","number","integer","boolean","null","object","array"],Vu=new Set(Ku);function Pu($){return typeof $=="string"&&Vu.has($)}_B.isJSONType=Pu;function qu(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}_B.getRules=qu});var nU=_((vB)=>{Object.defineProperty(vB,"__esModule",{value:!0});vB.shouldUseRule=vB.shouldUseGroup=vB.schemaHasRulesForType=void 0;function ku({schema:$,self:w},E){let X=w.RULES.types[E];return X&&X!==!0&&CB($,X)}vB.schemaHasRulesForType=ku;function CB($,w){return w.rules.some((E)=>fB($,E))}vB.shouldUseGroup=CB;function fB($,w){var E;return $[w.keyword]!==void 0||((E=w.definition.implements)===null||E===void 0?void 0:E.some((X)=>$[X]!==void 0))}vB.shouldUseRule=fB});var mA=_((nB)=>{Object.defineProperty(nB,"__esModule",{value:!0});nB.reportTypeError=nB.checkDataTypes=nB.checkDataType=nB.coerceAndCheckDataType=nB.getJSONTypes=nB.getSchemaTypes=nB.DataType=void 0;var Zu=uU(),Cu=nU(),fu=oA(),O0=J0(),yB=T0(),dX;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(dX||(nB.DataType=dX={}));function vu($){let w=gB($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}nB.getSchemaTypes=vu;function gB($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(Zu.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}nB.getJSONTypes=gB;function xu($,w){let{gen:E,data:X,opts:G}=$,A=yu(w,G.coerceTypes),N=w.length>0&&!(A.length===0&&w.length===1&&(0,Cu.schemaHasRulesForType)($,w[0]));if(N){let D=cU(w,X,G.strictNumbers,dX.Wrong);E.if(D,()=>{if(A.length)gu($,w,A);else rU($)})}return N}nB.coerceAndCheckDataType=xu;var uB=new Set(["string","number","integer","boolean","null"]);function yu($,w){return w?$.filter((E)=>uB.has(E)||w==="array"&&E==="array"):[]}function gu($,w,E){let{gen:X,data:G,opts:A}=$,N=X.let("dataType",O0._`typeof ${G}`),D=X.let("coerced",O0._`undefined`);if(A.coerceTypes==="array")X.if(O0._`${N} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>X.assign(G,O0._`${G}[0]`).assign(N,O0._`typeof ${G}`).if(cU(w,G,A.strictNumbers),()=>X.assign(D,G)));X.if(O0._`${D} !== undefined`);for(let W of E)if(uB.has(W)||W==="array"&&A.coerceTypes==="array")O(W);X.else(),rU($),X.endIf(),X.if(O0._`${D} !== undefined`,()=>{X.assign(G,D),uu($,D)});function O(W){switch(W){case"string":X.elseIf(O0._`${N} == "number" || ${N} == "boolean"`).assign(D,O0._`"" + ${G}`).elseIf(O0._`${G} === null`).assign(D,O0._`""`);return;case"number":X.elseIf(O0._`${N} == "boolean" || ${G} === null
556
+ || (${N} == "string" && ${G} && ${G} == +${G})`).assign(D,O0._`+${G}`);return;case"integer":X.elseIf(O0._`${N} === "boolean" || ${G} === null
557
+ || (${N} === "string" && ${G} && ${G} == +${G} && !(${G} % 1))`).assign(D,O0._`+${G}`);return;case"boolean":X.elseIf(O0._`${G} === "false" || ${G} === 0 || ${G} === null`).assign(D,!1).elseIf(O0._`${G} === "true" || ${G} === 1`).assign(D,!0);return;case"null":X.elseIf(O0._`${G} === "" || ${G} === 0 || ${G} === false`),X.assign(D,null);return;case"array":X.elseIf(O0._`${N} === "string" || ${N} === "number"
558
+ || ${N} === "boolean" || ${G} === null`).assign(D,O0._`[${G}]`)}}}function uu({gen:$,parentData:w,parentDataProperty:E},X){$.if(O0._`${w} !== undefined`,()=>$.assign(O0._`${w}[${E}]`,X))}function hU($,w,E,X=dX.Correct){let G=X===dX.Correct?O0.operators.EQ:O0.operators.NEQ,A;switch($){case"null":return O0._`${w} ${G} null`;case"array":A=O0._`Array.isArray(${w})`;break;case"object":A=O0._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":A=N(O0._`!(${w} % 1) && !isNaN(${w})`);break;case"number":A=N();break;default:return O0._`typeof ${w} ${G} ${$}`}return X===dX.Correct?A:(0,O0.not)(A);function N(D=O0.nil){return(0,O0.and)(O0._`typeof ${w} == "number"`,D,E?O0._`isFinite(${w})`:O0.nil)}}nB.checkDataType=hU;function cU($,w,E,X){if($.length===1)return hU($[0],w,E,X);let G,A=(0,yB.toHash)($);if(A.array&&A.object){let N=O0._`typeof ${w} != "object"`;G=A.null?N:O0._`!${w} || ${N}`,delete A.null,delete A.array,delete A.object}else G=O0.nil;if(A.number)delete A.integer;for(let N in A)G=(0,O0.and)(G,hU(N,w,E,X));return G}nB.checkDataTypes=cU;var nu={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?O0._`{type: ${$}}`:O0._`{type: ${w}}`};function rU($){let w=hu($);(0,fu.reportError)(w,nu)}nB.reportTypeError=rU;function hu($){let{gen:w,data:E,schema:X}=$,G=(0,yB.schemaRefOrVal)($,X,"type");return{gen:w,keyword:"type",data:E,schema:X.type,schemaCode:G,schemaValue:G,parentSchema:X,params:{},it:$}}});var oB=_((rB)=>{Object.defineProperty(rB,"__esModule",{value:!0});rB.assignDefaults=void 0;var lX=J0(),pu=T0();function du($,w){let{properties:E,items:X}=$.schema;if(w==="object"&&E)for(let G in E)cB($,G,E[G].default);else if(w==="array"&&Array.isArray(X))X.forEach((G,A)=>cB($,A,G.default))}rB.assignDefaults=du;function cB($,w,E){let{gen:X,compositeRule:G,data:A,opts:N}=$;if(E===void 0)return;let D=lX._`${A}${(0,lX.getProperty)(w)}`;if(G){(0,pu.checkStrictMode)($,`default is ignored for: ${D}`);return}let O=lX._`${D} === undefined`;if(N.useDefaults==="empty")O=lX._`${O} || ${D} === null || ${D} === ""`;X.if(O,lX._`${D} = ${(0,lX.stringify)(E)}`)}});var Iw=_((pB)=>{Object.defineProperty(pB,"__esModule",{value:!0});pB.validateUnion=pB.validateArray=pB.usePattern=pB.callValidateCode=pB.schemaProperties=pB.allSchemaProperties=pB.noPropertyInData=pB.propertyInData=pB.isOwnProperty=pB.hasPropFunc=pB.reportMissingProp=pB.checkMissingProp=pB.checkReportMissingProp=void 0;var h0=J0(),tU=T0(),X1=qE(),lu=T0();function su($,w){let{gen:E,data:X,it:G}=$;E.if(mU(E,X,w,G.opts.ownProperties),()=>{$.setParams({missingProperty:h0._`${w}`},!0),$.error()})}pB.checkReportMissingProp=su;function au({gen:$,data:w,it:{opts:E}},X,G){return(0,h0.or)(...X.map((A)=>(0,h0.and)(mU($,w,A,E.ownProperties),h0._`${G} = ${A}`)))}pB.checkMissingProp=au;function eu($,w){$.setParams({missingProperty:w},!0),$.error()}pB.reportMissingProp=eu;function mB($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:h0._`Object.prototype.hasOwnProperty`})}pB.hasPropFunc=mB;function oU($,w,E){return h0._`${mB($)}.call(${w}, ${E})`}pB.isOwnProperty=oU;function $n($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} !== undefined`;return X?h0._`${G} && ${oU($,w,E)}`:G}pB.propertyInData=$n;function mU($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} === undefined`;return X?(0,h0.or)(G,(0,h0.not)(oU($,w,E))):G}pB.noPropertyInData=mU;function iB($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}pB.allSchemaProperties=iB;function wn($,w){return iB(w).filter((E)=>!(0,tU.alwaysValidSchema)($,w[E]))}pB.schemaProperties=wn;function En({schemaCode:$,data:w,it:{gen:E,topSchemaRef:X,schemaPath:G,errorPath:A},it:N},D,O,W){let J=W?h0._`${$}, ${w}, ${X}${G}`:w,Y=[[X1.default.instancePath,(0,h0.strConcat)(X1.default.instancePath,A)],[X1.default.parentData,N.parentData],[X1.default.parentDataProperty,N.parentDataProperty],[X1.default.rootData,X1.default.rootData]];if(N.opts.dynamicRef)Y.push([X1.default.dynamicAnchors,X1.default.dynamicAnchors]);let H=h0._`${J}, ${E.object(...Y)}`;return O!==h0.nil?h0._`${D}.call(${O}, ${H})`:h0._`${D}(${H})`}pB.callValidateCode=En;var Xn=h0._`new RegExp`;function Gn({gen:$,it:{opts:w}},E){let X=w.unicodeRegExp?"u":"",{regExp:G}=w.code,A=G(E,X);return $.scopeValue("pattern",{key:A.toString(),ref:A,code:h0._`${G.code==="new RegExp"?Xn:(0,lu.useFunc)($,G)}(${E}, ${X})`})}pB.usePattern=Gn;function An($){let{gen:w,data:E,keyword:X,it:G}=$,A=w.name("valid");if(G.allErrors){let D=w.let("valid",!0);return N(()=>w.assign(D,!1)),D}return w.var(A,!0),N(()=>w.break()),A;function N(D){let O=w.const("len",h0._`${E}.length`);w.forRange("i",0,O,(W)=>{$.subschema({keyword:X,dataProp:W,dataPropType:tU.Type.Num},A),w.if((0,h0.not)(A),D)})}}pB.validateArray=An;function Nn($){let{gen:w,schema:E,keyword:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(E.some((O)=>(0,tU.alwaysValidSchema)(G,O))&&!G.opts.unevaluated)return;let N=w.let("valid",!1),D=w.name("_valid");w.block(()=>E.forEach((O,W)=>{let J=$.subschema({keyword:X,schemaProp:W,compositeRule:!0},D);if(w.assign(N,h0._`${N} || ${D}`),!$.mergeValidEvaluated(J,D))w.if((0,h0.not)(N))})),$.result(N,()=>$.reset(),()=>$.error(!0))}pB.validateUnion=Nn});var $I=_((aB)=>{Object.defineProperty(aB,"__esModule",{value:!0});aB.validateKeywordUsage=aB.validSchemaType=aB.funcKeywordCode=aB.macroKeywordCode=void 0;var m$=J0(),C1=qE(),Rn=Iw(),zn=oA();function Bn($,w){let{gen:E,keyword:X,schema:G,parentSchema:A,it:N}=$,D=w.macro.call(N.self,G,A,N),O=sB(E,X,D);if(N.opts.validateSchema!==!1)N.self.validateSchema(D,!0);let W=E.name("valid");$.subschema({schema:D,schemaPath:m$.nil,errSchemaPath:`${N.errSchemaPath}/${X}`,topSchemaRef:O,compositeRule:!0},W),$.pass(W,()=>$.error(!0))}aB.macroKeywordCode=Bn;function In($,w){var E;let{gen:X,keyword:G,schema:A,parentSchema:N,$data:D,it:O}=$;Kn(O,w);let W=!D&&w.compile?w.compile.call(O.self,A,N,O):w.validate,J=sB(X,G,W),Y=X.let("valid");$.block$data(Y,H),$.ok((E=w.valid)!==null&&E!==void 0?E:Y);function H(){if(w.errors===!1){if(j(),w.modifying)lB($);M(()=>$.error())}else{let R=w.async?L():F();if(w.modifying)lB($);M(()=>Qn($,R))}}function L(){let R=X.let("ruleErrs",null);return X.try(()=>j(m$._`await `),(B)=>X.assign(Y,!1).if(m$._`${B} instanceof ${O.ValidationError}`,()=>X.assign(R,m$._`${B}.errors`),()=>X.throw(B))),R}function F(){let R=m$._`${J}.errors`;return X.assign(R,null),j(m$.nil),R}function j(R=w.async?m$._`await `:m$.nil){let B=O.opts.passContext?C1.default.this:C1.default.self,I=!(("compile"in w)&&!D||w.schema===!1);X.assign(Y,m$._`${R}${(0,Rn.callValidateCode)($,J,B,I)}`,w.modifying)}function M(R){var B;X.if((0,m$.not)((B=w.valid)!==null&&B!==void 0?B:Y),R)}}aB.funcKeywordCode=In;function lB($){let{gen:w,data:E,it:X}=$;w.if(X.parentData,()=>w.assign(E,m$._`${X.parentData}[${X.parentDataProperty}]`))}function Qn($,w){let{gen:E}=$;E.if(m$._`Array.isArray(${w})`,()=>{E.assign(C1.default.vErrors,m$._`${C1.default.vErrors} === null ? ${w} : ${C1.default.vErrors}.concat(${w})`).assign(C1.default.errors,m$._`${C1.default.vErrors}.length`),(0,zn.extendErrors)($)},()=>$.error())}function Kn({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function sB($,w,E){if(E===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof E=="function"?{ref:E}:{ref:E,code:(0,m$.stringify)(E)})}function Vn($,w,E=!1){return!w.length||w.some((X)=>X==="array"?Array.isArray($):X==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==X||E&&typeof $>"u")}aB.validSchemaType=Vn;function Pn({schema:$,opts:w,self:E,errSchemaPath:X},G,A){if(Array.isArray(G.keyword)?!G.keyword.includes(A):G.keyword!==A)throw Error("ajv implementation error");let N=G.dependencies;if(N===null||N===void 0?void 0:N.some((D)=>!Object.prototype.hasOwnProperty.call($,D)))throw Error(`parent schema must have dependencies of ${A}: ${N.join(",")}`);if(G.validateSchema){if(!G.validateSchema($[A])){let O=`keyword "${A}" value is invalid at path "${X}": `+E.errorsText(G.validateSchema.errors);if(w.validateSchema==="log")E.logger.error(O);else throw Error(O)}}}aB.validateKeywordUsage=Pn});var GI=_((EI)=>{Object.defineProperty(EI,"__esModule",{value:!0});EI.extendSubschemaMode=EI.extendSubschemaData=EI.getSubschema=void 0;var AE=J0(),wI=T0();function bn($,{keyword:w,schemaProp:E,schema:X,schemaPath:G,errSchemaPath:A,topSchemaRef:N}){if(w!==void 0&&X!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let D=$.schema[w];return E===void 0?{schema:D,schemaPath:AE._`${$.schemaPath}${(0,AE.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:D[E],schemaPath:AE._`${$.schemaPath}${(0,AE.getProperty)(w)}${(0,AE.getProperty)(E)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,wI.escapeFragment)(E)}`}}if(X!==void 0){if(G===void 0||A===void 0||N===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:X,schemaPath:G,topSchemaRef:N,errSchemaPath:A}}throw Error('either "keyword" or "schema" must be passed')}EI.getSubschema=bn;function _n($,w,{dataProp:E,dataPropType:X,data:G,dataTypes:A,propertyName:N}){if(G!==void 0&&E!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:D}=w;if(E!==void 0){let{errorPath:W,dataPathArr:J,opts:Y}=w,H=D.let("data",AE._`${w.data}${(0,AE.getProperty)(E)}`,!0);O(H),$.errorPath=AE.str`${W}${(0,wI.getErrorPath)(E,X,Y.jsPropertySyntax)}`,$.parentDataProperty=AE._`${E}`,$.dataPathArr=[...J,$.parentDataProperty]}if(G!==void 0){let W=G instanceof AE.Name?G:D.let("data",G,!0);if(O(W),N!==void 0)$.propertyName=N}if(A)$.dataTypes=A;function O(W){$.data=W,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,W]}}EI.extendSubschemaData=_n;function Zn($,{jtdDiscriminator:w,jtdMetadata:E,compositeRule:X,createErrors:G,allErrors:A}){if(X!==void 0)$.compositeRule=X;if(G!==void 0)$.createErrors=G;if(A!==void 0)$.allErrors=A;$.jtdDiscriminator=w,$.jtdMetadata=E}EI.extendSubschemaMode=Zn});var iU=_((oJ0,AI)=>{AI.exports=function $(w,E){if(w===E)return!0;if(w&&E&&typeof w=="object"&&typeof E=="object"){if(w.constructor!==E.constructor)return!1;var X,G,A;if(Array.isArray(w)){if(X=w.length,X!=E.length)return!1;for(G=X;G--!==0;)if(!$(w[G],E[G]))return!1;return!0}if(w.constructor===RegExp)return w.source===E.source&&w.flags===E.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===E.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===E.toString();if(A=Object.keys(w),X=A.length,X!==Object.keys(E).length)return!1;for(G=X;G--!==0;)if(!Object.prototype.hasOwnProperty.call(E,A[G]))return!1;for(G=X;G--!==0;){var N=A[G];if(!$(w[N],E[N]))return!1}return!0}return w!==w&&E!==E}});var DI=_((mJ0,NI)=>{var G1=NI.exports=function($,w,E){if(typeof w=="function")E=w,w={};E=w.cb||E;var X=typeof E=="function"?E:E.pre||function(){},G=E.post||function(){};$O(w,X,G,$,"",$)};G1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};G1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};G1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};G1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function $O($,w,E,X,G,A,N,D,O,W){if(X&&typeof X=="object"&&!Array.isArray(X)){w(X,G,A,N,D,O,W);for(var J in X){var Y=X[J];if(Array.isArray(Y)){if(J in G1.arrayKeywords)for(var H=0;H<Y.length;H++)$O($,w,E,Y[H],G+"/"+J+"/"+H,A,G,J,X,H)}else if(J in G1.propsKeywords){if(Y&&typeof Y=="object")for(var L in Y)$O($,w,E,Y[L],G+"/"+J+"/"+vn(L),A,G,J,X,L)}else if(J in G1.keywords||$.allKeys&&!(J in G1.skipKeywords))$O($,w,E,Y,G+"/"+J,A,G,J,X)}E(X,G,A,N,D,O,W)}}function vn($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var iA=_((UI)=>{Object.defineProperty(UI,"__esModule",{value:!0});UI.getSchemaRefs=UI.resolveUrl=UI.normalizeId=UI._getFullPath=UI.getFullPath=UI.inlineRef=void 0;var xn=T0(),yn=iU(),gn=DI(),un=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function nn($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!pU($);if(!w)return!1;return OI($)<=w}UI.inlineRef=nn;var hn=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pU($){for(let w in $){if(hn.has(w))return!0;let E=$[w];if(Array.isArray(E)&&E.some(pU))return!0;if(typeof E=="object"&&pU(E))return!0}return!1}function OI($){let w=0;for(let E in $){if(E==="$ref")return 1/0;if(w++,un.has(E))continue;if(typeof $[E]=="object")(0,xn.eachItem)($[E],(X)=>w+=OI(X));if(w===1/0)return 1/0}return w}function WI($,w="",E){if(E!==!1)w=sX(w);let X=$.parse(w);return JI($,X)}UI.getFullPath=WI;function JI($,w){return $.serialize(w).split("#")[0]+"#"}UI._getFullPath=JI;var cn=/#\/?$/;function sX($){return $?$.replace(cn,""):""}UI.normalizeId=sX;function rn($,w,E){return E=sX(E),$.resolve(w,E)}UI.resolveUrl=rn;var tn=/^[a-z_][-a-z0-9._]*$/i;function on($,w){if(typeof $=="boolean")return{};let{schemaId:E,uriResolver:X}=this.opts,G=sX($[E]||w),A={"":G},N=WI(X,G,!1),D={},O=new Set;return gn($,{allKeys:!0},(Y,H,L,F)=>{if(F===void 0)return;let j=N+H,M=A[F];if(typeof Y[E]=="string")M=R.call(this,Y[E]);B.call(this,Y.$anchor),B.call(this,Y.$dynamicAnchor),A[H]=M;function R(I){let C=this.opts.uriResolver.resolve;if(I=sX(M?C(M,I):I),O.has(I))throw J(I);O.add(I);let v=this.refs[I];if(typeof v=="string")v=this.refs[v];if(typeof v=="object")W(Y,v.schema,I);else if(I!==sX(j))if(I[0]==="#")W(Y,D[I],I),D[I]=Y;else this.refs[I]=j;return I}function B(I){if(typeof I=="string"){if(!tn.test(I))throw Error(`invalid anchor "${I}"`);R.call(this,`#${I}`)}}}),D;function W(Y,H,L){if(H!==void 0&&!yn(Y,H))throw J(L)}function J(Y){return Error(`reference "${Y}" resolves to more than one schema`)}}UI.getSchemaRefs=on});var lA=_((qI)=>{Object.defineProperty(qI,"__esModule",{value:!0});qI.getData=qI.KeywordCxt=qI.validateFunctionCode=void 0;var MI=bB(),HI=mA(),lU=nU(),wO=mA(),an=oB(),dA=$I(),dU=GI(),m=J0(),w0=qE(),en=iA(),SE=T0(),pA=oA();function $h($){if(zI($)){if(BI($),RI($)){Xh($);return}}TI($,()=>(0,MI.topBoolOrEmptySchema)($))}qI.validateFunctionCode=$h;function TI({gen:$,validateName:w,schema:E,schemaEnv:X,opts:G},A){if(G.code.es5)$.func(w,m._`${w0.default.data}, ${w0.default.valCxt}`,X.$async,()=>{$.code(m._`"use strict"; ${LI(E,G)}`),Eh($,G),$.code(A)});else $.func(w,m._`${w0.default.data}, ${wh(G)}`,X.$async,()=>$.code(LI(E,G)).code(A))}function wh($){return m._`{${w0.default.instancePath}="", ${w0.default.parentData}, ${w0.default.parentDataProperty}, ${w0.default.rootData}=${w0.default.data}${$.dynamicRef?m._`, ${w0.default.dynamicAnchors}={}`:m.nil}}={}`}function Eh($,w){$.if(w0.default.valCxt,()=>{if($.var(w0.default.instancePath,m._`${w0.default.valCxt}.${w0.default.instancePath}`),$.var(w0.default.parentData,m._`${w0.default.valCxt}.${w0.default.parentData}`),$.var(w0.default.parentDataProperty,m._`${w0.default.valCxt}.${w0.default.parentDataProperty}`),$.var(w0.default.rootData,m._`${w0.default.valCxt}.${w0.default.rootData}`),w.dynamicRef)$.var(w0.default.dynamicAnchors,m._`${w0.default.valCxt}.${w0.default.dynamicAnchors}`)},()=>{if($.var(w0.default.instancePath,m._`""`),$.var(w0.default.parentData,m._`undefined`),$.var(w0.default.parentDataProperty,m._`undefined`),$.var(w0.default.rootData,w0.default.data),w.dynamicRef)$.var(w0.default.dynamicAnchors,m._`{}`)})}function Xh($){let{schema:w,opts:E,gen:X}=$;TI($,()=>{if(E.$comment&&w.$comment)QI($);if(Oh($),X.let(w0.default.vErrors,null),X.let(w0.default.errors,0),E.unevaluated)Gh($);II($),Uh($)});return}function Gh($){let{gen:w,validateName:E}=$;$.evaluated=w.const("evaluated",m._`${E}.evaluated`),w.if(m._`${$.evaluated}.dynamicProps`,()=>w.assign(m._`${$.evaluated}.props`,m._`undefined`)),w.if(m._`${$.evaluated}.dynamicItems`,()=>w.assign(m._`${$.evaluated}.items`,m._`undefined`))}function LI($,w){let E=typeof $=="object"&&$[w.schemaId];return E&&(w.code.source||w.code.process)?m._`/*# sourceURL=${E} */`:m.nil}function Ah($,w){if(zI($)){if(BI($),RI($)){Nh($,w);return}}(0,MI.boolOrEmptySchema)($,w)}function RI({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let E in $)if(w.RULES.all[E])return!0;return!1}function zI($){return typeof $.schema!="boolean"}function Nh($,w){let{schema:E,gen:X,opts:G}=$;if(G.$comment&&E.$comment)QI($);Wh($),Jh($);let A=X.const("_errs",w0.default.errors);II($,A),X.var(w,m._`${A} === ${w0.default.errors}`)}function BI($){(0,SE.checkUnknownRules)($),Dh($)}function II($,w){if($.opts.jtd)return FI($,[],!1,w);let E=(0,HI.getSchemaTypes)($.schema),X=(0,HI.coerceAndCheckDataType)($,E);FI($,E,!X,w)}function Dh($){let{schema:w,errSchemaPath:E,opts:X,self:G}=$;if(w.$ref&&X.ignoreKeywordsWithRef&&(0,SE.schemaHasRulesButRef)(w,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${E}"`)}function Oh($){let{schema:w,opts:E}=$;if(w.default!==void 0&&E.useDefaults&&E.strictSchema)(0,SE.checkStrictMode)($,"default is ignored in the schema root")}function Wh($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,en.resolveUrl)($.opts.uriResolver,$.baseId,w)}function Jh($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function QI({gen:$,schemaEnv:w,schema:E,errSchemaPath:X,opts:G}){let A=E.$comment;if(G.$comment===!0)$.code(m._`${w0.default.self}.logger.log(${A})`);else if(typeof G.$comment=="function"){let N=m.str`${X}/$comment`,D=$.scopeValue("root",{ref:w.root});$.code(m._`${w0.default.self}.opts.$comment(${A}, ${N}, ${D}.schema)`)}}function Uh($){let{gen:w,schemaEnv:E,validateName:X,ValidationError:G,opts:A}=$;if(E.$async)w.if(m._`${w0.default.errors} === 0`,()=>w.return(w0.default.data),()=>w.throw(m._`new ${G}(${w0.default.vErrors})`));else{if(w.assign(m._`${X}.errors`,w0.default.vErrors),A.unevaluated)Yh($);w.return(m._`${w0.default.errors} === 0`)}}function Yh({gen:$,evaluated:w,props:E,items:X}){if(E instanceof m.Name)$.assign(m._`${w}.props`,E);if(X instanceof m.Name)$.assign(m._`${w}.items`,X)}function FI($,w,E,X){let{gen:G,schema:A,data:N,allErrors:D,opts:O,self:W}=$,{RULES:J}=W;if(A.$ref&&(O.ignoreKeywordsWithRef||!(0,SE.schemaHasRulesButRef)(A,J))){G.block(()=>VI($,"$ref",J.all.$ref.definition));return}if(!O.jtd)Hh($,w);G.block(()=>{for(let H of J.rules)Y(H);Y(J.post)});function Y(H){if(!(0,lU.shouldUseGroup)(A,H))return;if(H.type){if(G.if((0,wO.checkDataType)(H.type,N,O.strictNumbers)),jI($,H),w.length===1&&w[0]===H.type&&E)G.else(),(0,wO.reportTypeError)($);G.endIf()}else jI($,H);if(!D)G.if(m._`${w0.default.errors} === ${X||0}`)}}function jI($,w){let{gen:E,schema:X,opts:{useDefaults:G}}=$;if(G)(0,an.assignDefaults)($,w.type);E.block(()=>{for(let A of w.rules)if((0,lU.shouldUseRule)(X,A))VI($,A.keyword,A.definition,w.type)})}function Hh($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(Lh($,w),!$.opts.allowUnionTypes)Fh($,w);jh($,$.dataTypes)}function Lh($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((E)=>{if(!KI($.dataTypes,E))sU($,`type "${E}" not allowed by context "${$.dataTypes.join(",")}"`)}),Th($,w)}function Fh($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))sU($,"use allowUnionTypes to allow union type keyword")}function jh($,w){let E=$.self.RULES.all;for(let X in E){let G=E[X];if(typeof G=="object"&&(0,lU.shouldUseRule)($.schema,G)){let{type:A}=G.definition;if(A.length&&!A.some((N)=>Mh(w,N)))sU($,`missing type "${A.join(",")}" for keyword "${X}"`)}}}function Mh($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function KI($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function Th($,w){let E=[];for(let X of $.dataTypes)if(KI(w,X))E.push(X);else if(w.includes("integer")&&X==="number")E.push("integer");$.dataTypes=E}function sU($,w){let E=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${E}" (strictTypes)`,(0,SE.checkStrictMode)($,w,$.opts.strictTypes)}class aU{constructor($,w,E){if((0,dA.validateKeywordUsage)($,w,E),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=E,this.data=$.data,this.schema=$.schema[E],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,SE.schemaRefOrVal)($,this.schema,E,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",PI(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,dA.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${E} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",w0.default.errors)}result($,w,E){this.failResult((0,m.not)($),w,E)}failResult($,w,E){if(this.gen.if($),E)E();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,m.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(m._`${w} !== undefined && (${(0,m.or)(this.invalid$data(),$)})`)}error($,w,E){if(w){this.setParams(w),this._error($,E),this.setParams({});return}this._error($,E)}_error($,w){($?pA.reportExtraError:pA.reportError)(this,this.def.error,w)}$dataError(){(0,pA.reportError)(this,this.def.$dataError||pA.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,pA.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,E=m.nil){this.gen.block(()=>{this.check$data($,E),w()})}check$data($=m.nil,w=m.nil){if(!this.$data)return;let{gen:E,schemaCode:X,schemaType:G,def:A}=this;if(E.if((0,m.or)(m._`${X} === undefined`,w)),$!==m.nil)E.assign($,!0);if(G.length||A.validateSchema){if(E.elseIf(this.invalid$data()),this.$dataError(),$!==m.nil)E.assign($,!1)}E.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:E,def:X,it:G}=this;return(0,m.or)(A(),N());function A(){if(E.length){if(!(w instanceof m.Name))throw Error("ajv implementation error");let D=Array.isArray(E)?E:[E];return m._`${(0,wO.checkDataTypes)(D,w,G.opts.strictNumbers,wO.DataType.Wrong)}`}return m.nil}function N(){if(X.validateSchema){let D=$.scopeValue("validate$data",{ref:X.validateSchema});return m._`!${D}(${w})`}return m.nil}}subschema($,w){let E=(0,dU.getSubschema)(this.it,$);(0,dU.extendSubschemaData)(E,this.it,$),(0,dU.extendSubschemaMode)(E,$);let X={...this.it,...E,items:void 0,props:void 0};return Ah(X,w),X}mergeEvaluated($,w){let{it:E,gen:X}=this;if(!E.opts.unevaluated)return;if(E.props!==!0&&$.props!==void 0)E.props=SE.mergeEvaluated.props(X,$.props,E.props,w);if(E.items!==!0&&$.items!==void 0)E.items=SE.mergeEvaluated.items(X,$.items,E.items,w)}mergeValidEvaluated($,w){let{it:E,gen:X}=this;if(E.opts.unevaluated&&(E.props!==!0||E.items!==!0))return X.if(w,()=>this.mergeEvaluated($,m.Name)),!0}}qI.KeywordCxt=aU;function VI($,w,E,X){let G=new aU($,E,w);if("code"in E)E.code(G,X);else if(G.$data&&E.validate)(0,dA.funcKeywordCode)(G,E);else if("macro"in E)(0,dA.macroKeywordCode)(G,E);else if(E.compile||E.validate)(0,dA.funcKeywordCode)(G,E)}var Rh=/^\/(?:[^~]|~0|~1)*$/,zh=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function PI($,{dataLevel:w,dataNames:E,dataPathArr:X}){let G,A;if($==="")return w0.default.rootData;if($[0]==="/"){if(!Rh.test($))throw Error(`Invalid JSON-pointer: ${$}`);G=$,A=w0.default.rootData}else{let W=zh.exec($);if(!W)throw Error(`Invalid JSON-pointer: ${$}`);let J=+W[1];if(G=W[2],G==="#"){if(J>=w)throw Error(O("property/index",J));return X[w-J]}if(J>w)throw Error(O("data",J));if(A=E[w-J],!G)return A}let N=A,D=G.split("/");for(let W of D)if(W)A=m._`${A}${(0,m.getProperty)((0,SE.unescapeJsonPointer)(W))}`,N=m._`${N} && ${A}`;return N;function O(W,J){return`Cannot access ${W} ${J} levels up, current level is ${w}`}}qI.getData=PI});var EO=_((bI)=>{Object.defineProperty(bI,"__esModule",{value:!0});class kI extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}bI.default=kI});var sA=_((ZI)=>{Object.defineProperty(ZI,"__esModule",{value:!0});var eU=iA();class _I extends Error{constructor($,w,E,X){super(X||`can't resolve reference ${E} from id ${w}`);this.missingRef=(0,eU.resolveUrl)($,w,E),this.missingSchema=(0,eU.normalizeId)((0,eU.getFullPath)($,this.missingRef))}}ZI.default=_I});var GO=_((vI)=>{Object.defineProperty(vI,"__esModule",{value:!0});vI.resolveSchema=vI.getCompilingSchema=vI.resolveRef=vI.compileSchema=vI.SchemaEnv=void 0;var hw=J0(),Vh=EO(),f1=qE(),cw=iA(),CI=T0(),Ph=lA();class aA{constructor($){var w;this.refs={},this.dynamicAnchors={};let E;if(typeof $.schema=="object")E=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,cw.normalizeId)(E===null||E===void 0?void 0:E[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=E===null||E===void 0?void 0:E.$async,this.refs={}}}vI.SchemaEnv=aA;function w9($){let w=fI.call(this,$);if(w)return w;let E=(0,cw.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:X,lines:G}=this.opts.code,{ownProperties:A}=this.opts,N=new hw.CodeGen(this.scope,{es5:X,lines:G,ownProperties:A}),D;if($.$async)D=N.scopeValue("Error",{ref:Vh.default,code:hw._`require("ajv/dist/runtime/validation_error").default`});let O=N.scopeName("validate");$.validateName=O;let W={gen:N,allErrors:this.opts.allErrors,data:f1.default.data,parentData:f1.default.parentData,parentDataProperty:f1.default.parentDataProperty,dataNames:[f1.default.data],dataPathArr:[hw.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:N.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,hw.stringify)($.schema)}:{ref:$.schema}),validateName:O,ValidationError:D,schema:$.schema,schemaEnv:$,rootId:E,baseId:$.baseId||E,schemaPath:hw.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:hw._`""`,opts:this.opts,self:this},J;try{this._compilations.add($),(0,Ph.validateFunctionCode)(W),N.optimize(this.opts.code.optimize);let Y=N.toString();if(J=`${N.scopeRefs(f1.default.scope)}return ${Y}`,this.opts.code.process)J=this.opts.code.process(J,$);let L=Function(`${f1.default.self}`,`${f1.default.scope}`,J)(this,this.scope.get());if(this.scope.value(O,{ref:L}),L.errors=null,L.schema=$.schema,L.schemaEnv=$,$.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:O,validateCode:Y,scopeValues:N._values};if(this.opts.unevaluated){let{props:F,items:j}=W;if(L.evaluated={props:F instanceof hw.Name?void 0:F,items:j instanceof hw.Name?void 0:j,dynamicProps:F instanceof hw.Name,dynamicItems:j instanceof hw.Name},L.source)L.source.evaluated=(0,hw.stringify)(L.evaluated)}return $.validate=L,$}catch(Y){if(delete $.validate,delete $.validateName,J)this.logger.error("Error compiling schema, function code:",J);throw Y}finally{this._compilations.delete($)}}vI.compileSchema=w9;function qh($,w,E){var X;E=(0,cw.resolveUrl)(this.opts.uriResolver,w,E);let G=$.refs[E];if(G)return G;let A=bh.call(this,$,E);if(A===void 0){let N=(X=$.localRefs)===null||X===void 0?void 0:X[E],{schemaId:D}=this.opts;if(N)A=new aA({schema:N,schemaId:D,root:$,baseId:w})}if(A===void 0)return;return $.refs[E]=Sh.call(this,A)}vI.resolveRef=qh;function Sh($){if((0,cw.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:w9.call(this,$)}function fI($){for(let w of this._compilations)if(kh(w,$))return w}vI.getCompilingSchema=fI;function kh($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function bh($,w){let E;while(typeof(E=this.refs[w])=="string")w=E;return E||this.schemas[w]||XO.call(this,$,w)}function XO($,w){let E=this.opts.uriResolver.parse(w),X=(0,cw._getFullPath)(this.opts.uriResolver,E),G=(0,cw.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&X===G)return $9.call(this,E,$);let A=(0,cw.normalizeId)(X),N=this.refs[A]||this.schemas[A];if(typeof N=="string"){let D=XO.call(this,$,N);if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;return $9.call(this,E,D)}if(typeof(N===null||N===void 0?void 0:N.schema)!=="object")return;if(!N.validate)w9.call(this,N);if(A===(0,cw.normalizeId)(w)){let{schema:D}=N,{schemaId:O}=this.opts,W=D[O];if(W)G=(0,cw.resolveUrl)(this.opts.uriResolver,G,W);return new aA({schema:D,schemaId:O,root:$,baseId:G})}return $9.call(this,E,N)}vI.resolveSchema=XO;var _h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function $9($,{baseId:w,schema:E,root:X}){var G;if(((G=$.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let D of $.fragment.slice(1).split("/")){if(typeof E==="boolean")return;let O=E[(0,CI.unescapeFragment)(D)];if(O===void 0)return;E=O;let W=typeof E==="object"&&E[this.opts.schemaId];if(!_h.has(D)&&W)w=(0,cw.resolveUrl)(this.opts.uriResolver,w,W)}let A;if(typeof E!="boolean"&&E.$ref&&!(0,CI.schemaHasRulesButRef)(E,this.RULES)){let D=(0,cw.resolveUrl)(this.opts.uriResolver,w,E.$ref);A=XO.call(this,X,D)}let{schemaId:N}=this.opts;if(A=A||new aA({schema:E,schemaId:N,root:X,baseId:w}),A.schema!==A.root.schema)return A;return}});var yI=_((aJ0,xh)=>{xh.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var X9=_((eJ0,hI)=>{var yh=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),uI=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function E9($){let w="",E=0,X=0;for(X=0;X<$.length;X++){if(E=$[X].charCodeAt(0),E===48)continue;if(!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X];break}for(X+=1;X<$.length;X++){if(E=$[X].charCodeAt(0),!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X]}return w}var gh=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gI($){return $.length=0,!0}function uh($,w,E){if($.length){let X=E9($);if(X!=="")w.push(X);else return E.error=!0,!1;$.length=0}return!0}function nh($){let w=0,E={error:!1,address:"",zone:""},X=[],G=[],A=!1,N=!1,D=uh;for(let O=0;O<$.length;O++){let W=$[O];if(W==="["||W==="]")continue;if(W===":"){if(A===!0)N=!0;if(!D(G,X,E))break;if(++w>7){E.error=!0;break}if(O>0&&$[O-1]===":")A=!0;X.push(":");continue}else if(W==="%"){if(!D(G,X,E))break;D=gI}else{G.push(W);continue}}if(G.length)if(D===gI)E.zone=G.join("");else if(N)X.push(G.join(""));else X.push(E9(G));return E.address=X.join(""),E}function nI($){if(hh($,":")<2)return{host:$,isIPV6:!1};let w=nh($);if(!w.error){let{address:E,address:X}=w;if(w.zone)E+="%"+w.zone,X+="%25"+w.zone;return{host:E,isIPV6:!0,escapedHost:X}}else return{host:$,isIPV6:!1}}function hh($,w){let E=0;for(let X=0;X<$.length;X++)if($[X]===w)E++;return E}function ch($){let w=$,E=[],X=-1,G=0;while(G=w.length){if(G===1)if(w===".")break;else if(w==="/"){E.push("/");break}else{E.push(w);break}else if(G===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){E.push("/");break}}}else if(G===3){if(w==="/.."){if(E.length!==0)E.pop();E.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),E.length!==0)E.pop();continue}}}}if((X=w.indexOf("/",1))===-1){E.push(w);break}else E.push(w.slice(0,X)),w=w.slice(X)}return E.join("")}function rh($,w){let E=w!==!0?escape:unescape;if($.scheme!==void 0)$.scheme=E($.scheme);if($.userinfo!==void 0)$.userinfo=E($.userinfo);if($.host!==void 0)$.host=E($.host);if($.path!==void 0)$.path=E($.path);if($.query!==void 0)$.query=E($.query);if($.fragment!==void 0)$.fragment=E($.fragment);return $}function th($){let w=[];if($.userinfo!==void 0)w.push($.userinfo),w.push("@");if($.host!==void 0){let E=unescape($.host);if(!uI(E)){let X=nI(E);if(X.isIPV6===!0)E=`[${X.escapedHost}]`;else E=$.host}w.push(E)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}hI.exports={nonSimpleDomain:gh,recomposeAuthority:th,normalizeComponentEncoding:rh,removeDotSegments:ch,isIPv4:uI,isUUID:yh,normalizeIPv6:nI,stringArrayToHexStripped:E9}});var mI=_(($40,oI)=>{var{isUUID:oh}=X9(),mh=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ih=["http","https","ws","wss","urn","urn:uuid"];function ph($){return ih.indexOf($)!==-1}function G9($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function cI($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function rI($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function dh($){return $.secure=G9($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function lh($){if($.port===(G9($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[w,E]=$.resourceName.split("?");$.path=w&&w!=="/"?w:void 0,$.query=E,$.resourceName=void 0}return $.fragment=void 0,$}function sh($,w){if(!$.path)return $.error="URN can not be parsed",$;let E=$.path.match(mh);if(E){let X=w.scheme||$.scheme||"urn";$.nid=E[1].toLowerCase(),$.nss=E[2];let G=`${X}:${w.nid||$.nid}`,A=A9(G);if($.path=void 0,A)$=A.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function ah($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let E=w.scheme||$.scheme||"urn",X=$.nid.toLowerCase(),G=`${E}:${w.nid||X}`,A=A9(G);if(A)$=A.serialize($,w);let N=$,D=$.nss;return N.path=`${X||w.nid}:${D}`,w.skipEscape=!0,N}function eh($,w){let E=$;if(E.uuid=E.nss,E.nss=void 0,!w.tolerant&&(!E.uuid||!oh(E.uuid)))E.error=E.error||"UUID is not valid.";return E}function $c($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var tI={scheme:"http",domainHost:!0,parse:cI,serialize:rI},wc={scheme:"https",domainHost:tI.domainHost,parse:cI,serialize:rI},AO={scheme:"ws",domainHost:!0,parse:dh,serialize:lh},Ec={scheme:"wss",domainHost:AO.domainHost,parse:AO.parse,serialize:AO.serialize},Xc={scheme:"urn",parse:sh,serialize:ah,skipNormalize:!0},Gc={scheme:"urn:uuid",parse:eh,serialize:$c,skipNormalize:!0},NO={http:tI,https:wc,ws:AO,wss:Ec,urn:Xc,"urn:uuid":Gc};Object.setPrototypeOf(NO,null);function A9($){return $&&(NO[$]||NO[$.toLowerCase()])||void 0}oI.exports={wsIsSecure:G9,SCHEMES:NO,isValidSchemeName:ph,getSchemeHandler:A9}});var dI=_((w40,OO)=>{var{normalizeIPv6:Ac,removeDotSegments:eA,recomposeAuthority:Nc,normalizeComponentEncoding:DO,isIPv4:Dc,nonSimpleDomain:Oc}=X9(),{SCHEMES:Wc,getSchemeHandler:iI}=mI();function Jc($,w){if(typeof $==="string")$=NE(kE($,w),w);else if(typeof $==="object")$=kE(NE($,w),w);return $}function Uc($,w,E){let X=E?Object.assign({scheme:"null"},E):{scheme:"null"},G=pI(kE($,X),kE(w,X),X,!0);return X.skipEscape=!0,NE(G,X)}function pI($,w,E,X){let G={};if(!X)$=kE(NE($,E),E),w=kE(NE(w,E),E);if(E=E||{},!E.tolerant&&w.scheme)G.scheme=w.scheme,G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=eA(w.path||""),G.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=eA(w.path||""),G.query=w.query;else{if(!w.path)if(G.path=$.path,w.query!==void 0)G.query=w.query;else G.query=$.query;else{if(w.path[0]==="/")G.path=eA(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)G.path="/"+w.path;else if(!$.path)G.path=w.path;else G.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;G.path=eA(G.path)}G.query=w.query}G.userinfo=$.userinfo,G.host=$.host,G.port=$.port}G.scheme=$.scheme}return G.fragment=w.fragment,G}function Yc($,w,E){if(typeof $==="string")$=unescape($),$=NE(DO(kE($,E),!0),{...E,skipEscape:!0});else if(typeof $==="object")$=NE(DO($,!0),{...E,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=NE(DO(kE(w,E),!0),{...E,skipEscape:!0});else if(typeof w==="object")w=NE(DO(w,!0),{...E,skipEscape:!0});return $.toLowerCase()===w.toLowerCase()}function NE($,w){let E={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},X=Object.assign({},w),G=[],A=iI(X.scheme||E.scheme);if(A&&A.serialize)A.serialize(E,X);if(E.path!==void 0)if(!X.skipEscape){if(E.path=escape(E.path),E.scheme!==void 0)E.path=E.path.split("%3A").join(":")}else E.path=unescape(E.path);if(X.reference!=="suffix"&&E.scheme)G.push(E.scheme,":");let N=Nc(E);if(N!==void 0){if(X.reference!=="suffix")G.push("//");if(G.push(N),E.path&&E.path[0]!=="/")G.push("/")}if(E.path!==void 0){let D=E.path;if(!X.absolutePath&&(!A||!A.absolutePath))D=eA(D);if(N===void 0&&D[0]==="/"&&D[1]==="/")D="/%2F"+D.slice(2);G.push(D)}if(E.query!==void 0)G.push("?",E.query);if(E.fragment!==void 0)G.push("#",E.fragment);return G.join("")}var Hc=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kE($,w){let E=Object.assign({},w),X={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(E.reference==="suffix")if(E.scheme)$=E.scheme+":"+$;else $="//"+$;let A=$.match(Hc);if(A){if(X.scheme=A[1],X.userinfo=A[3],X.host=A[4],X.port=parseInt(A[5],10),X.path=A[6]||"",X.query=A[7],X.fragment=A[8],isNaN(X.port))X.port=A[5];if(X.host)if(Dc(X.host)===!1){let O=Ac(X.host);X.host=O.host.toLowerCase(),G=O.isIPV6}else G=!0;if(X.scheme===void 0&&X.userinfo===void 0&&X.host===void 0&&X.port===void 0&&X.query===void 0&&!X.path)X.reference="same-document";else if(X.scheme===void 0)X.reference="relative";else if(X.fragment===void 0)X.reference="absolute";else X.reference="uri";if(E.reference&&E.reference!=="suffix"&&E.reference!==X.reference)X.error=X.error||"URI is not a "+E.reference+" reference.";let N=iI(E.scheme||X.scheme);if(!E.unicodeSupport&&(!N||!N.unicodeSupport)){if(X.host&&(E.domainHost||N&&N.domainHost)&&G===!1&&Oc(X.host))try{X.host=URL.domainToASCII(X.host.toLowerCase())}catch(D){X.error=X.error||"Host's domain name can not be converted to ASCII: "+D}}if(!N||N&&!N.skipNormalize){if($.indexOf("%")!==-1){if(X.scheme!==void 0)X.scheme=unescape(X.scheme);if(X.host!==void 0)X.host=unescape(X.host)}if(X.path)X.path=escape(unescape(X.path));if(X.fragment)X.fragment=encodeURI(decodeURIComponent(X.fragment))}if(N&&N.parse)N.parse(X,E)}else X.error=X.error||"URI can not be parsed.";return X}var N9={SCHEMES:Wc,normalize:Jc,resolve:Uc,resolveComponent:pI,equal:Yc,serialize:NE,parse:kE};OO.exports=N9;OO.exports.default=N9;OO.exports.fastUri=N9});var aI=_((sI)=>{Object.defineProperty(sI,"__esModule",{value:!0});var lI=dI();lI.code='require("ajv/dist/runtime/uri").default';sI.default=lI});var NQ=_((bE)=>{Object.defineProperty(bE,"__esModule",{value:!0});bE.CodeGen=bE.Name=bE.nil=bE.stringify=bE.str=bE._=bE.KeywordCxt=void 0;var Fc=lA();Object.defineProperty(bE,"KeywordCxt",{enumerable:!0,get:function(){return Fc.KeywordCxt}});var aX=J0();Object.defineProperty(bE,"_",{enumerable:!0,get:function(){return aX._}});Object.defineProperty(bE,"str",{enumerable:!0,get:function(){return aX.str}});Object.defineProperty(bE,"stringify",{enumerable:!0,get:function(){return aX.stringify}});Object.defineProperty(bE,"nil",{enumerable:!0,get:function(){return aX.nil}});Object.defineProperty(bE,"Name",{enumerable:!0,get:function(){return aX.Name}});Object.defineProperty(bE,"CodeGen",{enumerable:!0,get:function(){return aX.CodeGen}});var jc=EO(),XQ=sA(),Mc=uU(),$N=GO(),Tc=J0(),wN=iA(),WO=mA(),O9=T0(),eI=yI(),Rc=aI(),GQ=($,w)=>new RegExp($,w);GQ.code="new RegExp";var zc=["removeAdditional","useDefaults","coerceTypes"],Bc=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Ic={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Qc={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$Q=200;function Kc($){var w,E,X,G,A,N,D,O,W,J,Y,H,L,F,j,M,R,B,I,C,v,k,n,H0,b0;let c0=$.strict,l0=(w=$.code)===null||w===void 0?void 0:w.optimize,V0=l0===!0||l0===void 0?1:l0||0,Y$=(X=(E=$.code)===null||E===void 0?void 0:E.regExp)!==null&&X!==void 0?X:GQ,Jw=(G=$.uriResolver)!==null&&G!==void 0?G:Rc.default;return{strictSchema:(N=(A=$.strictSchema)!==null&&A!==void 0?A:c0)!==null&&N!==void 0?N:!0,strictNumbers:(O=(D=$.strictNumbers)!==null&&D!==void 0?D:c0)!==null&&O!==void 0?O:!0,strictTypes:(J=(W=$.strictTypes)!==null&&W!==void 0?W:c0)!==null&&J!==void 0?J:"log",strictTuples:(H=(Y=$.strictTuples)!==null&&Y!==void 0?Y:c0)!==null&&H!==void 0?H:"log",strictRequired:(F=(L=$.strictRequired)!==null&&L!==void 0?L:c0)!==null&&F!==void 0?F:!1,code:$.code?{...$.code,optimize:V0,regExp:Y$}:{optimize:V0,regExp:Y$},loopRequired:(j=$.loopRequired)!==null&&j!==void 0?j:$Q,loopEnum:(M=$.loopEnum)!==null&&M!==void 0?M:$Q,meta:(R=$.meta)!==null&&R!==void 0?R:!0,messages:(B=$.messages)!==null&&B!==void 0?B:!0,inlineRefs:(I=$.inlineRefs)!==null&&I!==void 0?I:!0,schemaId:(C=$.schemaId)!==null&&C!==void 0?C:"$id",addUsedSchema:(v=$.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(k=$.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(n=$.validateFormats)!==null&&n!==void 0?n:!0,unicodeRegExp:(H0=$.unicodeRegExp)!==null&&H0!==void 0?H0:!0,int32range:(b0=$.int32range)!==null&&b0!==void 0?b0:!0,uriResolver:Jw}}class JO{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...Kc($)};let{es5:w,lines:E}=this.opts.code;this.scope=new Tc.ValueScope({scope:{},prefixes:Bc,es5:w,lines:E}),this.logger=bc($.logger);let X=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,Mc.getRules)(),wQ.call(this,Ic,$,"NOT SUPPORTED"),wQ.call(this,Qc,$,"DEPRECATED","warn"),this._metaOpts=Sc.call(this),$.formats)Pc.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)qc.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);Vc.call(this),$.validateFormats=X}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:E}=this.opts,X=eI;if(E==="id")X={...eI},X.id=X.$id,delete X.$id;if(w&&$)this.addMetaSchema(X,X[E],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let E;if(typeof $=="string"){if(E=this.getSchema($),!E)throw Error(`no schema with key or ref "${$}"`)}else E=this.compile($);let X=E(w);if(!("$async"in E))this.errors=E.errors;return X}compile($,w){let E=this._addSchema($,w);return E.validate||this._compileSchemaEnv(E)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:E}=this.opts;return X.call(this,$,w);async function X(W,J){await G.call(this,W.$schema);let Y=this._addSchema(W,J);return Y.validate||A.call(this,Y)}async function G(W){if(W&&!this.getSchema(W))await X.call(this,{$ref:W},!0)}async function A(W){try{return this._compileSchemaEnv(W)}catch(J){if(!(J instanceof XQ.default))throw J;return N.call(this,J),await D.call(this,J.missingSchema),A.call(this,W)}}function N({missingSchema:W,missingRef:J}){if(this.refs[W])throw Error(`AnySchema ${W} is loaded but ${J} cannot be resolved`)}async function D(W){let J=await O.call(this,W);if(!this.refs[W])await G.call(this,J.$schema);if(!this.refs[W])this.addSchema(J,W,w)}async function O(W){let J=this._loading[W];if(J)return J;try{return await(this._loading[W]=E(W))}finally{delete this._loading[W]}}}addSchema($,w,E,X=this.opts.validateSchema){if(Array.isArray($)){for(let A of $)this.addSchema(A,void 0,E,X);return this}let G;if(typeof $==="object"){let{schemaId:A}=this.opts;if(G=$[A],G!==void 0&&typeof G!="string")throw Error(`schema ${A} must be string`)}return w=(0,wN.normalizeId)(w||G),this._checkUnique(w),this.schemas[w]=this._addSchema($,E,w,X,!0),this}addMetaSchema($,w,E=this.opts.validateSchema){return this.addSchema($,w,!0,E),this}validateSchema($,w){if(typeof $=="boolean")return!0;let E;if(E=$.$schema,E!==void 0&&typeof E!="string")throw Error("$schema must be a string");if(E=E||this.opts.defaultMeta||this.defaultMeta(),!E)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let X=this.validate(E,$);if(!X&&w){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return X}getSchema($){let w;while(typeof(w=EQ.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:E}=this.opts,X=new $N.SchemaEnv({schema:{},schemaId:E});if(w=$N.resolveSchema.call(this,X,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=EQ.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let E=$[this.opts.schemaId];if(E)E=(0,wN.normalizeId)(E),delete this.schemas[E],delete this.refs[E];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let E;if(typeof $=="string"){if(E=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=E}else if(typeof $=="object"&&w===void 0){if(w=$,E=w.keyword,Array.isArray(E)&&!E.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Zc.call(this,E,w),!w)return(0,O9.eachItem)(E,(G)=>D9.call(this,G)),this;fc.call(this,w);let X={...w,type:(0,WO.getJSONTypes)(w.type),schemaType:(0,WO.getJSONTypes)(w.schemaType)};return(0,O9.eachItem)(E,X.type.length===0?(G)=>D9.call(this,G,X):(G)=>X.type.forEach((A)=>D9.call(this,G,X,A))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let E of w.rules){let X=E.rules.findIndex((G)=>G.keyword===$);if(X>=0)E.rules.splice(X,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:E="data"}={}){if(!$||$.length===0)return"No errors";return $.map((X)=>`${E}${X.instancePath} ${X.message}`).reduce((X,G)=>X+w+G)}$dataMetaSchema($,w){let E=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let X of w){let G=X.split("/").slice(1),A=$;for(let N of G)A=A[N];for(let N in E){let D=E[N];if(typeof D!="object")continue;let{$data:O}=D.definition,W=A[N];if(O&&W)A[N]=AQ(W)}}return $}_removeAllSchemas($,w){for(let E in $){let X=$[E];if(!w||w.test(E)){if(typeof X=="string")delete $[E];else if(X&&!X.meta)this._cache.delete(X.schema),delete $[E]}}}_addSchema($,w,E,X=this.opts.validateSchema,G=this.opts.addUsedSchema){let A,{schemaId:N}=this.opts;if(typeof $=="object")A=$[N];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let D=this._cache.get($);if(D!==void 0)return D;E=(0,wN.normalizeId)(A||E);let O=wN.getSchemaRefs.call(this,$,E);if(D=new $N.SchemaEnv({schema:$,schemaId:N,meta:w,baseId:E,localRefs:O}),this._cache.set(D.schema,D),G&&!E.startsWith("#")){if(E)this._checkUnique(E);this.refs[E]=D}if(X)this.validateSchema($,!0);return D}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else $N.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{$N.compileSchema.call(this,$)}finally{this.opts=w}}}JO.ValidationError=jc.default;JO.MissingRefError=XQ.default;bE.default=JO;function wQ($,w,E,X="error"){for(let G in $){let A=G;if(A in w)this.logger[X](`${E}: option ${G}. ${$[A]}`)}}function EQ($){return $=(0,wN.normalizeId)($),this.schemas[$]||this.refs[$]}function Vc(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function Pc(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function qc($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let E=$[w];if(!E.keyword)E.keyword=w;this.addKeyword(E)}}function Sc(){let $={...this.opts};for(let w of zc)delete $[w];return $}var kc={log(){},warn(){},error(){}};function bc($){if($===!1)return kc;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var _c=/^[a-z_$][a-z0-9_$:-]*$/i;function Zc($,w){let{RULES:E}=this;if((0,O9.eachItem)($,(X)=>{if(E.keywords[X])throw Error(`Keyword ${X} is already defined`);if(!_c.test(X))throw Error(`Keyword ${X} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function D9($,w,E){var X;let G=w===null||w===void 0?void 0:w.post;if(E&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:A}=this,N=G?A.post:A.rules.find(({type:O})=>O===E);if(!N)N={type:E,rules:[]},A.rules.push(N);if(A.keywords[$]=!0,!w)return;let D={keyword:$,definition:{...w,type:(0,WO.getJSONTypes)(w.type),schemaType:(0,WO.getJSONTypes)(w.schemaType)}};if(w.before)Cc.call(this,N,D,w.before);else N.rules.push(D);A.all[$]=D,(X=w.implements)===null||X===void 0||X.forEach((O)=>this.addKeyword(O))}function Cc($,w,E){let X=$.rules.findIndex((G)=>G.keyword===E);if(X>=0)$.rules.splice(X,0,w);else $.rules.push(w),this.logger.warn(`rule ${E} is not defined`)}function fc($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=AQ(w);$.validateSchema=this.compile(w,!0)}var vc={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function AQ($){return{anyOf:[$,vc]}}});var OQ=_((DQ)=>{Object.defineProperty(DQ,"__esModule",{value:!0});var gc={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};DQ.default=gc});var LQ=_((YQ)=>{Object.defineProperty(YQ,"__esModule",{value:!0});YQ.callRef=YQ.getValidate=void 0;var nc=sA(),WQ=Iw(),Ew=J0(),eX=qE(),JQ=GO(),UO=T0(),hc={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:E,it:X}=$,{baseId:G,schemaEnv:A,validateName:N,opts:D,self:O}=X,{root:W}=A;if((E==="#"||E==="#/")&&G===W.baseId)return Y();let J=JQ.resolveRef.call(O,W,G,E);if(J===void 0)throw new nc.default(X.opts.uriResolver,G,E);if(J instanceof JQ.SchemaEnv)return H(J);return L(J);function Y(){if(A===W)return YO($,N,A,A.$async);let F=w.scopeValue("root",{ref:W});return YO($,Ew._`${F}.validate`,W,W.$async)}function H(F){let j=UQ($,F);YO($,j,F,F.$async)}function L(F){let j=w.scopeValue("schema",D.code.source===!0?{ref:F,code:(0,Ew.stringify)(F)}:{ref:F}),M=w.name("valid"),R=$.subschema({schema:F,dataTypes:[],schemaPath:Ew.nil,topSchemaRef:j,errSchemaPath:E},M);$.mergeEvaluated(R),$.ok(M)}}};function UQ($,w){let{gen:E}=$;return w.validate?E.scopeValue("validate",{ref:w.validate}):Ew._`${E.scopeValue("wrapper",{ref:w})}.validate`}YQ.getValidate=UQ;function YO($,w,E,X){let{gen:G,it:A}=$,{allErrors:N,schemaEnv:D,opts:O}=A,W=O.passContext?eX.default.this:Ew.nil;if(X)J();else Y();function J(){if(!D.$async)throw Error("async schema referenced by sync schema");let F=G.let("valid");G.try(()=>{if(G.code(Ew._`await ${(0,WQ.callValidateCode)($,w,W)}`),L(w),!N)G.assign(F,!0)},(j)=>{if(G.if(Ew._`!(${j} instanceof ${A.ValidationError})`,()=>G.throw(j)),H(j),!N)G.assign(F,!1)}),$.ok(F)}function Y(){$.result((0,WQ.callValidateCode)($,w,W),()=>L(w),()=>H(w))}function H(F){let j=Ew._`${F}.errors`;G.assign(eX.default.vErrors,Ew._`${eX.default.vErrors} === null ? ${j} : ${eX.default.vErrors}.concat(${j})`),G.assign(eX.default.errors,Ew._`${eX.default.vErrors}.length`)}function L(F){var j;if(!A.opts.unevaluated)return;let M=(j=E===null||E===void 0?void 0:E.validate)===null||j===void 0?void 0:j.evaluated;if(A.props!==!0)if(M&&!M.dynamicProps){if(M.props!==void 0)A.props=UO.mergeEvaluated.props(G,M.props,A.props)}else{let R=G.var("props",Ew._`${F}.evaluated.props`);A.props=UO.mergeEvaluated.props(G,R,A.props,Ew.Name)}if(A.items!==!0)if(M&&!M.dynamicItems){if(M.items!==void 0)A.items=UO.mergeEvaluated.items(G,M.items,A.items)}else{let R=G.var("items",Ew._`${F}.evaluated.items`);A.items=UO.mergeEvaluated.items(G,R,A.items,Ew.Name)}}}YQ.callRef=YO;YQ.default=hc});var jQ=_((FQ)=>{Object.defineProperty(FQ,"__esModule",{value:!0});var tc=OQ(),oc=LQ(),mc=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",tc.default,oc.default];FQ.default=mc});var TQ=_((MQ)=>{Object.defineProperty(MQ,"__esModule",{value:!0});var HO=J0(),A1=HO.operators,LO={maximum:{okStr:"<=",ok:A1.LTE,fail:A1.GT},minimum:{okStr:">=",ok:A1.GTE,fail:A1.LT},exclusiveMaximum:{okStr:"<",ok:A1.LT,fail:A1.GTE},exclusiveMinimum:{okStr:">",ok:A1.GT,fail:A1.LTE}},pc={message:({keyword:$,schemaCode:w})=>HO.str`must be ${LO[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>HO._`{comparison: ${LO[$].okStr}, limit: ${w}}`},dc={keyword:Object.keys(LO),type:"number",schemaType:"number",$data:!0,error:pc,code($){let{keyword:w,data:E,schemaCode:X}=$;$.fail$data(HO._`${E} ${LO[w].fail} ${X} || isNaN(${E})`)}};MQ.default=dc});var zQ=_((RQ)=>{Object.defineProperty(RQ,"__esModule",{value:!0});var EN=J0(),sc={message:({schemaCode:$})=>EN.str`must be multiple of ${$}`,params:({schemaCode:$})=>EN._`{multipleOf: ${$}}`},ac={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:sc,code($){let{gen:w,data:E,schemaCode:X,it:G}=$,A=G.opts.multipleOfPrecision,N=w.let("res"),D=A?EN._`Math.abs(Math.round(${N}) - ${N}) > 1e-${A}`:EN._`${N} !== parseInt(${N})`;$.fail$data(EN._`(${X} === 0 || (${N} = ${E}/${X}, ${D}))`)}};RQ.default=ac});var QQ=_((IQ)=>{Object.defineProperty(IQ,"__esModule",{value:!0});function BQ($){let w=$.length,E=0,X=0,G;while(X<w)if(E++,G=$.charCodeAt(X++),G>=55296&&G<=56319&&X<w){if(G=$.charCodeAt(X),(G&64512)===56320)X++}return E}IQ.default=BQ;BQ.code='require("ajv/dist/runtime/ucs2length").default'});var VQ=_((KQ)=>{Object.defineProperty(KQ,"__esModule",{value:!0});var v1=J0(),wr=T0(),Er=QQ(),Xr={message({keyword:$,schemaCode:w}){let E=$==="maxLength"?"more":"fewer";return v1.str`must NOT have ${E} than ${w} characters`},params:({schemaCode:$})=>v1._`{limit: ${$}}`},Gr={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Xr,code($){let{keyword:w,data:E,schemaCode:X,it:G}=$,A=w==="maxLength"?v1.operators.GT:v1.operators.LT,N=G.opts.unicode===!1?v1._`${E}.length`:v1._`${(0,wr.useFunc)($.gen,Er.default)}(${E})`;$.fail$data(v1._`${N} ${A} ${X}`)}};KQ.default=Gr});var qQ=_((PQ)=>{Object.defineProperty(PQ,"__esModule",{value:!0});var Nr=Iw(),Dr=T0(),$G=J0(),Or={message:({schemaCode:$})=>$G.str`must match pattern "${$}"`,params:({schemaCode:$})=>$G._`{pattern: ${$}}`},Wr={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Or,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:A,it:N}=$,D=N.opts.unicodeRegExp?"u":"";if(X){let{regExp:O}=N.opts.code,W=O.code==="new RegExp"?$G._`new RegExp`:(0,Dr.useFunc)(w,O),J=w.let("valid");w.try(()=>w.assign(J,$G._`${W}(${A}, ${D}).test(${E})`),()=>w.assign(J,!1)),$.fail$data($G._`!${J}`)}else{let O=(0,Nr.usePattern)($,G);$.fail$data($G._`!${O}.test(${E})`)}}};PQ.default=Wr});var kQ=_((SQ)=>{Object.defineProperty(SQ,"__esModule",{value:!0});var XN=J0(),Ur={message({keyword:$,schemaCode:w}){let E=$==="maxProperties"?"more":"fewer";return XN.str`must NOT have ${E} than ${w} properties`},params:({schemaCode:$})=>XN._`{limit: ${$}}`},Yr={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ur,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxProperties"?XN.operators.GT:XN.operators.LT;$.fail$data(XN._`Object.keys(${E}).length ${G} ${X}`)}};SQ.default=Yr});var _Q=_((bQ)=>{Object.defineProperty(bQ,"__esModule",{value:!0});var GN=Iw(),AN=J0(),Lr=T0(),Fr={message:({params:{missingProperty:$}})=>AN.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>AN._`{missingProperty: ${$}}`},jr={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Fr,code($){let{gen:w,schema:E,schemaCode:X,data:G,$data:A,it:N}=$,{opts:D}=N;if(!A&&E.length===0)return;let O=E.length>=D.loopRequired;if(N.allErrors)W();else J();if(D.strictRequired){let L=$.parentSchema.properties,{definedProperties:F}=$.it;for(let j of E)if((L===null||L===void 0?void 0:L[j])===void 0&&!F.has(j)){let M=N.schemaEnv.baseId+N.errSchemaPath,R=`required property "${j}" is not defined at "${M}" (strictRequired)`;(0,Lr.checkStrictMode)(N,R,N.opts.strictRequired)}}function W(){if(O||A)$.block$data(AN.nil,Y);else for(let L of E)(0,GN.checkReportMissingProp)($,L)}function J(){let L=w.let("missing");if(O||A){let F=w.let("valid",!0);$.block$data(F,()=>H(L,F)),$.ok(F)}else w.if((0,GN.checkMissingProp)($,E,L)),(0,GN.reportMissingProp)($,L),w.else()}function Y(){w.forOf("prop",X,(L)=>{$.setParams({missingProperty:L}),w.if((0,GN.noPropertyInData)(w,G,L,D.ownProperties),()=>$.error())})}function H(L,F){$.setParams({missingProperty:L}),w.forOf(L,X,()=>{w.assign(F,(0,GN.propertyInData)(w,G,L,D.ownProperties)),w.if((0,AN.not)(F),()=>{$.error(),w.break()})},AN.nil)}}};bQ.default=jr});var CQ=_((ZQ)=>{Object.defineProperty(ZQ,"__esModule",{value:!0});var NN=J0(),Tr={message({keyword:$,schemaCode:w}){let E=$==="maxItems"?"more":"fewer";return NN.str`must NOT have ${E} than ${w} items`},params:({schemaCode:$})=>NN._`{limit: ${$}}`},Rr={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Tr,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxItems"?NN.operators.GT:NN.operators.LT;$.fail$data(NN._`${E}.length ${G} ${X}`)}};ZQ.default=Rr});var FO=_((vQ)=>{Object.defineProperty(vQ,"__esModule",{value:!0});var fQ=iU();fQ.code='require("ajv/dist/runtime/equal").default';vQ.default=fQ});var yQ=_((xQ)=>{Object.defineProperty(xQ,"__esModule",{value:!0});var W9=mA(),k$=J0(),Ir=T0(),Qr=FO(),Kr={message:({params:{i:$,j:w}})=>k$.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>k$._`{i: ${$}, j: ${w}}`},Vr={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Kr,code($){let{gen:w,data:E,$data:X,schema:G,parentSchema:A,schemaCode:N,it:D}=$;if(!X&&!G)return;let O=w.let("valid"),W=A.items?(0,W9.getSchemaTypes)(A.items):[];$.block$data(O,J,k$._`${N} === false`),$.ok(O);function J(){let F=w.let("i",k$._`${E}.length`),j=w.let("j");$.setParams({i:F,j}),w.assign(O,!0),w.if(k$._`${F} > 1`,()=>(Y()?H:L)(F,j))}function Y(){return W.length>0&&!W.some((F)=>F==="object"||F==="array")}function H(F,j){let M=w.name("item"),R=(0,W9.checkDataTypes)(W,M,D.opts.strictNumbers,W9.DataType.Wrong),B=w.const("indices",k$._`{}`);w.for(k$._`;${F}--;`,()=>{if(w.let(M,k$._`${E}[${F}]`),w.if(R,k$._`continue`),W.length>1)w.if(k$._`typeof ${M} == "string"`,k$._`${M} += "_"`);w.if(k$._`typeof ${B}[${M}] == "number"`,()=>{w.assign(j,k$._`${B}[${M}]`),$.error(),w.assign(O,!1).break()}).code(k$._`${B}[${M}] = ${F}`)})}function L(F,j){let M=(0,Ir.useFunc)(w,Qr.default),R=w.name("outer");w.label(R).for(k$._`;${F}--;`,()=>w.for(k$._`${j} = ${F}; ${j}--;`,()=>w.if(k$._`${M}(${E}[${F}], ${E}[${j}])`,()=>{$.error(),w.assign(O,!1).break(R)})))}}};xQ.default=Vr});var uQ=_((gQ)=>{Object.defineProperty(gQ,"__esModule",{value:!0});var J9=J0(),qr=T0(),Sr=FO(),kr={message:"must be equal to constant",params:({schemaCode:$})=>J9._`{allowedValue: ${$}}`},br={keyword:"const",$data:!0,error:kr,code($){let{gen:w,data:E,$data:X,schemaCode:G,schema:A}=$;if(X||A&&typeof A=="object")$.fail$data(J9._`!${(0,qr.useFunc)(w,Sr.default)}(${E}, ${G})`);else $.fail(J9._`${A} !== ${E}`)}};gQ.default=br});var hQ=_((nQ)=>{Object.defineProperty(nQ,"__esModule",{value:!0});var DN=J0(),Zr=T0(),Cr=FO(),fr={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>DN._`{allowedValues: ${$}}`},vr={keyword:"enum",schemaType:"array",$data:!0,error:fr,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:A,it:N}=$;if(!X&&G.length===0)throw Error("enum must have non-empty array");let D=G.length>=N.opts.loopEnum,O,W=()=>O!==null&&O!==void 0?O:O=(0,Zr.useFunc)(w,Cr.default),J;if(D||X)J=w.let("valid"),$.block$data(J,Y);else{if(!Array.isArray(G))throw Error("ajv implementation error");let L=w.const("vSchema",A);J=(0,DN.or)(...G.map((F,j)=>H(L,j)))}$.pass(J);function Y(){w.assign(J,!1),w.forOf("v",A,(L)=>w.if(DN._`${W()}(${E}, ${L})`,()=>w.assign(J,!0).break()))}function H(L,F){let j=G[F];return typeof j==="object"&&j!==null?DN._`${W()}(${E}, ${L}[${F}])`:DN._`${E} === ${j}`}}};nQ.default=vr});var rQ=_((cQ)=>{Object.defineProperty(cQ,"__esModule",{value:!0});var yr=TQ(),gr=zQ(),ur=VQ(),nr=qQ(),hr=kQ(),cr=_Q(),rr=CQ(),tr=yQ(),or=uQ(),mr=hQ(),ir=[yr.default,gr.default,ur.default,nr.default,hr.default,cr.default,rr.default,tr.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},or.default,mr.default];cQ.default=ir});var Y9=_((oQ)=>{Object.defineProperty(oQ,"__esModule",{value:!0});oQ.validateAdditionalItems=void 0;var x1=J0(),U9=T0(),dr={message:({params:{len:$}})=>x1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>x1._`{limit: ${$}}`},lr={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dr,code($){let{parentSchema:w,it:E}=$,{items:X}=w;if(!Array.isArray(X)){(0,U9.checkStrictMode)(E,'"additionalItems" is ignored when "items" is not an array of schemas');return}tQ($,X)}};function tQ($,w){let{gen:E,schema:X,data:G,keyword:A,it:N}=$;N.items=!0;let D=E.const("len",x1._`${G}.length`);if(X===!1)$.setParams({len:w.length}),$.pass(x1._`${D} <= ${w.length}`);else if(typeof X=="object"&&!(0,U9.alwaysValidSchema)(N,X)){let W=E.var("valid",x1._`${D} <= ${w.length}`);E.if((0,x1.not)(W),()=>O(W)),$.ok(W)}function O(W){E.forRange("i",w.length,D,(J)=>{if($.subschema({keyword:A,dataProp:J,dataPropType:U9.Type.Num},W),!N.allErrors)E.if((0,x1.not)(W),()=>E.break())})}}oQ.validateAdditionalItems=tQ;oQ.default=lr});var H9=_((dQ)=>{Object.defineProperty(dQ,"__esModule",{value:!0});dQ.validateTuple=void 0;var iQ=J0(),jO=T0(),ar=Iw(),er={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:E}=$;if(Array.isArray(w))return pQ($,"additionalItems",w);if(E.items=!0,(0,jO.alwaysValidSchema)(E,w))return;$.ok((0,ar.validateArray)($))}};function pQ($,w,E=$.schema){let{gen:X,parentSchema:G,data:A,keyword:N,it:D}=$;if(J(G),D.opts.unevaluated&&E.length&&D.items!==!0)D.items=jO.mergeEvaluated.items(X,E.length,D.items);let O=X.name("valid"),W=X.const("len",iQ._`${A}.length`);E.forEach((Y,H)=>{if((0,jO.alwaysValidSchema)(D,Y))return;X.if(iQ._`${W} > ${H}`,()=>$.subschema({keyword:N,schemaProp:H,dataProp:H},O)),$.ok(O)});function J(Y){let{opts:H,errSchemaPath:L}=D,F=E.length,j=F===Y.minItems&&(F===Y.maxItems||Y[w]===!1);if(H.strictTuples&&!j){let M=`"${N}" is ${F}-tuple, but minItems or maxItems/${w} are not specified or different at path "${L}"`;(0,jO.checkStrictMode)(D,M,H.strictTuples)}}}dQ.validateTuple=pQ;dQ.default=er});var aQ=_((sQ)=>{Object.defineProperty(sQ,"__esModule",{value:!0});var wt=H9(),Et={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,wt.validateTuple)($,"items")};sQ.default=Et});var wK=_(($K)=>{Object.defineProperty($K,"__esModule",{value:!0});var eQ=J0(),Gt=T0(),At=Iw(),Nt=Y9(),Dt={message:({params:{len:$}})=>eQ.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>eQ._`{limit: ${$}}`},Ot={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Dt,code($){let{schema:w,parentSchema:E,it:X}=$,{prefixItems:G}=E;if(X.items=!0,(0,Gt.alwaysValidSchema)(X,w))return;if(G)(0,Nt.validateAdditionalItems)($,G);else $.ok((0,At.validateArray)($))}};$K.default=Ot});var XK=_((EK)=>{Object.defineProperty(EK,"__esModule",{value:!0});var Qw=J0(),MO=T0(),Jt={message:({params:{min:$,max:w}})=>w===void 0?Qw.str`must contain at least ${$} valid item(s)`:Qw.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?Qw._`{minContains: ${$}}`:Qw._`{minContains: ${$}, maxContains: ${w}}`},Ut={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Jt,code($){let{gen:w,schema:E,parentSchema:X,data:G,it:A}=$,N,D,{minContains:O,maxContains:W}=X;if(A.opts.next)N=O===void 0?1:O,D=W;else N=1;let J=w.const("len",Qw._`${G}.length`);if($.setParams({min:N,max:D}),D===void 0&&N===0){(0,MO.checkStrictMode)(A,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(D!==void 0&&N>D){(0,MO.checkStrictMode)(A,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,MO.alwaysValidSchema)(A,E)){let j=Qw._`${J} >= ${N}`;if(D!==void 0)j=Qw._`${j} && ${J} <= ${D}`;$.pass(j);return}A.items=!0;let Y=w.name("valid");if(D===void 0&&N===1)L(Y,()=>w.if(Y,()=>w.break()));else if(N===0){if(w.let(Y,!0),D!==void 0)w.if(Qw._`${G}.length > 0`,H)}else w.let(Y,!1),H();$.result(Y,()=>$.reset());function H(){let j=w.name("_valid"),M=w.let("count",0);L(j,()=>w.if(j,()=>F(M)))}function L(j,M){w.forRange("i",0,J,(R)=>{$.subschema({keyword:"contains",dataProp:R,dataPropType:MO.Type.Num,compositeRule:!0},j),M()})}function F(j){if(w.code(Qw._`${j}++`),D===void 0)w.if(Qw._`${j} >= ${N}`,()=>w.assign(Y,!0).break());else if(w.if(Qw._`${j} > ${D}`,()=>w.assign(Y,!1).break()),N===1)w.assign(Y,!0);else w.if(Qw._`${j} >= ${N}`,()=>w.assign(Y,!0))}}};EK.default=Ut});var WK=_((NK)=>{Object.defineProperty(NK,"__esModule",{value:!0});NK.validateSchemaDeps=NK.validatePropertyDeps=NK.error=void 0;var L9=J0(),Ht=T0(),ON=Iw();NK.error={message:({params:{property:$,depsCount:w,deps:E}})=>{let X=w===1?"property":"properties";return L9.str`must have ${X} ${E} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:E,missingProperty:X}})=>L9._`{property: ${$},
575
559
  missingProperty: ${X},
576
560
  depsCount: ${w},
577
- deps: ${E}}`};var $r={keyword:"dependencies",type:"object",schemaType:"object",error:aI.error,code($){let[w,E]=wr($);lI($,w),sI($,E)}};function wr({schema:$}){let w={},E={};for(let X in $){if(X==="__proto__")continue;let G=Array.isArray($[X])?w:E;G[X]=$[X]}return[w,E]}function lI($,w=$.schema){let{gen:E,data:X,it:G}=$;if(Object.keys(w).length===0)return;let J=E.let("missing");for(let A in w){let D=w[A];if(D.length===0)continue;let N=(0,GJ.propertyInData)(E,X,A,G.opts.ownProperties);if($.setParams({property:A,depsCount:D.length,deps:D.join(", ")}),G.allErrors)E.if(N,()=>{for(let W of D)(0,GJ.checkReportMissingProp)($,W)});else E.if(DO._`${N} && (${(0,GJ.checkMissingProp)($,D,J)})`),(0,GJ.reportMissingProp)($,J),E.else()}}aI.validatePropertyDeps=lI;function sI($,w=$.schema){let{gen:E,data:X,keyword:G,it:J}=$,A=E.name("valid");for(let D in w){if((0,em.alwaysValidSchema)(J,w[D]))continue;E.if((0,GJ.propertyInData)(E,X,D,J.opts.ownProperties),()=>{let N=$.subschema({keyword:G,schemaProp:D},A);$.mergeValidEvaluated(N,A)},()=>E.var(A,!0)),$.ok(A)}}aI.validateSchemaDeps=sI;aI.default=$r});var GK=Z((XK)=>{Object.defineProperty(XK,"__esModule",{value:!0});var EK=W0(),Gr=R0(),Jr={message:"property name must be valid",params:({params:$})=>EK._`{propertyName: ${$.propertyName}}`},Ar={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Jr,code($){let{gen:w,schema:E,data:X,it:G}=$;if((0,Gr.alwaysValidSchema)(G,E))return;let J=w.name("valid");w.forIn("key",X,(A)=>{$.setParams({propertyName:A}),$.subschema({keyword:"propertyNames",data:A,dataTypes:["string"],propertyName:A,compositeRule:!0},J),w.if((0,EK.not)(J),()=>{if($.error(!0),!G.allErrors)w.break()})}),$.ok(J)}};XK.default=Ar});var NO=Z((JK)=>{Object.defineProperty(JK,"__esModule",{value:!0});var FD=I1(),r1=W0(),Nr=qw(),jD=R0(),Wr={message:"must NOT have additional properties",params:({params:$})=>r1._`{additionalProperty: ${$.additionalProperty}}`},Or={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Wr,code($){let{gen:w,schema:E,parentSchema:X,data:G,errsCount:J,it:A}=$;if(!J)throw Error("ajv implementation error");let{allErrors:D,opts:N}=A;if(A.props=!0,N.removeAdditional!=="all"&&(0,jD.alwaysValidSchema)(A,E))return;let W=(0,FD.allSchemaProperties)(X.properties),O=(0,FD.allSchemaProperties)(X.patternProperties);Y(),$.ok(r1._`${J} === ${Nr.default.errors}`);function Y(){w.forIn("key",G,(M)=>{if(!W.length&&!O.length)F(M);else w.if(H(M),()=>F(M))})}function H(M){let z;if(W.length>8){let B=(0,jD.schemaRefOrVal)(A,X.properties,"properties");z=(0,FD.isOwnProperty)(w,B,M)}else if(W.length)z=(0,r1.or)(...W.map((B)=>r1._`${M} === ${B}`));else z=r1.nil;if(O.length)z=(0,r1.or)(z,...O.map((B)=>r1._`${(0,FD.usePattern)($,B)}.test(${M})`));return(0,r1.not)(z)}function L(M){w.code(r1._`delete ${G}[${M}]`)}function F(M){if(N.removeAdditional==="all"||N.removeAdditional&&E===!1){L(M);return}if(E===!1){if($.setParams({additionalProperty:M}),$.error(),!D)w.break();return}if(typeof E=="object"&&!(0,jD.alwaysValidSchema)(A,E)){let z=w.name("valid");if(N.removeAdditional==="failing")j(M,z,!1),w.if((0,r1.not)(z),()=>{$.reset(),L(M)});else if(j(M,z),!D)w.if((0,r1.not)(z),()=>w.break())}}function j(M,z,B){let Q={keyword:"additionalProperties",dataProp:M,dataPropType:jD.Type.Str};if(B===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(Q,z)}}};JK.default=Or});var WK=Z((NK)=>{Object.defineProperty(NK,"__esModule",{value:!0});var Yr=o6(),AK=I1(),WO=R0(),DK=NO(),Hr={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,parentSchema:X,data:G,it:J}=$;if(J.opts.removeAdditional==="all"&&X.additionalProperties===void 0)DK.default.code(new Yr.KeywordCxt(J,DK.default,"additionalProperties"));let A=(0,AK.allSchemaProperties)(E);for(let Y of A)J.definedProperties.add(Y);if(J.opts.unevaluated&&A.length&&J.props!==!0)J.props=WO.mergeEvaluated.props(w,(0,WO.toHash)(A),J.props);let D=A.filter((Y)=>!(0,WO.alwaysValidSchema)(J,E[Y]));if(D.length===0)return;let N=w.name("valid");for(let Y of D){if(W(Y))O(Y);else{if(w.if((0,AK.propertyInData)(w,G,Y,J.opts.ownProperties)),O(Y),!J.allErrors)w.else().var(N,!0);w.endIf()}$.it.definedProperties.add(Y),$.ok(N)}function W(Y){return J.opts.useDefaults&&!J.compositeRule&&E[Y].default!==void 0}function O(Y){$.subschema({keyword:"properties",schemaProp:Y,dataProp:Y},N)}}};NK.default=Hr});var LK=Z((HK)=>{Object.defineProperty(HK,"__esModule",{value:!0});var OK=I1(),MD=W0(),UK=R0(),YK=R0(),Fr={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,data:X,parentSchema:G,it:J}=$,{opts:A}=J,D=(0,OK.allSchemaProperties)(E),N=D.filter((j)=>(0,UK.alwaysValidSchema)(J,E[j]));if(D.length===0||N.length===D.length&&(!J.opts.unevaluated||J.props===!0))return;let W=A.strictSchema&&!A.allowMatchingProperties&&G.properties,O=w.name("valid");if(J.props!==!0&&!(J.props instanceof MD.Name))J.props=(0,YK.evaluatedPropsToName)(w,J.props);let{props:Y}=J;H();function H(){for(let j of D){if(W)L(j);if(J.allErrors)F(j);else w.var(O,!0),F(j),w.if(O)}}function L(j){for(let M in W)if(new RegExp(j).test(M))(0,UK.checkStrictMode)(J,`property ${M} matches pattern ${j} (use allowMatchingProperties)`)}function F(j){w.forIn("key",X,(M)=>{w.if(MD._`${(0,OK.usePattern)($,j)}.test(${M})`,()=>{let z=N.includes(j);if(!z)$.subschema({keyword:"patternProperties",schemaProp:j,dataProp:M,dataPropType:YK.Type.Str},O);if(J.opts.unevaluated&&Y!==!0)w.assign(MD._`${Y}[${M}]`,!0);else if(!z&&!J.allErrors)w.if((0,MD.not)(O),()=>w.break())})})}}};HK.default=Fr});var jK=Z((FK)=>{Object.defineProperty(FK,"__esModule",{value:!0});var Mr=R0(),Rr={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:E,it:X}=$;if((0,Mr.alwaysValidSchema)(X,E)){$.fail();return}let G=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),$.failResult(G,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};FK.default=Rr});var RK=Z((MK)=>{Object.defineProperty(MK,"__esModule",{value:!0});var Tr=I1(),Br={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Tr.validateUnion,error:{message:"must match a schema in anyOf"}};MK.default=Br});var TK=Z((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});var RD=W0(),Ir=R0(),Kr={message:"must match exactly one schema in oneOf",params:({params:$})=>RD._`{passingSchemas: ${$.passing}}`},Vr={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Kr,code($){let{gen:w,schema:E,parentSchema:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(G.opts.discriminator&&X.discriminator)return;let J=E,A=w.let("valid",!1),D=w.let("passing",null),N=w.name("_valid");$.setParams({passing:D}),w.block(W),$.result(A,()=>$.reset(),()=>$.error(!0));function W(){J.forEach((O,Y)=>{let H;if((0,Ir.alwaysValidSchema)(G,O))w.var(N,!0);else H=$.subschema({keyword:"oneOf",schemaProp:Y,compositeRule:!0},N);if(Y>0)w.if(RD._`${N} && ${A}`).assign(A,!1).assign(D,RD._`[${D}, ${Y}]`).else();w.if(N,()=>{if(w.assign(A,!0),w.assign(D,Y),H)$.mergeEvaluated(H,RD.Name)})})}}};zK.default=Vr});var QK=Z((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});var qr=R0(),Sr={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:E,it:X}=$;if(!Array.isArray(E))throw Error("ajv implementation error");let G=w.name("valid");E.forEach((J,A)=>{if((0,qr.alwaysValidSchema)(X,J))return;let D=$.subschema({keyword:"allOf",schemaProp:A},G);$.ok(G),$.mergeEvaluated(D)})}};BK.default=Sr});var PK=Z((VK)=>{Object.defineProperty(VK,"__esModule",{value:!0});var zD=W0(),KK=R0(),br={message:({params:$})=>zD.str`must match "${$.ifClause}" schema`,params:({params:$})=>zD._`{failingKeyword: ${$.ifClause}}`},Zr={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:br,code($){let{gen:w,parentSchema:E,it:X}=$;if(E.then===void 0&&E.else===void 0)(0,KK.checkStrictMode)(X,'"if" without "then" and "else" is ignored');let G=IK(X,"then"),J=IK(X,"else");if(!G&&!J)return;let A=w.let("valid",!0),D=w.name("_valid");if(N(),$.reset(),G&&J){let O=w.let("ifClause");$.setParams({ifClause:O}),w.if(D,W("then",O),W("else",O))}else if(G)w.if(D,W("then"));else w.if((0,zD.not)(D),W("else"));$.pass(A,()=>$.error(!0));function N(){let O=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},D);$.mergeEvaluated(O)}function W(O,Y){return()=>{let H=$.subschema({keyword:O},D);if(w.assign(A,D),$.mergeValidEvaluated(H,A),Y)w.assign(Y,zD._`${O}`);else $.setParams({ifClause:O})}}}};function IK($,w){let E=$.schema[w];return E!==void 0&&!(0,KK.alwaysValidSchema)($,E)}VK.default=Zr});var SK=Z((qK)=>{Object.defineProperty(qK,"__esModule",{value:!0});var _r=R0(),vr={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:E}){if(w.if===void 0)(0,_r.checkStrictMode)(E,`"${$}" without "if" is ignored`)}};qK.default=vr});var bK=Z((kK)=>{Object.defineProperty(kK,"__esModule",{value:!0});var xr=JO(),yr=rI(),gr=AO(),ur=tI(),hr=dI(),cr=wK(),nr=GK(),mr=NO(),rr=WK(),pr=LK(),or=jK(),tr=RK(),ir=TK(),dr=QK(),lr=PK(),sr=SK();function ar($=!1){let w=[or.default,tr.default,ir.default,dr.default,lr.default,sr.default,nr.default,mr.default,cr.default,rr.default,pr.default];if($)w.push(yr.default,ur.default);else w.push(xr.default,gr.default);return w.push(hr.default),w}kK.default=ar});var CK=Z((ZK)=>{Object.defineProperty(ZK,"__esModule",{value:!0});var J$=W0(),$p={message:({schemaCode:$})=>J$.str`must match format "${$}"`,params:({schemaCode:$})=>J$._`{format: ${$}}`},wp={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$p,code($,w){let{gen:E,data:X,$data:G,schema:J,schemaCode:A,it:D}=$,{opts:N,errSchemaPath:W,schemaEnv:O,self:Y}=D;if(!N.validateFormats)return;if(G)H();else L();function H(){let F=E.scopeValue("formats",{ref:Y.formats,code:N.code.formats}),j=E.const("fDef",J$._`${F}[${A}]`),M=E.let("fType"),z=E.let("format");E.if(J$._`typeof ${j} == "object" && !(${j} instanceof RegExp)`,()=>E.assign(M,J$._`${j}.type || "string"`).assign(z,J$._`${j}.validate`),()=>E.assign(M,J$._`"string"`).assign(z,j)),$.fail$data((0,J$.or)(B(),Q()));function B(){if(N.strictSchema===!1)return J$.nil;return J$._`${A} && !${z}`}function Q(){let k=O.$async?J$._`(${j}.async ? await ${z}(${X}) : ${z}(${X}))`:J$._`${z}(${X})`,v=J$._`(typeof ${z} == "function" ? ${k} : ${z}.test(${X}))`;return J$._`${z} && ${z} !== true && ${M} === ${w} && !${v}`}}function L(){let F=Y.formats[J];if(!F){B();return}if(F===!0)return;let[j,M,z]=Q(F);if(j===w)$.pass(k());function B(){if(N.strictSchema===!1){Y.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${J}" ignored in schema at path "${W}"`}}function Q(v){let C=v instanceof RegExp?(0,J$.regexpCode)(v):N.code.formats?J$._`${N.code.formats}${(0,J$.getProperty)(J)}`:void 0,n=E.scopeValue("formats",{key:J,ref:v,code:C});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,J$._`${n}.validate`];return["string",v,n]}function k(){if(typeof F=="object"&&!(F instanceof RegExp)&&F.async){if(!O.$async)throw Error("async format in sync schema");return J$._`await ${z}(${X})`}return typeof M=="function"?J$._`${z}(${X})`:J$._`${z}.test(${X})`}}}};ZK.default=wp});var vK=Z((_K)=>{Object.defineProperty(_K,"__esModule",{value:!0});var Xp=CK(),Gp=[Xp.default];_K.default=Gp});var yK=Z((fK)=>{Object.defineProperty(fK,"__esModule",{value:!0});fK.contentVocabulary=fK.metadataVocabulary=void 0;fK.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fK.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hK=Z((uK)=>{Object.defineProperty(uK,"__esModule",{value:!0});var Dp=NI(),Np=fI(),Wp=bK(),Op=vK(),gK=yK(),Up=[Dp.default,Np.default,(0,Wp.default)(),Op.default,gK.metadataVocabulary,gK.contentVocabulary];uK.default=Up});var rK=Z((nK)=>{Object.defineProperty(nK,"__esModule",{value:!0});nK.DiscrError=void 0;var cK;(function($){$.Tag="tag",$.Mapping="mapping"})(cK||(nK.DiscrError=cK={}))});var tK=Z((oK)=>{Object.defineProperty(oK,"__esModule",{value:!0});var sX=W0(),OO=rK(),pK=wD(),Hp=t6(),Lp=R0(),Fp={message:({params:{discrError:$,tagName:w}})=>$===OO.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:E}})=>sX._`{error: ${$}, tag: ${E}, tagValue: ${w}}`},jp={keyword:"discriminator",type:"object",schemaType:"object",error:Fp,code($){let{gen:w,data:E,schema:X,parentSchema:G,it:J}=$,{oneOf:A}=G;if(!J.opts.discriminator)throw Error("discriminator: requires discriminator option");let D=X.propertyName;if(typeof D!="string")throw Error("discriminator: requires propertyName");if(X.mapping)throw Error("discriminator: mapping is not supported");if(!A)throw Error("discriminator: requires oneOf keyword");let N=w.let("valid",!1),W=w.const("tag",sX._`${E}${(0,sX.getProperty)(D)}`);w.if(sX._`typeof ${W} == "string"`,()=>O(),()=>$.error(!1,{discrError:OO.DiscrError.Tag,tag:W,tagName:D})),$.ok(N);function O(){let L=H();w.if(!1);for(let F in L)w.elseIf(sX._`${W} === ${F}`),w.assign(N,Y(L[F]));w.else(),$.error(!1,{discrError:OO.DiscrError.Mapping,tag:W,tagName:D}),w.endIf()}function Y(L){let F=w.name("valid"),j=$.subschema({keyword:"oneOf",schemaProp:L},F);return $.mergeEvaluated(j,sX.Name),F}function H(){var L;let F={},j=z(G),M=!0;for(let k=0;k<A.length;k++){let v=A[k];if((v===null||v===void 0?void 0:v.$ref)&&!(0,Lp.schemaHasRulesButRef)(v,J.self.RULES)){let n=v.$ref;if(v=pK.resolveRef.call(J.self,J.schemaEnv.root,J.baseId,n),v instanceof pK.SchemaEnv)v=v.schema;if(v===void 0)throw new Hp.default(J.opts.uriResolver,J.baseId,n)}let C=(L=v===null||v===void 0?void 0:v.properties)===null||L===void 0?void 0:L[D];if(typeof C!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${D}"`);M=M&&(j||z(v)),B(C,k)}if(!M)throw Error(`discriminator: "${D}" must be required`);return F;function z({required:k}){return Array.isArray(k)&&k.includes(D)}function B(k,v){if(k.const)Q(k.const,v);else if(k.enum)for(let C of k.enum)Q(C,v);else throw Error(`discriminator: "properties/${D}" must have "const" or "enum"`)}function Q(k,v){if(typeof k!="string"||k in F)throw Error(`discriminator: "${D}" values must be unique strings`);F[k]=v}}}};oK.default=jp});var iK=Z((rN0,Rp)=>{Rp.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var YO=Z((E1,UO)=>{Object.defineProperty(E1,"__esModule",{value:!0});E1.MissingRefError=E1.ValidationError=E1.CodeGen=E1.Name=E1.nil=E1.stringify=E1.str=E1._=E1.KeywordCxt=E1.Ajv=void 0;var zp=aQ(),Tp=hK(),Bp=tK(),dK=iK(),Qp=["/properties"],TD="http://json-schema.org/draft-07/schema";class JJ extends zp.default{_addVocabularies(){if(super._addVocabularies(),Tp.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(Bp.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(dK,Qp):dK;this.addMetaSchema($,TD,!1),this.refs["http://json-schema.org/schema"]=TD}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(TD)?TD:void 0)}}E1.Ajv=JJ;UO.exports=E1=JJ;UO.exports.Ajv=JJ;Object.defineProperty(E1,"__esModule",{value:!0});E1.default=JJ;var Ip=o6();Object.defineProperty(E1,"KeywordCxt",{enumerable:!0,get:function(){return Ip.KeywordCxt}});var aX=W0();Object.defineProperty(E1,"_",{enumerable:!0,get:function(){return aX._}});Object.defineProperty(E1,"str",{enumerable:!0,get:function(){return aX.str}});Object.defineProperty(E1,"stringify",{enumerable:!0,get:function(){return aX.stringify}});Object.defineProperty(E1,"nil",{enumerable:!0,get:function(){return aX.nil}});Object.defineProperty(E1,"Name",{enumerable:!0,get:function(){return aX.Name}});Object.defineProperty(E1,"CodeGen",{enumerable:!0,get:function(){return aX.CodeGen}});var Kp=e4();Object.defineProperty(E1,"ValidationError",{enumerable:!0,get:function(){return Kp.default}});var Vp=t6();Object.defineProperty(E1,"MissingRefError",{enumerable:!0,get:function(){return Vp.default}})});var JV=Z((XV)=>{Object.defineProperty(XV,"__esModule",{value:!0});XV.formatNames=XV.fastFormats=XV.fullFormats=void 0;function Nw($,w){return{validate:$,compare:w}}XV.fullFormats={date:Nw(eK,jO),time:Nw(LO(!0),MO),"date-time":Nw(lK(!0),wV),"iso-time":Nw(LO(),$V),"iso-date-time":Nw(lK(),EV),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_p,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:hp,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:vp,int32:{type:"number",validate:yp},int64:{type:"number",validate:gp},float:{type:"number",validate:aK},double:{type:"number",validate:aK},password:!0,binary:!0};XV.fastFormats={...XV.fullFormats,date:Nw(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,jO),time:Nw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,MO),"date-time":Nw(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wV),"iso-time":Nw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,$V),"iso-date-time":Nw(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,EV),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};XV.formatNames=Object.keys(XV.fullFormats);function Sp($){return $%4===0&&($%100!==0||$%400===0)}var kp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bp=[0,31,28,31,30,31,30,31,31,30,31,30,31];function eK($){let w=kp.exec($);if(!w)return!1;let E=+w[1],X=+w[2],G=+w[3];return X>=1&&X<=12&&G>=1&&G<=(X===2&&Sp(E)?29:bp[X])}function jO($,w){if(!($&&w))return;if($>w)return 1;if($<w)return-1;return 0}var HO=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function LO($){return function(E){let X=HO.exec(E);if(!X)return!1;let G=+X[1],J=+X[2],A=+X[3],D=X[4],N=X[5]==="-"?-1:1,W=+(X[6]||0),O=+(X[7]||0);if(W>23||O>59||$&&!D)return!1;if(G<=23&&J<=59&&A<60)return!0;let Y=J-O*N,H=G-W*N-(Y<0?1:0);return(H===23||H===-1)&&(Y===59||Y===-1)&&A<61}}function MO($,w){if(!($&&w))return;let E=new Date("2020-01-01T"+$).valueOf(),X=new Date("2020-01-01T"+w).valueOf();if(!(E&&X))return;return E-X}function $V($,w){if(!($&&w))return;let E=HO.exec($),X=HO.exec(w);if(!(E&&X))return;if($=E[1]+E[2]+E[3],w=X[1]+X[2]+X[3],$>w)return 1;if($<w)return-1;return 0}var FO=/t|\s/i;function lK($){let w=LO($);return function(X){let G=X.split(FO);return G.length===2&&eK(G[0])&&w(G[1])}}function wV($,w){if(!($&&w))return;let E=new Date($).valueOf(),X=new Date(w).valueOf();if(!(E&&X))return;return E-X}function EV($,w){if(!($&&w))return;let[E,X]=$.split(FO),[G,J]=w.split(FO),A=jO(E,G);if(A===void 0)return;return A||MO(X,J)}var Zp=/\/|:/,Cp=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _p($){return Zp.test($)&&Cp.test($)}var sK=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function vp($){return sK.lastIndex=0,sK.test($)}var fp=-2147483648,xp=2147483647;function yp($){return Number.isInteger($)&&$<=xp&&$>=fp}function gp($){return Number.isInteger($)}function aK(){return!0}var up=/[^\\]\\Z/;function hp($){if(up.test($))return!1;try{return new RegExp($),!0}catch(w){return!1}}});var DV=Z((AV)=>{Object.defineProperty(AV,"__esModule",{value:!0});AV.formatLimitDefinition=void 0;var np=YO(),p1=W0(),JE=p1.operators,BD={formatMaximum:{okStr:"<=",ok:JE.LTE,fail:JE.GT},formatMinimum:{okStr:">=",ok:JE.GTE,fail:JE.LT},formatExclusiveMaximum:{okStr:"<",ok:JE.LT,fail:JE.GTE},formatExclusiveMinimum:{okStr:">",ok:JE.GT,fail:JE.LTE}},mp={message:({keyword:$,schemaCode:w})=>p1.str`should be ${BD[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>p1._`{comparison: ${BD[$].okStr}, limit: ${w}}`};AV.formatLimitDefinition={keyword:Object.keys(BD),type:"string",schemaType:"string",$data:!0,error:mp,code($){let{gen:w,data:E,schemaCode:X,keyword:G,it:J}=$,{opts:A,self:D}=J;if(!A.validateFormats)return;let N=new np.KeywordCxt(J,D.RULES.all.format.definition,"format");if(N.$data)W();else O();function W(){let H=w.scopeValue("formats",{ref:D.formats,code:A.code.formats}),L=w.const("fmt",p1._`${H}[${N.schemaCode}]`);$.fail$data((0,p1.or)(p1._`typeof ${L} != "object"`,p1._`${L} instanceof RegExp`,p1._`typeof ${L}.compare != "function"`,Y(L)))}function O(){let H=N.schema,L=D.formats[H];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${G}": format "${H}" does not define "compare" function`);let F=w.scopeValue("formats",{key:H,ref:L,code:A.code.formats?p1._`${A.code.formats}${(0,p1.getProperty)(H)}`:void 0});$.fail$data(Y(F))}function Y(H){return p1._`${H}.compare(${E}, ${X}) ${BD[G].fail} 0`}},dependencies:["format"]};var rp=($)=>{return $.addKeyword(AV.formatLimitDefinition),$};AV.default=rp});var UV=Z((AJ,OV)=>{Object.defineProperty(AJ,"__esModule",{value:!0});var eX=JV(),op=DV(),TO=W0(),NV=new TO.Name("fullFormats"),tp=new TO.Name("fastFormats"),BO=($,w={keywords:!0})=>{if(Array.isArray(w))return WV($,w,eX.fullFormats,NV),$;let[E,X]=w.mode==="fast"?[eX.fastFormats,tp]:[eX.fullFormats,NV],G=w.formats||eX.formatNames;if(WV($,G,E,X),w.keywords)(0,op.default)($);return $};BO.get=($,w="full")=>{let X=(w==="fast"?eX.fastFormats:eX.fullFormats)[$];if(!X)throw Error(`Unknown format "${$}"`);return X};function WV($,w,E,X){var G,J;(G=(J=$.opts.code).formats)!==null&&G!==void 0||(J.formats=TO._`require("ajv-formats/dist/formats").${X}`);for(let A of w)$.addFormat(A,E[A])}OV.exports=AJ=BO;Object.defineProperty(AJ,"__esModule",{value:!0});AJ.default=BO});function ip(){let $=new YV.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return HV.default($),$}class QO{constructor($){this._ajv=$??ip()}getValidator($){let w="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(E)=>{if(w(E))return{valid:!0,data:E,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}var YV,HV;var LV=R(()=>{YV=DJ(YO(),1),HV=DJ(UV(),1)});class IO{constructor($){this._server=$}requestStream($,w,E){return this._server.requestStream($,w,E)}createMessageStream($,w){let E=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!E?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let X=$.messages[$.messages.length-1],G=Array.isArray(X.content)?X.content:[X.content],J=G.some((W)=>W.type==="tool_result"),A=$.messages.length>1?$.messages[$.messages.length-2]:void 0,D=A?Array.isArray(A.content)?A.content:[A.content]:[],N=D.some((W)=>W.type==="tool_use");if(J){if(G.some((W)=>W.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!N)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(N){let W=new Set(D.filter((Y)=>Y.type==="tool_use").map((Y)=>Y.id)),O=new Set(G.filter((Y)=>Y.type==="tool_result").map((Y)=>Y.toolUseId));if(W.size!==O.size||![...W].every((Y)=>O.has(Y)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},x6,w)}elicitInputStream($,w){let E=this._server.getClientCapabilities(),X=$.mode??"form";switch(X){case"url":{if(!E?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!E?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let G=X==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:G},hX,w)}async getTask($,w){return this._server.getTask({taskId:$},w)}async getTaskResult($,w,E){return this._server.getTaskResult({taskId:$},w,E)}async listTasks($,w){return this._server.listTasks($?{cursor:$}:void 0,w)}async cancelTask($,w){return this._server.cancelTask({taskId:$},w)}}var FV=R(()=>{cX()});function jV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!$.tools?.call)throw Error(`${E} does not support task creation for tools/call (required for ${w})`);break;default:break}}function MV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${E} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${E} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}var KO;var RV=R(()=>{fT();cX();LV();M4();FV();KO=class KO extends RW{constructor($,w){super(w);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(f6.options.map((E,X)=>[E,X])),this.isMessageIgnored=(E,X)=>{let G=this._loggingLevels.get(X);return G?this.LOG_LEVEL_SEVERITY.get(E)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new QO,this.setRequestHandler(f5,(E)=>this._oninitialize(E)),this.setNotificationHandler(x5,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r5,async(E,X)=>{let G=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=E.params,A=f6.safeParse(J);if(A.success)this._loggingLevels.set(G,A.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new IO(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vT(this._capabilities,$)}setRequestHandler($,w){let X=j4($)?.method;if(!X)throw Error("Schema is missing a method literal");let G;if(xX(X)){let A=X;G=A._zod?.def?.value??A.value}else{let A=X;G=A._def?.value??A.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let A=async(D,N)=>{let W=lw(v6,D);if(!W.success){let L=W.error instanceof Error?W.error.message:String(W.error);throw new A0(L0.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:O}=W.data,Y=await Promise.resolve(w(D,N));if(O.task){let L=lw(gX,Y);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new A0(L0.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let H=lw(_4,Y);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new A0(L0.InvalidParams,`Invalid tools/call result: ${L}`)}return H.data};return super.setRequestHandler($,A)}return super.setRequestHandler($,w)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){MV(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;jV(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let w=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:HT.includes(w)?w:b5,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},I4)}async createMessage($,w){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let E=$.messages[$.messages.length-1],X=Array.isArray(E.content)?E.content:[E.content],G=X.some((N)=>N.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,A=J?Array.isArray(J.content)?J.content:[J.content]:[],D=A.some((N)=>N.type==="tool_use");if(G){if(X.some((N)=>N.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let N=new Set(A.filter((O)=>O.type==="tool_use").map((O)=>O.id)),W=new Set(X.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(N.size!==W.size||![...N].every((O)=>W.has(O)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},p5,w);return this.request({method:"sampling/createMessage",params:$},x6,w)}async elicitInput($,w){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},hX,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},G=await this.request({method:"elicitation/create",params:X},hX,w);if(G.action==="accept"&&G.content&&X.requestedSchema)try{let A=this._jsonSchemaValidator.getValidator(X.requestedSchema)(G.content);if(!A.valid)throw new A0(L0.InvalidParams,`Elicitation response content does not match requested schema: ${A.errorMessage}`)}catch(J){if(J instanceof A0)throw J;throw new A0(L0.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return G}}}createElicitationCompletionNotifier($,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:$}},w)}async listRoots($,w){return this.request({method:"roots/list",params:$},o5,w)}async sendLoggingMessage($,w){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,w))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});class VO{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
578
- `);if($===-1)return null;let w=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),dp(w)}clear(){this._buffer=void 0}}function dp($){return BT.parse(JSON.parse($))}function zV($){return JSON.stringify($)+`
579
- `}var TV=R(()=>{cX()});import BV from"process";class PO{constructor($=BV.stdin,w=BV.stdout){this._stdin=$,this._stdout=w,this._readBuffer=new VO,this._started=!1,this._ondata=(E)=>{this._readBuffer.append(E),this.processReadBuffer()},this._onerror=(E)=>{this.onerror?.(E)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((w)=>{let E=zV($);if(this._stdout.write(E))w();else this._stdout.once("drain",w)})}}var QV=R(()=>{TV()});function $G($){let w=$._def,E=w.typeName;if(E==="ZodObject"){let X=w.shape(),G={},J=[];for(let[A,D]of Object.entries(X)){G[A]=$G(D);let N=D._def;if(N.typeName!=="ZodOptional"&&N.typeName!=="ZodDefault")J.push(A)}return{type:"object",properties:G,...J.length?{required:J}:{}}}if(E==="ZodString")return{type:"string"};if(E==="ZodNumber")return{type:"number"};if(E==="ZodBoolean")return{type:"boolean"};if(E==="ZodArray")return{type:"array",items:$G(w.type)};if(E==="ZodEnum")return{type:"string",enum:w.values};if(E==="ZodOptional"||E==="ZodDefault")return $G(w.innerType);if(E==="ZodUnion")return{oneOf:w.options.map($G)};return{}}function IV(){let $=new KO({name:"orc",version:"0.0.1"},{capabilities:{tools:{}}});return $.setRequestHandler(m5,async()=>({tools:qX.map((w)=>({name:w.name,description:w.description,inputSchema:$G(w.inputSchema)}))})),$.setRequestHandler(v6,async(w)=>{let{name:E,arguments:X}=w.params;qO.debug(`Tool call: ${E}`,X);try{let G=qX.find((D)=>D.name===E);if(!G)return{content:[{type:"text",text:`Unknown tool: ${E}`}],isError:!0};let J=G.inputSchema.safeParse(X??{});if(!J.success)return{content:[{type:"text",text:`Invalid args: ${J.error.message}`}],isError:!0};return{content:[{type:"text",text:await D6(E,J.data)}]}}catch(G){return qO.error(`Tool error: ${E}`,G),{content:[{type:"text",text:G instanceof Error?G.message:"Unknown error"}],isError:!0}}}),$}async function lp(){let $=IV(),w=new PO;await $.connect(w),qO.info("MCP server running on stdio")}var qO;var KV=R(()=>{RV();QV();cX();p$();oA();qO=Z0("mcp")});var VV={};Ww(VV,{toolDefinitions:()=>qX,startStdioServer:()=>lp,executeTool:()=>D6,createMcpServer:()=>IV});var PV=R(async()=>{KV();oA()});C$();FJ();import{existsSync as sp,statSync as ap}from"fs";var HU=DJ(YU(),1),{program:no,createCommand:mo,createArgument:ro,createOption:po,CommanderError:oo,InvalidArgumentError:to,InvalidOptionArgumentError:io,Command:$$,Argument:lo,Option:so,Help:ao}=HU.default;C$();bN();import{mkdirSync as Gv,readFileSync as Jv,writeFileSync as Av}from"fs";import{homedir as Dv}from"os";import{join as eA}from"path";nw();p$();y$();d$();function k$($,w,E,X,G,J,A,D){return k$.fromTZ(k$.tp($,w,E,X,G,J,A),D)}k$.fromTZISO=($,w,E)=>k$.fromTZ(eb($,w),E);k$.fromTZ=function($,w){let E=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),X=ZN($.tz,E),G=new Date(E.getTime()-X),J=ZN($.tz,G);if(J-X===0)return G;{let A=new Date(E.getTime()-J),D=ZN($.tz,A);if(D-J===0)return A;if(!w&&D-J>0)return A;if(w)throw Error("Invalid date passed to fromTZ()");return G}};k$.toTZ=function($,w){let E=$.toLocaleString("en-US",{timeZone:w}).replace(/[\u202f]/," "),X=new Date(E);return{y:X.getFullYear(),m:X.getMonth()+1,d:X.getDate(),h:X.getHours(),i:X.getMinutes(),s:X.getSeconds(),tz:w}};k$.tp=($,w,E,X,G,J,A)=>({y:$,m:w,d:E,h:X,i:G,s:J,tz:A});function ZN($,w=new Date){let E=w.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],X=w.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${X} GMT`)-Date.parse(`${X} ${E}`)}function eb($,w){let E=new Date(Date.parse($));if(isNaN(E))throw Error("minitz: Invalid ISO8601 passed to parser.");let X=$.substring(9);return $.includes("Z")||X.includes("-")||X.includes("+")?k$.tp(E.getUTCFullYear(),E.getUTCMonth()+1,E.getUTCDate(),E.getUTCHours(),E.getUTCMinutes(),E.getUTCSeconds(),"Etc/UTC"):k$.tp(E.getFullYear(),E.getMonth()+1,E.getDate(),E.getHours(),E.getMinutes(),E.getSeconds(),w)}k$.minitz=k$;var CN=32,nG=31|CN,nL=[1,2,4,8,16],uL=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor($,w){this.pattern=$,this.timezone=w,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let $=this.pattern.replace(/\s+/g," ").split(" ");if($.length<5||$.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if($.length===5&&$.unshift("0"),$[3].indexOf("L")>=0&&($[3]=$[3].replace("L",""),this.lastDayOfMonth=!0),$[3]=="*"&&(this.starDOM=!0),$[4].length>=3&&($[4]=this.replaceAlphaMonths($[4])),$[5].length>=3&&($[5]=this.replaceAlphaDays($[5])),$[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let w=new F1(new Date,this.timezone).getDate(!0);$[0]=$[0].replace("?",w.getSeconds().toString()),$[1]=$[1].replace("?",w.getMinutes().toString()),$[2]=$[2].replace("?",w.getHours().toString()),this.starDOM||($[3]=$[3].replace("?",w.getDate().toString())),$[4]=$[4].replace("?",(w.getMonth()+1).toString()),this.starDOW||($[5]=$[5].replace("?",w.getDay().toString()))}this.throwAtIllegalCharacters($),this.partToArray("second",$[0],0,1),this.partToArray("minute",$[1],0,1),this.partToArray("hour",$[2],0,1),this.partToArray("day",$[3],-1,1),this.partToArray("month",$[4],-1,1),this.partToArray("dayOfWeek",$[5],0,nG),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,w,E,X){let G=this[$],J=$==="day"&&this.lastDayOfMonth;if(w===""&&!J)throw TypeError("CronPattern: configuration entry "+$+" ("+w+") is empty, check for trailing spaces.");if(w==="*")return G.fill(X);let A=w.split(",");if(A.length>1)for(let D=0;D<A.length;D++)this.partToArray($,A[D],E,X);else w.indexOf("-")!==-1&&w.indexOf("/")!==-1?this.handleRangeWithStepping(w,$,E,X):w.indexOf("-")!==-1?this.handleRange(w,$,E,X):w.indexOf("/")!==-1?this.handleStepping(w,$,E,X):w!==""&&this.handleNumber(w,$,E,X)}throwAtIllegalCharacters($){for(let w=0;w<$.length;w++)if((w===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test($[w]))throw TypeError("CronPattern: configuration entry "+w+" ("+$[w]+") contains illegal characters.")}handleNumber($,w,E,X){let G=this.extractNth($,w),J=parseInt(G[0],10)+E;if(isNaN(J))throw TypeError("CronPattern: "+w+" is not a number: '"+$+"'");this.setPart(w,J,G[1]||X)}setPart($,w,E){if(!Object.prototype.hasOwnProperty.call(this,$))throw TypeError("CronPattern: Invalid part specified: "+$);if($==="dayOfWeek"){if(w===7&&(w=0),w<0||w>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+w);this.setNthWeekdayOfMonth(w,E);return}if($==="second"||$==="minute"){if(w<0||w>=60)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="hour"){if(w<0||w>=24)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="day"){if(w<0||w>=31)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="month"&&(w<0||w>=12))throw RangeError("CronPattern: Invalid value for "+$+": "+w);this[$][w]=E}handleRangeWithStepping($,w,E,X){let G=this.extractNth($,w),J=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(J===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,A,D,N]=J,W=parseInt(A,10)+E,O=parseInt(D,10)+E,Y=parseInt(N,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(O))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Y===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Y>this[w].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[w].length+")");if(W>O)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let H=W;H<=O;H+=Y)this.setPart(w,H,G[1]||X)}extractNth($,w){let E=$,X;if(E.includes("#")){if(w!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");X=E.split("#")[1],E=E.split("#")[0]}return[E,X]}handleRange($,w,E,X){let G=this.extractNth($,w),J=G[0].split("-");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let A=parseInt(J[0],10)+E,D=parseInt(J[1],10)+E;if(isNaN(A))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(A>D)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let N=A;N<=D;N++)this.setPart(w,N,G[1]||X)}handleStepping($,w,E,X){let G=this.extractNth($,w),J=G[0].split("/");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");J[0]===""&&(J[0]="*");let A=0;J[0]!=="*"&&(A=parseInt(J[0],10)+E);let D=parseInt(J[1],10);if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(D===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(D>this[w].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[w].length+")");for(let N=A;N<this[w].length;N+=D)this.setPart(w,N,G[1]||X)}replaceAlphaDays($){return $.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths($){return $.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames($){let w=$.trim().toLowerCase();return w==="@yearly"||w==="@annually"?"0 0 1 1 *":w==="@monthly"?"0 0 1 * *":w==="@weekly"?"0 0 * * 0":w==="@daily"?"0 0 * * *":w==="@hourly"?"0 * * * *":$}setNthWeekdayOfMonth($,w){if(typeof w!="number"&&w==="L")this.dayOfWeek[$]=this.dayOfWeek[$]|CN;else if(w===nG)this.dayOfWeek[$]=nG;else if(w<6&&w>0)this.dayOfWeek[$]=this.dayOfWeek[$]|nL[w-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${w}, Type: ${typeof w}`)}},hL=[31,28,31,30,31,30,31,31,30,31,30,31],zw=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],F1=class ${tz;ms;second;minute;hour;day;month;year;constructor(w,E){if(this.tz=E,w&&w instanceof Date)if(!isNaN(w))this.fromDate(w);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(w===void 0)this.fromDate(new Date);else if(w&&typeof w=="string")this.fromString(w);else if(w instanceof $)this.fromCronDate(w);else throw TypeError("CronDate: Invalid type ("+typeof w+") passed to CronDate constructor")}isNthWeekdayOfMonth(w,E,X,G){let J=new Date(Date.UTC(w,E,X)).getUTCDay(),A=0;for(let D=1;D<=X;D++)new Date(Date.UTC(w,E,D)).getUTCDay()===J&&A++;if(G&nG&&nL[A-1]&G)return!0;if(G&CN){let D=new Date(Date.UTC(w,E+1,0)).getUTCDate();for(let N=X+1;N<=D;N++)if(new Date(Date.UTC(w,E,N)).getUTCDay()===J)return!1;return!0}return!1}fromDate(w){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes()+this.tz,this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),this.apply();else{let E=k$.toTZ(w,this.tz);this.ms=w.getMilliseconds(),this.second=E.s,this.minute=E.i,this.hour=E.h,this.day=E.d,this.month=E.m-1,this.year=E.y}else this.ms=w.getMilliseconds(),this.second=w.getSeconds(),this.minute=w.getMinutes(),this.hour=w.getHours(),this.day=w.getDate(),this.month=w.getMonth(),this.year=w.getFullYear()}fromCronDate(w){this.tz=w.tz,this.year=w.year,this.month=w.month,this.day=w.day,this.hour=w.hour,this.minute=w.minute,this.second=w.second,this.ms=w.ms}apply(){if(this.month>11||this.day>hL[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let w=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes(),this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),!0}else return!1}fromString(w){if(typeof this.tz=="number"){let E=k$.fromTZISO(w);this.ms=E.getUTCMilliseconds(),this.second=E.getUTCSeconds(),this.minute=E.getUTCMinutes(),this.hour=E.getUTCHours(),this.day=E.getUTCDate(),this.month=E.getUTCMonth(),this.year=E.getUTCFullYear(),this.apply()}else return this.fromDate(k$.fromTZISO(w,this.tz))}findNext(w,E,X,G){let J=this[E],A;X.lastDayOfMonth&&(this.month!==1?A=hL[this.month]:A=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let D=!X.starDOW&&E=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let N=this[E]+G;N<X[E].length;N++){let W=X[E][N];if(E==="day"&&X.lastDayOfMonth&&N-G==A&&(W=1),E==="day"&&!X.starDOW){let O=X.dayOfWeek[(D+(N-G-1))%7];if(O&&O&nG)O=this.isNthWeekdayOfMonth(this.year,this.month,N-G,O)?1:0;else if(O)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${O}`);w.legacyMode&&!X.starDOM?W=W||O:W=W&&O}if(W)return this[E]=N-G,J!==this[E]?2:1}return 3}recurse(w,E,X){let G=this.findNext(E,zw[X][0],w,zw[X][2]);if(G>1){let J=X+1;for(;J<zw.length;)this[zw[J][0]]=-zw[J][2],J++;if(G===3)return this[zw[X][1]]++,this[zw[X][0]]=-zw[X][2],this.apply(),this.recurse(w,E,0);if(this.apply())return this.recurse(w,E,X-1)}return X+=1,X>=zw.length?this:this.year>=3000?null:this.recurse(w,E,X)}increment(w,E,X){return this.second+=E.interval!==void 0&&E.interval>1&&X?E.interval:1,this.ms=0,this.apply(),this.recurse(w,E,0)}getDate(w){return w||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):k$.fromTZ(k$.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function $Z($){if($===void 0&&($={}),delete $.name,$.legacyMode=$.legacyMode===void 0?!0:$.legacyMode,$.paused=$.paused===void 0?!1:$.paused,$.maxRuns=$.maxRuns===void 0?1/0:$.maxRuns,$.catch=$.catch===void 0?!1:$.catch,$.interval=$.interval===void 0?0:parseInt($.interval.toString(),10),$.utcOffset=$.utcOffset===void 0?void 0:parseInt($.utcOffset.toString(),10),$.unref=$.unref===void 0?!1:$.unref,$.startAt&&($.startAt=new F1($.startAt,$.timezone)),$.stopAt&&($.stopAt=new F1($.stopAt,$.timezone)),$.interval!==null){if(isNaN($.interval))throw Error("CronOptions: Supplied value for interval is not a number");if($.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if($.utcOffset!==void 0){if(isNaN($.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if($.utcOffset<-870||$.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if($.utcOffset!==void 0&&$.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if($.unref!==!0&&$.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return $}function cG($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function wZ($){return cG($)}function EZ($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var cL=30000,TA=[],mL=class{name;options;_states;fn;constructor($,w,E){let X,G;if(cG(w))G=w;else if(typeof w=="object")X=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(cG(E))G=E;else if(typeof E=="object")X=E;else if(E!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=X?.name,this.options=$Z(X),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:X?X.maxRuns:void 0,paused:X?X.paused:!1,pattern:new uL("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new F1($,this.options.timezone||this.options.utcOffset):this._states.pattern=new uL($,this.options.timezone),this.name){if(TA.find((J)=>J.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");TA.push(this)}return G!==void 0&&wZ(G)&&(this.fn=G,this.schedule()),this}nextRun($){let w=this._next($);return w?w.getDate(!1):null}nextRuns($,w){this._states.maxRuns!==void 0&&$>this._states.maxRuns&&($=this._states.maxRuns);let E=[],X=w||this._states.currentRun||void 0;for(;$--&&(X=this.nextRun(X));)E.push(X);return E}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),w=!this._states.paused,E=this.fn!==void 0,X=!this._states.kill;return w&&E&&X&&$!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext($){let w=this._next($);return w?$ instanceof F1||$ instanceof Date?w.getTime()-$.getTime():w.getTime()-new F1($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=TA.indexOf(this);$>=0&&TA.splice($,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule($){if($&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");$&&(this.fn=$);let w=this.msToNext(),E=this.nextRun(this._states.currentRun);return w==null||isNaN(w)||E===null?this:(w>cL&&(w=cL),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(E),w),this._states.currentTimeout&&this.options.unref&&EZ(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new F1(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(w){cG(this.options.catch)&&this.options.catch(w,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new F1($,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger($){let w=new Date,E=!this._states.paused&&w.getTime()>=$.getTime(),X=this._states.blocking&&this.options.protect;E&&!X?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):E&&X&&cG(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let w=!!($||this._states.currentRun),E=!1;!$&&this.options.startAt&&this.options.interval&&([$,w]=this._calculatePreviousRun($,w),E=!$),$=new F1($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let X=this._states.once||new F1($,this.options.timezone||this.options.utcOffset);return!E&&X!==this._states.once&&(X=X.increment(this._states.pattern,this.options,w)),this._states.once&&this._states.once.getTime()<=$.getTime()||X===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&X.getTime()>=this.options.stopAt.getTime()?null:X}_calculatePreviousRun($,w){let E=new F1(void 0,this.options.timezone||this.options.utcOffset),X=$;if(this.options.startAt.getTime()<=E.getTime()){X=this.options.startAt;let G=X.getTime()+this.options.interval*1000;for(;G<=E.getTime();)X=new F1(X,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=X.getTime()+this.options.interval*1000;w=!0}return X===null&&(X=void 0),[X,w]}};i$();nw();var Tw=Z0("runner:scheduler"),RX=new Map,rw=new Map;async function rL(){let w=await x().query.jobs.findMany({where:V(I0.enabled,!0)}),E=new Set(["cron","one-shot","watch","webhook","manual","bridge-msg"]),X=w.filter((G)=>!E.has(G.trigger_type));if(X.length>0)Tw.warn(`${X.length} job(s) have an unsupported trigger type and will not fire: ${X.map((G)=>`${G.name} (${G.trigger_type})`).join(", ")}. Use 'cron' with a 6-field expression (e.g. '*/30 * * * * *') for sub-minute intervals.`);for(let G of w)if(G.trigger_type==="cron"&&G.cron_expr)XZ(G.id,G.name,G.cron_expr);else if(G.trigger_type==="one-shot"&&G.run_at)GZ(G.id,G.name,G.run_at,G.run_count);Tw.info(`Scheduler started. ${RX.size} cron + ${rw.size} one-shot jobs scheduled.`)}function XZ($,w,E){if(RX.has($))RX.get($)?.stop();let X=new mL(E,async()=>{Tw.info(`Cron trigger: ${w}`);try{await A1({jobId:$,triggerBy:"cron"})}catch(G){Tw.error(`Cron job failed: ${w}`,G)}});RX.set($,X),Tw.info(`Scheduled cron job: ${w} (${E})`)}function GZ($,w,E,X){if(X>0)return;if(rw.has($))clearTimeout(rw.get($)),rw.delete($);let G=Math.max(0,E.getTime()-Date.now()),J=setTimeout(async()=>{rw.delete($),Tw.info(`One-shot trigger: ${w}`);try{await A1({jobId:$,triggerBy:"one-shot"})}catch(D){Tw.error(`One-shot job failed: ${w}`,D)}},G);rw.set($,J);let A=G<1000?"now":`in ${Math.round(G/1000)}s`;Tw.info(`Scheduled one-shot job: ${w} (${A})`)}function pL(){for(let[,$]of RX)$.stop();RX.clear();for(let[,$]of rw)clearTimeout($);rw.clear(),Tw.info("Scheduler stopped.")}p$();y$();d$();import{stat as vZ}from"fs";import{stat as fZ,readdir as xZ}from"fs/promises";import{EventEmitter as yZ}from"events";import*as H0 from"path";import{stat as JZ,lstat as oL,readdir as AZ,realpath as DZ}from"fs/promises";import{Readable as NZ}from"stream";import{resolve as tL,relative as WZ,join as OZ,sep as UZ}from"path";var D1={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},_N={root:".",fileFilter:($)=>!0,directoryFilter:($)=>!0,type:D1.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(_N);var sL="READDIRP_RECURSIVE_ERROR",YZ=new Set(["ENOENT","EPERM","EACCES","ELOOP",sL]),iL=[D1.DIR_TYPE,D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE,D1.FILE_TYPE],HZ=new Set([D1.DIR_TYPE,D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE]),LZ=new Set([D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE,D1.FILE_TYPE]),FZ=($)=>YZ.has($.code),jZ=process.platform==="win32",dL=($)=>!0,lL=($)=>{if($===void 0)return dL;if(typeof $==="function")return $;if(typeof $==="string"){let w=$.trim();return(E)=>E.basename===w}if(Array.isArray($)){let w=$.map((E)=>E.trim());return(E)=>w.some((X)=>E.basename===X)}return dL};class aL extends NZ{constructor($={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:$.highWaterMark});let w={..._N,...$},{root:E,type:X}=w;this._fileFilter=lL(w.fileFilter),this._directoryFilter=lL(w.directoryFilter);let G=w.lstat?oL:JZ;if(jZ)this._stat=(J)=>G(J,{bigint:!0});else this._stat=G;this._maxDepth=w.depth??_N.depth,this._wantsDir=X?HZ.has(X):!1,this._wantsFile=X?LZ.has(X):!1,this._wantsEverything=X===D1.EVERYTHING_TYPE,this._root=tL(E),this._isDirent=!w.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(E,1)],this.reading=!1,this.parent=void 0}async _read($){if(this.reading)return;this.reading=!0;try{while(!this.destroyed&&$>0){let w=this.parent,E=w&&w.files;if(E&&E.length>0){let{path:X,depth:G}=w,J=E.splice(0,$).map((D)=>this._formatEntry(D,X)),A=await Promise.all(J);for(let D of A){if(!D)continue;if(this.destroyed)return;let N=await this._getEntryType(D);if(N==="directory"&&this._directoryFilter(D)){if(G<=this._maxDepth)this.parents.push(this._exploreDir(D.fullPath,G+1));if(this._wantsDir)this.push(D),$--}else if((N==="file"||this._includeAsFile(D))&&this._fileFilter(D)){if(this._wantsFile)this.push(D),$--}}}else{let X=this.parents.pop();if(!X){this.push(null);break}if(this.parent=await X,this.destroyed)return}}}catch(w){this.destroy(w)}finally{this.reading=!1}}async _exploreDir($,w){let E;try{E=await AZ($,this._rdOptions)}catch(X){this._onError(X)}return{files:E,depth:w,path:$}}async _formatEntry($,w){let E,X=this._isDirent?$.name:$;try{let G=tL(OZ(w,X));E={path:WZ(this._root,G),fullPath:G,basename:X},E[this._statsProp]=this._isDirent?$:await this._stat(G)}catch(G){this._onError(G);return}return E}_onError($){if(FZ($)&&!this.destroyed)this.emit("warn",$);else this.destroy($)}async _getEntryType($){if(!$&&this._statsProp in $)return"";let w=$[this._statsProp];if(w.isFile())return"file";if(w.isDirectory())return"directory";if(w&&w.isSymbolicLink()){let E=$.fullPath;try{let X=await DZ(E),G=await oL(X);if(G.isFile())return"file";if(G.isDirectory()){let J=X.length;if(E.startsWith(X)&&E.substr(J,1)===UZ){let A=Error(`Circular symlink detected: "${E}" points to "${X}"`);return A.code=sL,this._onError(A)}return"directory"}}catch(X){return this._onError(X),""}}}_includeAsFile($){let w=$&&$[this._statsProp];return w&&this._wantsEverything&&!w.isDirectory()}}function eL($,w={}){let E=w.entryType||w.type;if(E==="both")E=D1.FILE_DIR_TYPE;if(E)w.type=E;if(!$)throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");else if(typeof $!=="string")throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if(E&&!iL.includes(E))throw Error(`readdirp: Invalid type passed. Use one of ${iL.join(", ")}`);return w.root=$,new aL(w)}import{watchFile as MZ,unwatchFile as $3,watch as RZ}from"fs";import{open as zZ,stat as E3,lstat as TZ,realpath as vN}from"fs/promises";import*as r0 from"path";import{type as BZ}from"os";var QZ="data",yN="end",X3="close",KA=()=>{};var VA=process.platform,gN=VA==="win32",IZ=VA==="darwin",KZ=VA==="linux",VZ=VA==="freebsd",G3=BZ()==="OS400",y0={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},v1=y0,PZ="watch",qZ={lstat:TZ,stat:E3},TE="listeners",BA="errHandlers",zX="rawEmitters",SZ=[TE,BA,zX],kZ=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),bZ=($)=>kZ.has(r0.extname($).slice(1).toLowerCase()),xN=($,w)=>{if($ instanceof Set)$.forEach(w);else w($)},mG=($,w,E)=>{let X=$[w];if(!(X instanceof Set))$[w]=X=new Set([X]);X.add(E)},ZZ=($)=>(w)=>{let E=$[w];if(E instanceof Set)E.clear();else delete $[w]},rG=($,w,E)=>{let X=$[w];if(X instanceof Set)X.delete(E);else if(X===E)delete $[w]},J3=($)=>$ instanceof Set?$.size===0:!$,QA=new Map;function w3($,w,E,X,G){let J=(A,D)=>{if(E($),G(A,D,{watchedPath:$}),D&&$!==D)IA(r0.resolve($,D),TE,r0.join($,D))};try{return RZ($,{persistent:w.persistent},J)}catch(A){X(A);return}}var IA=($,w,E,X,G)=>{let J=QA.get($);if(!J)return;xN(J[w],(A)=>{A(E,X,G)})},CZ=($,w,E,X)=>{let{listener:G,errHandler:J,rawEmitter:A}=X,D=QA.get(w),N;if(!E.persistent){if(N=w3($,E,G,J,A),!N)return;return N.close.bind(N)}if(D)mG(D,TE,G),mG(D,BA,J),mG(D,zX,A);else{if(N=w3($,E,IA.bind(null,w,TE),J,IA.bind(null,w,zX)),!N)return;N.on(v1.ERROR,async(W)=>{let O=IA.bind(null,w,BA);if(D)D.watcherUnusable=!0;if(gN&&W.code==="EPERM")try{await(await zZ($,"r")).close(),O(W)}catch(Y){}else O(W)}),D={listeners:G,errHandlers:J,rawEmitters:A,watcher:N},QA.set(w,D)}return()=>{if(rG(D,TE,G),rG(D,BA,J),rG(D,zX,A),J3(D.listeners))D.watcher.close(),QA.delete(w),SZ.forEach(ZZ(D)),D.watcher=void 0,Object.freeze(D)}},fN=new Map,_Z=($,w,E,X)=>{let{listener:G,rawEmitter:J}=X,A=fN.get(w),D=A&&A.options;if(D&&(D.persistent<E.persistent||D.interval>E.interval))$3(w),A=void 0;if(A)mG(A,TE,G),mG(A,zX,J);else A={listeners:G,rawEmitters:J,options:E,watcher:MZ(w,E,(N,W)=>{xN(A.rawEmitters,(Y)=>{Y(v1.CHANGE,w,{curr:N,prev:W})});let O=N.mtimeMs;if(N.size!==W.size||O>W.mtimeMs||O===0)xN(A.listeners,(Y)=>Y($,N))})},fN.set(w,A);return()=>{if(rG(A,TE,G),rG(A,zX,J),J3(A.listeners))fN.delete(w),$3(w),A.options=A.watcher=void 0,Object.freeze(A)}};class uN{constructor($){this.fsw=$,this._boundHandleError=(w)=>$._handleError(w)}_watchWithNodeFs($,w){let E=this.fsw.options,X=r0.dirname($),G=r0.basename($);this.fsw._getWatchedDir(X).add(G);let A=r0.resolve($),D={persistent:E.persistent};if(!w)w=KA;let N;if(E.usePolling){let W=E.interval!==E.binaryInterval;D.interval=W&&bZ(G)?E.binaryInterval:E.interval,N=_Z($,A,D,{listener:w,rawEmitter:this.fsw._emitRaw})}else N=CZ($,A,D,{listener:w,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return N}_handleFile($,w,E){if(this.fsw.closed)return;let X=r0.dirname($),G=r0.basename($),J=this.fsw._getWatchedDir(X),A=w;if(J.has(G))return;let D=async(W,O)=>{if(!this.fsw._throttle(PZ,$,5))return;if(!O||O.mtimeMs===0)try{let Y=await E3($);if(this.fsw.closed)return;let{atimeMs:H,mtimeMs:L}=Y;if(!H||H<=L||L!==A.mtimeMs)this.fsw._emit(v1.CHANGE,$,Y);if((IZ||KZ||VZ)&&A.ino!==Y.ino){this.fsw._closeFile(W),A=Y;let F=this._watchWithNodeFs($,D);if(F)this.fsw._addPathCloser(W,F)}else A=Y}catch(Y){this.fsw._remove(X,G)}else if(J.has(G)){let{atimeMs:Y,mtimeMs:H}=O;if(!Y||Y<=H||H!==A.mtimeMs)this.fsw._emit(v1.CHANGE,$,O);A=O}},N=this._watchWithNodeFs($,D);if(!(E&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored($)){if(!this.fsw._throttle(v1.ADD,$,0))return;this.fsw._emit(v1.ADD,$,w)}return N}async _handleSymlink($,w,E,X){if(this.fsw.closed)return;let G=$.fullPath,J=this.fsw._getWatchedDir(w);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let A;try{A=await vN(E)}catch(D){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;if(J.has(X)){if(this.fsw._symlinkPaths.get(G)!==A)this.fsw._symlinkPaths.set(G,A),this.fsw._emit(v1.CHANGE,E,$.stats)}else J.add(X),this.fsw._symlinkPaths.set(G,A),this.fsw._emit(v1.ADD,E,$.stats);return this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(G))return!0;this.fsw._symlinkPaths.set(G,!0)}_handleRead($,w,E,X,G,J,A){if($=r0.join($,""),A=this.fsw._throttle("readdir",$,1000),!A)return;let D=this.fsw._getWatchedDir(E.path),N=new Set,W=this.fsw._readdirp($,{fileFilter:(O)=>E.filterPath(O),directoryFilter:(O)=>E.filterDir(O)});if(!W)return;return W.on(QZ,async(O)=>{if(this.fsw.closed){W=void 0;return}let Y=O.path,H=r0.join($,Y);if(N.add(Y),O.stats.isSymbolicLink()&&await this._handleSymlink(O,$,H,Y))return;if(this.fsw.closed){W=void 0;return}if(Y===X||!X&&!D.has(Y))this.fsw._incrReadyCount(),H=r0.join(G,r0.relative(G,H)),this._addToNodeFs(H,w,E,J+1)}).on(v1.ERROR,this._boundHandleError),new Promise((O,Y)=>{if(!W)return Y();W.once(yN,()=>{if(this.fsw.closed){W=void 0;return}let H=A?A.clear():!1;if(O(void 0),D.getChildren().filter((L)=>{return L!==$&&!N.has(L)}).forEach((L)=>{this.fsw._remove($,L)}),W=void 0,H)this._handleRead($,!1,E,X,G,J,A)})})}async _handleDir($,w,E,X,G,J,A){let D=this.fsw._getWatchedDir(r0.dirname($)),N=D.has(r0.basename($));if(!(E&&this.fsw.options.ignoreInitial)&&!G&&!N)this.fsw._emit(v1.ADD_DIR,$,w);D.add(r0.basename($)),this.fsw._getWatchedDir($);let W,O,Y=this.fsw.options.depth;if((Y==null||X<=Y)&&!this.fsw._symlinkPaths.has(A)){if(!G){if(await this._handleRead($,E,J,G,$,X,W),this.fsw.closed)return}O=this._watchWithNodeFs($,(H,L)=>{if(L&&L.mtimeMs===0)return;this._handleRead(H,!1,J,G,$,X,W)})}return O}async _addToNodeFs($,w,E,X,G){let J=this.fsw._emitReady;if(this.fsw._isIgnored($)||this.fsw.closed)return J(),!1;let A=this.fsw._getWatchHelpers($);if(E)A.filterPath=(D)=>E.filterPath(D),A.filterDir=(D)=>E.filterDir(D);try{let D=await qZ[A.statMethod](A.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(A.watchPath,D))return J(),!1;let N=this.fsw.options.followSymlinks,W;if(D.isDirectory()){let O=r0.resolve($),Y=N?await vN($):$;if(this.fsw.closed)return;if(W=await this._handleDir(A.watchPath,D,w,X,G,A,Y),this.fsw.closed)return;if(O!==Y&&Y!==void 0)this.fsw._symlinkPaths.set(O,Y)}else if(D.isSymbolicLink()){let O=N?await vN($):$;if(this.fsw.closed)return;let Y=r0.dirname(A.watchPath);if(this.fsw._getWatchedDir(Y).add(A.watchPath),this.fsw._emit(v1.ADD,A.watchPath,D),W=await this._handleDir(Y,D,w,X,$,A,O),this.fsw.closed)return;if(O!==void 0)this.fsw._symlinkPaths.set(r0.resolve($),O)}else W=this._handleFile(A.watchPath,D,w);if(J(),W)this.fsw._addPathCloser($,W);return!1}catch(D){if(this.fsw._handleError(D))return J(),$}}}/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */var hN="/",gZ="//",U3=".",uZ="..",hZ="string",cZ=/\\/g,A3=/\/\//,nZ=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,mZ=/^\.[/\\]/;function PA($){return Array.isArray($)?$:[$]}var cN=($)=>typeof $==="object"&&$!==null&&!($ instanceof RegExp);function rZ($){if(typeof $==="function")return $;if(typeof $==="string")return(w)=>$===w;if($ instanceof RegExp)return(w)=>$.test(w);if(typeof $==="object"&&$!==null)return(w)=>{if($.path===w)return!0;if($.recursive){let E=H0.relative($.path,w);if(!E)return!1;return!E.startsWith("..")&&!H0.isAbsolute(E)}return!1};return()=>!1}function pZ($){if(typeof $!=="string")throw Error("string expected");$=H0.normalize($),$=$.replace(/\\/g,"/");let w=!1;if($.startsWith("//"))w=!0;let E=/\/\//;while($.match(E))$=$.replace(E,"/");if(w)$="/"+$;return $}function D3($,w,E){let X=pZ(w);for(let G=0;G<$.length;G++){let J=$[G];if(J(X,E))return!0}return!1}function oZ($,w){if($==null)throw TypeError("anymatch: specify first argument");let X=PA($).map((G)=>rZ(G));if(w==null)return(G,J)=>{return D3(X,G,J)};return D3(X,w)}var N3=($)=>{let w=PA($).flat();if(!w.every((E)=>typeof E===hZ))throw TypeError(`Non-string provided as watch path: ${w}`);return w.map(Y3)},W3=($)=>{let w=$.replace(cZ,hN),E=!1;if(w.startsWith(gZ))E=!0;while(w.match(A3))w=w.replace(A3,hN);if(E)w=hN+w;return w},Y3=($)=>W3(H0.normalize(W3($))),O3=($="")=>(w)=>{if(typeof w==="string")return Y3(H0.isAbsolute(w)?w:H0.join($,w));else return w},tZ=($,w)=>{if(H0.isAbsolute($))return $;return H0.join(w,$)},iZ=Object.freeze(new Set);class H3{constructor($,w){this.path=$,this._removeWatcher=w,this.items=new Set}add($){let{items:w}=this;if(!w)return;if($!==U3&&$!==uZ)w.add($)}async remove($){let{items:w}=this;if(!w)return;if(w.delete($),w.size>0)return;let E=this.path;try{await xZ(E)}catch(X){if(this._removeWatcher)this._removeWatcher(H0.dirname(E),H0.basename(E))}}has($){let{items:w}=this;if(!w)return;return w.has($)}getChildren(){let{items:$}=this;if(!$)return[];return[...$.values()]}dispose(){this.items.clear(),this.path="",this._removeWatcher=KA,this.items=iZ,Object.freeze(this)}}var dZ="stat",lZ="lstat";class L3{constructor($,w,E){this.fsw=E;let X=$;this.path=$=$.replace(mZ,""),this.watchPath=X,this.fullWatchPath=H0.resolve(X),this.dirParts=[],this.dirParts.forEach((G)=>{if(G.length>1)G.pop()}),this.followSymlinks=w,this.statMethod=w?dZ:lZ}entryPath($){return H0.join(this.watchPath,H0.relative(this.watchPath,$.fullPath))}filterPath($){let{stats:w}=$;if(w&&w.isSymbolicLink())return this.filterDir($);let E=this.entryPath($);return this.fsw._isntIgnored(E,w)&&this.fsw._hasReadPermissions(w)}filterDir($){return this.fsw._isntIgnored(this.entryPath($),$.stats)}}class nN extends yZ{constructor($={}){super();this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let w=$.awaitWriteFinish,E={stabilityThreshold:2000,pollInterval:100},X={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...$,ignored:$.ignored?PA($.ignored):PA([]),awaitWriteFinish:w===!0?E:typeof w==="object"?{...E,...w}:!1};if(G3)X.usePolling=!0;if(X.atomic===void 0)X.atomic=!X.usePolling;let G=process.env.CHOKIDAR_USEPOLLING;if(G!==void 0){let D=G.toLowerCase();if(D==="false"||D==="0")X.usePolling=!1;else if(D==="true"||D==="1")X.usePolling=!0;else X.usePolling=!!D}let J=process.env.CHOKIDAR_INTERVAL;if(J)X.interval=Number.parseInt(J,10);let A=0;this._emitReady=()=>{if(A++,A>=this._readyCount)this._emitReady=KA,this._readyEmitted=!0,process.nextTick(()=>this.emit(y0.READY))},this._emitRaw=(...D)=>this.emit(y0.RAW,...D),this._boundRemove=this._remove.bind(this),this.options=X,this._nodeFsHandler=new uN(this),Object.freeze(X)}_addIgnoredPath($){if(cN($)){for(let w of this._ignoredPaths)if(cN(w)&&w.path===$.path&&w.recursive===$.recursive)return}this._ignoredPaths.add($)}_removeIgnoredPath($){if(this._ignoredPaths.delete($),typeof $==="string"){for(let w of this._ignoredPaths)if(cN(w)&&w.path===$)this._ignoredPaths.delete(w)}}add($,w,E){let{cwd:X}=this.options;this.closed=!1,this._closePromise=void 0;let G=N3($);if(X)G=G.map((J)=>{return tZ(J,X)});if(G.forEach((J)=>{this._removeIgnoredPath(J)}),this._userIgnored=void 0,!this._readyCount)this._readyCount=0;return this._readyCount+=G.length,Promise.all(G.map(async(J)=>{let A=await this._nodeFsHandler._addToNodeFs(J,!E,void 0,0,w);if(A)this._emitReady();return A})).then((J)=>{if(this.closed)return;J.forEach((A)=>{if(A)this.add(H0.dirname(A),H0.basename(w||A))})}),this}unwatch($){if(this.closed)return this;let w=N3($),{cwd:E}=this.options;return w.forEach((X)=>{if(!H0.isAbsolute(X)&&!this._closers.has(X)){if(E)X=H0.join(E,X);X=H0.resolve(X)}if(this._closePath(X),this._addIgnoredPath(X),this._watched.has(X))this._addIgnoredPath({path:X,recursive:!0});this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let $=[];return this._closers.forEach((w)=>w.forEach((E)=>{let X=E();if(X instanceof Promise)$.push(X)})),this._streams.forEach((w)=>w.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach((w)=>w.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=$.length?Promise.all($).then(()=>{return}):Promise.resolve(),this._closePromise}getWatched(){let $={};return this._watched.forEach((w,E)=>{let G=(this.options.cwd?H0.relative(this.options.cwd,E):E)||U3;$[G]=w.getChildren().sort()}),$}emitWithAll($,w){if(this.emit($,...w),$!==y0.ERROR)this.emit(y0.ALL,$,...w)}async _emit($,w,E){if(this.closed)return;let X=this.options;if(gN)w=H0.normalize(w);if(X.cwd)w=H0.relative(X.cwd,w);let G=[w];if(E!=null)G.push(E);let J=X.awaitWriteFinish,A;if(J&&(A=this._pendingWrites.get(w)))return A.lastChange=new Date,this;if(X.atomic){if($===y0.UNLINK)return this._pendingUnlinks.set(w,[$,...G]),setTimeout(()=>{this._pendingUnlinks.forEach((D,N)=>{this.emit(...D),this.emit(y0.ALL,...D),this._pendingUnlinks.delete(N)})},typeof X.atomic==="number"?X.atomic:100),this;if($===y0.ADD&&this._pendingUnlinks.has(w))$=y0.CHANGE,this._pendingUnlinks.delete(w)}if(J&&($===y0.ADD||$===y0.CHANGE)&&this._readyEmitted){let D=(N,W)=>{if(N)$=y0.ERROR,G[0]=N,this.emitWithAll($,G);else if(W){if(G.length>1)G[1]=W;else G.push(W);this.emitWithAll($,G)}};return this._awaitWriteFinish(w,J.stabilityThreshold,$,D),this}if($===y0.CHANGE){if(!this._throttle(y0.CHANGE,w,50))return this}if(X.alwaysStat&&E===void 0&&($===y0.ADD||$===y0.ADD_DIR||$===y0.CHANGE)){let D=X.cwd?H0.join(X.cwd,w):w,N;try{N=await fZ(D)}catch(W){}if(!N||this.closed)return;G.push(N)}return this.emitWithAll($,G),this}_handleError($){let w=$&&$.code;if($&&w!=="ENOENT"&&w!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||w!=="EPERM"&&w!=="EACCES"))this.emit(y0.ERROR,$);return $||this.closed}_throttle($,w,E){if(!this._throttled.has($))this._throttled.set($,new Map);let X=this._throttled.get($);if(!X)throw Error("invalid throttle");let G=X.get(w);if(G)return G.count++,!1;let J,A=()=>{let N=X.get(w),W=N?N.count:0;if(X.delete(w),clearTimeout(J),N)clearTimeout(N.timeoutObject);return W};J=setTimeout(A,E);let D={timeoutObject:J,clear:A,count:0};return X.set(w,D),D}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish($,w,E,X){let G=this.options.awaitWriteFinish;if(typeof G!=="object")return;let J=G.pollInterval,A,D=$;if(this.options.cwd&&!H0.isAbsolute($))D=H0.join(this.options.cwd,$);let N=new Date,W=this._pendingWrites;function O(Y){vZ(D,(H,L)=>{if(H||!W.has($)){if(H&&H.code!=="ENOENT")X(H);return}let F=Number(new Date);if(Y&&L.size!==Y.size)W.get($).lastChange=F;let j=W.get($);if(F-j.lastChange>=w)W.delete($),X(void 0,L);else A=setTimeout(O,J,L)})}if(!W.has($))W.set($,{lastChange:N,cancelWait:()=>{return W.delete($),clearTimeout(A),E}}),A=setTimeout(O,J)}_isIgnored($,w){if(this.options.atomic&&nZ.test($))return!0;if(!this._userIgnored){let{cwd:E}=this.options,G=(this.options.ignored||[]).map(O3(E)),A=[...[...this._ignoredPaths].map(O3(E)),...G];this._userIgnored=oZ(A,void 0)}return this._userIgnored($,w)}_isntIgnored($,w){return!this._isIgnored($,w)}_getWatchHelpers($){return new L3($,this.options.followSymlinks,this)}_getWatchedDir($){let w=H0.resolve($);if(!this._watched.has(w))this._watched.set(w,new H3(w,this._boundRemove));return this._watched.get(w)}_hasReadPermissions($){if(this.options.ignorePermissionErrors)return!0;return Boolean(Number($.mode)&256)}_remove($,w,E){let X=H0.join($,w),G=H0.resolve(X);if(E=E!=null?E:this._watched.has(X)||this._watched.has(G),!this._throttle("remove",X,100))return;if(!E&&this._watched.size===1)this.add($,w,!0);this._getWatchedDir(X).getChildren().forEach((Y)=>this._remove(X,Y));let D=this._getWatchedDir($),N=D.has(w);if(D.remove(w),this._symlinkPaths.has(G))this._symlinkPaths.delete(G);let W=X;if(this.options.cwd)W=H0.relative(this.options.cwd,X);if(this.options.awaitWriteFinish&&this._pendingWrites.has(W)){if(this._pendingWrites.get(W).cancelWait()===y0.ADD)return}this._watched.delete(X),this._watched.delete(G);let O=E?y0.UNLINK_DIR:y0.UNLINK;if(N&&!this._isIgnored(X))this._emit(O,X);this._closePath(X)}_closePath($){this._closeFile($);let w=H0.dirname($);this._getWatchedDir(w).remove(H0.basename($))}_closeFile($){let w=this._closers.get($);if(!w)return;w.forEach((E)=>E()),this._closers.delete($)}_addPathCloser($,w){if(!w)return;let E=this._closers.get($);if(!E)E=[],this._closers.set($,E);E.push(w)}_readdirp($,w){if(this.closed)return;let E={type:y0.ALL,alwaysStat:!0,lstat:!0,...w,depth:0},X=eL($,E);return this._streams.add(X),X.once(X3,()=>{X=void 0}),X.once(yN,()=>{if(X)this._streams.delete(X),X=void 0}),X}}function sZ($,w={}){let E=new nN(w);return E.add($),E}var F3={watch:sZ,FSWatcher:nN};i$();nw();var pG=Z0("runner:watcher"),TX=new Map;async function M3(){let w=await x().query.jobs.findMany({where:V(I0.enabled,!0)});for(let E of w)if(E.trigger_type==="watch"&&E.watch_path)aZ(E.id,E.name,E.watch_path);pG.info(`Watchers started. ${TX.size} paths watched.`)}function aZ($,w,E){if(TX.has($))TX.get($)?.close().catch(()=>{});let X=F3.watch(E,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});X.on("add",(G)=>j3($,w,G)),X.on("change",(G)=>j3($,w,G)),TX.set($,X),pG.info(`Watching: ${E} \u2192 ${w}`)}async function j3($,w,E){pG.info(`Watch trigger: ${w} (${E})`);try{await A1({jobId:$,triggerBy:"watch",envOverrides:{WATCH_PATH:E}})}catch(X){pG.error(`Watch job failed: ${w}`,X)}}async function R3(){for(let[,$]of TX)await $.close();TX.clear(),pG.info("Watchers stopped.")}C$();async function eZ($,w,E,X,G,J){let A=`${$}${X}`;if(J){let N=new URLSearchParams;for(let[O,Y]of Object.entries(J))if(Y!==void 0)N.set(O,String(Y));let W=N.toString();if(W)A+=`?${W}`}let D={"Content-Type":"application/json"};if(w)D.Authorization=`Bearer ${w}`;try{let N=await fetch(A,{method:E,headers:D,...G!==void 0?{body:JSON.stringify(G)}:{}});if(N.status===204)return{data:null,error:null};let W=await N.json();if(!N.ok){let O=W;return{data:null,error:{error:O.error??"Unknown error",code:O.code??"UNKNOWN"}}}return{data:W,error:null}}catch(N){return{data:null,error:{error:String(N),code:"NETWORK_ERROR"}}}}function e($){let w=O0(),E=$?.baseUrl??`http://${w.api.host}:${w.api.port}`,X=$?.secret??w.api.secret,G=(J,A,D,N)=>eZ(E,X,J,A,D,N);return{tasks:{list:(J)=>G("GET","/tasks",void 0,J),get:(J)=>G("GET",`/tasks/${J}`),create:(J)=>G("POST","/tasks",J),update:(J,A)=>G("PATCH",`/tasks/${J}`,A),delete:(J)=>G("DELETE",`/tasks/${J}`),addComment:(J,A,D="human")=>G("POST",`/tasks/${J}/comments`,{content:A,author:D}),listComments:(J)=>G("GET",`/tasks/${J}/comments`),listLinks:(J)=>G("GET",`/tasks/${J}/links`),addLink:(J,A)=>G("POST",`/tasks/${J}/links`,A),deleteLink:(J,A)=>G("DELETE",`/tasks/${J}/links/${A}`)},memories:{list:(J)=>G("GET","/memories",void 0,J),search:(J,A)=>G("GET","/memories/search",void 0,{q:J,scope:A?.scope,project_id:A?.project_id,limit:A?.limit}),create:(J)=>G("POST","/memories",J),delete:(J)=>G("DELETE",`/memories/${J}`)},jobs:{list:(J)=>G("GET","/jobs",void 0,J),get:(J)=>G("GET",`/jobs/${J}`),create:(J)=>G("POST","/jobs",J),update:(J,A)=>G("PATCH",`/jobs/${J}`,A),delete:(J)=>G("DELETE",`/jobs/${J}`),trigger:(J)=>G("POST",`/jobs/${J}/trigger`),runs:(J,A)=>G("GET",`/jobs/${J}/runs`,void 0,{limit:A}),runLogs:(J,A,D)=>G("GET",`/jobs/${J}/runs/${A}/logs`,void 0,D)},prompts:{list:(J)=>G("GET","/prompts",void 0,J),get:(J)=>G("GET",`/prompts/${J}`),create:(J)=>G("POST","/prompts",J),update:(J,A)=>G("PATCH",`/prompts/${J}`,A),delete:(J)=>G("DELETE",`/prompts/${J}`),render:(J,A)=>G("POST",`/prompts/${J}/render`,{vars:A??{}}),history:(J,A)=>G("GET",`/prompts/${J}/history`,void 0,{limit:A})},projects:{list:(J)=>G("GET","/projects",void 0,J),get:(J)=>G("GET",`/projects/${J}`),getByName:(J)=>G("GET",`/projects/by-name/${encodeURIComponent(J)}`),summary:(J)=>G("GET",`/projects/${J}/summary`),create:(J)=>G("POST","/projects",J),update:(J,A)=>G("PATCH",`/projects/${J}`,A),delete:(J)=>G("DELETE",`/projects/${J}`),addComment:(J,A,D="human")=>G("POST",`/projects/${J}/comments`,{content:A,author:D}),listComments:(J)=>G("GET",`/projects/${J}/comments`)},sessions:{list:(J)=>G("GET","/sessions",void 0,J),get:(J)=>G("GET",`/sessions/${J}`)},health:{check:()=>G("GET","/health")},gateway:{status:()=>G("GET","/gateway/status"),send:(J)=>G("POST","/gateway/send",J)}}}var tw=process.env.ORC_HOME??eA(Dv(),".orc"),xX0=eA(tw,"daemon.log"),bX=eA(tw,"daemon.pid");function Nv(){Gv(eA(tw,"logs"),{recursive:!0})}function aA(){try{return Number(Jv(bX,"utf-8").trim())}catch{return null}}function Wv(){Av(bX,String(process.pid))}function Vj(){try{V$("fs").unlinkSync(bX)}catch{}}function Pj(){let $=new $$("daemon").description("Run the API + scheduler + file watchers + gateway as one persistent process");return $.command("start",{isDefault:!0}).description("Start the daemon (use global --port / --host / --db / --secret to configure)").action(async()=>{Nv();let w=aA();if(w)try{process.kill(w,0),console.error(`[orc] daemon already running (pid ${w}). Use: orc daemon stop`),process.exit(1)}catch{}let E=O0();Wv(),await Promise.resolve().then(() => (P9(),V9)),console.log(`[orc] home ${tw}`),console.log(`[orc] db ${E.db.path}`),console.log(`[orc] API http://${E.api.host}:${E.api.port}`),console.log(`[orc] pid ${process.pid} -> ${bX}`),await rL(),await M3(),await PN(),console.log(`[orc] Scheduler + watchers + gateway active. Ctrl+C to stop.
561
+ deps: ${E}}`};var Lt={keyword:"dependencies",type:"object",schemaType:"object",error:NK.error,code($){let[w,E]=Ft($);GK($,w),AK($,E)}};function Ft({schema:$}){let w={},E={};for(let X in $){if(X==="__proto__")continue;let G=Array.isArray($[X])?w:E;G[X]=$[X]}return[w,E]}function GK($,w=$.schema){let{gen:E,data:X,it:G}=$;if(Object.keys(w).length===0)return;let A=E.let("missing");for(let N in w){let D=w[N];if(D.length===0)continue;let O=(0,ON.propertyInData)(E,X,N,G.opts.ownProperties);if($.setParams({property:N,depsCount:D.length,deps:D.join(", ")}),G.allErrors)E.if(O,()=>{for(let W of D)(0,ON.checkReportMissingProp)($,W)});else E.if(L9._`${O} && (${(0,ON.checkMissingProp)($,D,A)})`),(0,ON.reportMissingProp)($,A),E.else()}}NK.validatePropertyDeps=GK;function AK($,w=$.schema){let{gen:E,data:X,keyword:G,it:A}=$,N=E.name("valid");for(let D in w){if((0,Ht.alwaysValidSchema)(A,w[D]))continue;E.if((0,ON.propertyInData)(E,X,D,A.opts.ownProperties),()=>{let O=$.subschema({keyword:G,schemaProp:D},N);$.mergeValidEvaluated(O,N)},()=>E.var(N,!0)),$.ok(N)}}NK.validateSchemaDeps=AK;NK.default=Lt});var YK=_((UK)=>{Object.defineProperty(UK,"__esModule",{value:!0});var JK=J0(),Tt=T0(),Rt={message:"property name must be valid",params:({params:$})=>JK._`{propertyName: ${$.propertyName}}`},zt={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Rt,code($){let{gen:w,schema:E,data:X,it:G}=$;if((0,Tt.alwaysValidSchema)(G,E))return;let A=w.name("valid");w.forIn("key",X,(N)=>{$.setParams({propertyName:N}),$.subschema({keyword:"propertyNames",data:N,dataTypes:["string"],propertyName:N,compositeRule:!0},A),w.if((0,JK.not)(A),()=>{if($.error(!0),!G.allErrors)w.break()})}),$.ok(A)}};UK.default=zt});var F9=_((HK)=>{Object.defineProperty(HK,"__esModule",{value:!0});var TO=Iw(),rw=J0(),It=qE(),RO=T0(),Qt={message:"must NOT have additional properties",params:({params:$})=>rw._`{additionalProperty: ${$.additionalProperty}}`},Kt={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Qt,code($){let{gen:w,schema:E,parentSchema:X,data:G,errsCount:A,it:N}=$;if(!A)throw Error("ajv implementation error");let{allErrors:D,opts:O}=N;if(N.props=!0,O.removeAdditional!=="all"&&(0,RO.alwaysValidSchema)(N,E))return;let W=(0,TO.allSchemaProperties)(X.properties),J=(0,TO.allSchemaProperties)(X.patternProperties);Y(),$.ok(rw._`${A} === ${It.default.errors}`);function Y(){w.forIn("key",G,(M)=>{if(!W.length&&!J.length)F(M);else w.if(H(M),()=>F(M))})}function H(M){let R;if(W.length>8){let B=(0,RO.schemaRefOrVal)(N,X.properties,"properties");R=(0,TO.isOwnProperty)(w,B,M)}else if(W.length)R=(0,rw.or)(...W.map((B)=>rw._`${M} === ${B}`));else R=rw.nil;if(J.length)R=(0,rw.or)(R,...J.map((B)=>rw._`${(0,TO.usePattern)($,B)}.test(${M})`));return(0,rw.not)(R)}function L(M){w.code(rw._`delete ${G}[${M}]`)}function F(M){if(O.removeAdditional==="all"||O.removeAdditional&&E===!1){L(M);return}if(E===!1){if($.setParams({additionalProperty:M}),$.error(),!D)w.break();return}if(typeof E=="object"&&!(0,RO.alwaysValidSchema)(N,E)){let R=w.name("valid");if(O.removeAdditional==="failing")j(M,R,!1),w.if((0,rw.not)(R),()=>{$.reset(),L(M)});else if(j(M,R),!D)w.if((0,rw.not)(R),()=>w.break())}}function j(M,R,B){let I={keyword:"additionalProperties",dataProp:M,dataPropType:RO.Type.Str};if(B===!1)Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(I,R)}}};HK.default=Kt});var MK=_((jK)=>{Object.defineProperty(jK,"__esModule",{value:!0});var Pt=lA(),LK=Iw(),j9=T0(),FK=F9(),qt={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,parentSchema:X,data:G,it:A}=$;if(A.opts.removeAdditional==="all"&&X.additionalProperties===void 0)FK.default.code(new Pt.KeywordCxt(A,FK.default,"additionalProperties"));let N=(0,LK.allSchemaProperties)(E);for(let Y of N)A.definedProperties.add(Y);if(A.opts.unevaluated&&N.length&&A.props!==!0)A.props=j9.mergeEvaluated.props(w,(0,j9.toHash)(N),A.props);let D=N.filter((Y)=>!(0,j9.alwaysValidSchema)(A,E[Y]));if(D.length===0)return;let O=w.name("valid");for(let Y of D){if(W(Y))J(Y);else{if(w.if((0,LK.propertyInData)(w,G,Y,A.opts.ownProperties)),J(Y),!A.allErrors)w.else().var(O,!0);w.endIf()}$.it.definedProperties.add(Y),$.ok(O)}function W(Y){return A.opts.useDefaults&&!A.compositeRule&&E[Y].default!==void 0}function J(Y){$.subschema({keyword:"properties",schemaProp:Y,dataProp:Y},O)}}};jK.default=qt});var IK=_((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});var TK=Iw(),zO=J0(),RK=T0(),zK=T0(),kt={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,data:X,parentSchema:G,it:A}=$,{opts:N}=A,D=(0,TK.allSchemaProperties)(E),O=D.filter((j)=>(0,RK.alwaysValidSchema)(A,E[j]));if(D.length===0||O.length===D.length&&(!A.opts.unevaluated||A.props===!0))return;let W=N.strictSchema&&!N.allowMatchingProperties&&G.properties,J=w.name("valid");if(A.props!==!0&&!(A.props instanceof zO.Name))A.props=(0,zK.evaluatedPropsToName)(w,A.props);let{props:Y}=A;H();function H(){for(let j of D){if(W)L(j);if(A.allErrors)F(j);else w.var(J,!0),F(j),w.if(J)}}function L(j){for(let M in W)if(new RegExp(j).test(M))(0,RK.checkStrictMode)(A,`property ${M} matches pattern ${j} (use allowMatchingProperties)`)}function F(j){w.forIn("key",X,(M)=>{w.if(zO._`${(0,TK.usePattern)($,j)}.test(${M})`,()=>{let R=O.includes(j);if(!R)$.subschema({keyword:"patternProperties",schemaProp:j,dataProp:M,dataPropType:zK.Type.Str},J);if(A.opts.unevaluated&&Y!==!0)w.assign(zO._`${Y}[${M}]`,!0);else if(!R&&!A.allErrors)w.if((0,zO.not)(J),()=>w.break())})})}}};BK.default=kt});var KK=_((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});var _t=T0(),Zt={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:E,it:X}=$;if((0,_t.alwaysValidSchema)(X,E)){$.fail();return}let G=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),$.failResult(G,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};QK.default=Zt});var PK=_((VK)=>{Object.defineProperty(VK,"__esModule",{value:!0});var ft=Iw(),vt={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ft.validateUnion,error:{message:"must match a schema in anyOf"}};VK.default=vt});var SK=_((qK)=>{Object.defineProperty(qK,"__esModule",{value:!0});var BO=J0(),yt=T0(),gt={message:"must match exactly one schema in oneOf",params:({params:$})=>BO._`{passingSchemas: ${$.passing}}`},ut={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gt,code($){let{gen:w,schema:E,parentSchema:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(G.opts.discriminator&&X.discriminator)return;let A=E,N=w.let("valid",!1),D=w.let("passing",null),O=w.name("_valid");$.setParams({passing:D}),w.block(W),$.result(N,()=>$.reset(),()=>$.error(!0));function W(){A.forEach((J,Y)=>{let H;if((0,yt.alwaysValidSchema)(G,J))w.var(O,!0);else H=$.subschema({keyword:"oneOf",schemaProp:Y,compositeRule:!0},O);if(Y>0)w.if(BO._`${O} && ${N}`).assign(N,!1).assign(D,BO._`[${D}, ${Y}]`).else();w.if(O,()=>{if(w.assign(N,!0),w.assign(D,Y),H)$.mergeEvaluated(H,BO.Name)})})}}};qK.default=ut});var bK=_((kK)=>{Object.defineProperty(kK,"__esModule",{value:!0});var ht=T0(),ct={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:E,it:X}=$;if(!Array.isArray(E))throw Error("ajv implementation error");let G=w.name("valid");E.forEach((A,N)=>{if((0,ht.alwaysValidSchema)(X,A))return;let D=$.subschema({keyword:"allOf",schemaProp:N},G);$.ok(G),$.mergeEvaluated(D)})}};kK.default=ct});var fK=_((CK)=>{Object.defineProperty(CK,"__esModule",{value:!0});var IO=J0(),ZK=T0(),tt={message:({params:$})=>IO.str`must match "${$.ifClause}" schema`,params:({params:$})=>IO._`{failingKeyword: ${$.ifClause}}`},ot={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:tt,code($){let{gen:w,parentSchema:E,it:X}=$;if(E.then===void 0&&E.else===void 0)(0,ZK.checkStrictMode)(X,'"if" without "then" and "else" is ignored');let G=_K(X,"then"),A=_K(X,"else");if(!G&&!A)return;let N=w.let("valid",!0),D=w.name("_valid");if(O(),$.reset(),G&&A){let J=w.let("ifClause");$.setParams({ifClause:J}),w.if(D,W("then",J),W("else",J))}else if(G)w.if(D,W("then"));else w.if((0,IO.not)(D),W("else"));$.pass(N,()=>$.error(!0));function O(){let J=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},D);$.mergeEvaluated(J)}function W(J,Y){return()=>{let H=$.subschema({keyword:J},D);if(w.assign(N,D),$.mergeValidEvaluated(H,N),Y)w.assign(Y,IO._`${J}`);else $.setParams({ifClause:J})}}}};function _K($,w){let E=$.schema[w];return E!==void 0&&!(0,ZK.alwaysValidSchema)($,E)}CK.default=ot});var xK=_((vK)=>{Object.defineProperty(vK,"__esModule",{value:!0});var it=T0(),pt={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:E}){if(w.if===void 0)(0,it.checkStrictMode)(E,`"${$}" without "if" is ignored`)}};vK.default=pt});var gK=_((yK)=>{Object.defineProperty(yK,"__esModule",{value:!0});var lt=Y9(),st=aQ(),at=H9(),et=wK(),$o=XK(),wo=WK(),Eo=YK(),Xo=F9(),Go=MK(),Ao=IK(),No=KK(),Do=PK(),Oo=SK(),Wo=bK(),Jo=fK(),Uo=xK();function Yo($=!1){let w=[No.default,Do.default,Oo.default,Wo.default,Jo.default,Uo.default,Eo.default,Xo.default,wo.default,Go.default,Ao.default];if($)w.push(st.default,et.default);else w.push(lt.default,at.default);return w.push($o.default),w}yK.default=Yo});var nK=_((uK)=>{Object.defineProperty(uK,"__esModule",{value:!0});var A$=J0(),Lo={message:({schemaCode:$})=>A$.str`must match format "${$}"`,params:({schemaCode:$})=>A$._`{format: ${$}}`},Fo={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Lo,code($,w){let{gen:E,data:X,$data:G,schema:A,schemaCode:N,it:D}=$,{opts:O,errSchemaPath:W,schemaEnv:J,self:Y}=D;if(!O.validateFormats)return;if(G)H();else L();function H(){let F=E.scopeValue("formats",{ref:Y.formats,code:O.code.formats}),j=E.const("fDef",A$._`${F}[${N}]`),M=E.let("fType"),R=E.let("format");E.if(A$._`typeof ${j} == "object" && !(${j} instanceof RegExp)`,()=>E.assign(M,A$._`${j}.type || "string"`).assign(R,A$._`${j}.validate`),()=>E.assign(M,A$._`"string"`).assign(R,j)),$.fail$data((0,A$.or)(B(),I()));function B(){if(O.strictSchema===!1)return A$.nil;return A$._`${N} && !${R}`}function I(){let C=J.$async?A$._`(${j}.async ? await ${R}(${X}) : ${R}(${X}))`:A$._`${R}(${X})`,v=A$._`(typeof ${R} == "function" ? ${C} : ${R}.test(${X}))`;return A$._`${R} && ${R} !== true && ${M} === ${w} && !${v}`}}function L(){let F=Y.formats[A];if(!F){B();return}if(F===!0)return;let[j,M,R]=I(F);if(j===w)$.pass(C());function B(){if(O.strictSchema===!1){Y.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${A}" ignored in schema at path "${W}"`}}function I(v){let k=v instanceof RegExp?(0,A$.regexpCode)(v):O.code.formats?A$._`${O.code.formats}${(0,A$.getProperty)(A)}`:void 0,n=E.scopeValue("formats",{key:A,ref:v,code:k});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,A$._`${n}.validate`];return["string",v,n]}function C(){if(typeof F=="object"&&!(F instanceof RegExp)&&F.async){if(!J.$async)throw Error("async format in sync schema");return A$._`await ${R}(${X})`}return typeof M=="function"?A$._`${R}(${X})`:A$._`${R}.test(${X})`}}}};uK.default=Fo});var cK=_((hK)=>{Object.defineProperty(hK,"__esModule",{value:!0});var Mo=nK(),To=[Mo.default];hK.default=To});var oK=_((rK)=>{Object.defineProperty(rK,"__esModule",{value:!0});rK.contentVocabulary=rK.metadataVocabulary=void 0;rK.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];rK.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var pK=_((iK)=>{Object.defineProperty(iK,"__esModule",{value:!0});var Bo=jQ(),Io=rQ(),Qo=gK(),Ko=cK(),mK=oK(),Vo=[Bo.default,Io.default,(0,Qo.default)(),Ko.default,mK.metadataVocabulary,mK.contentVocabulary];iK.default=Vo});var aK=_((lK)=>{Object.defineProperty(lK,"__esModule",{value:!0});lK.DiscrError=void 0;var dK;(function($){$.Tag="tag",$.Mapping="mapping"})(dK||(lK.DiscrError=dK={}))});var wV=_(($V)=>{Object.defineProperty($V,"__esModule",{value:!0});var wG=J0(),M9=aK(),eK=GO(),qo=sA(),So=T0(),ko={message:({params:{discrError:$,tagName:w}})=>$===M9.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:E}})=>wG._`{error: ${$}, tag: ${E}, tagValue: ${w}}`},bo={keyword:"discriminator",type:"object",schemaType:"object",error:ko,code($){let{gen:w,data:E,schema:X,parentSchema:G,it:A}=$,{oneOf:N}=G;if(!A.opts.discriminator)throw Error("discriminator: requires discriminator option");let D=X.propertyName;if(typeof D!="string")throw Error("discriminator: requires propertyName");if(X.mapping)throw Error("discriminator: mapping is not supported");if(!N)throw Error("discriminator: requires oneOf keyword");let O=w.let("valid",!1),W=w.const("tag",wG._`${E}${(0,wG.getProperty)(D)}`);w.if(wG._`typeof ${W} == "string"`,()=>J(),()=>$.error(!1,{discrError:M9.DiscrError.Tag,tag:W,tagName:D})),$.ok(O);function J(){let L=H();w.if(!1);for(let F in L)w.elseIf(wG._`${W} === ${F}`),w.assign(O,Y(L[F]));w.else(),$.error(!1,{discrError:M9.DiscrError.Mapping,tag:W,tagName:D}),w.endIf()}function Y(L){let F=w.name("valid"),j=$.subschema({keyword:"oneOf",schemaProp:L},F);return $.mergeEvaluated(j,wG.Name),F}function H(){var L;let F={},j=R(G),M=!0;for(let C=0;C<N.length;C++){let v=N[C];if((v===null||v===void 0?void 0:v.$ref)&&!(0,So.schemaHasRulesButRef)(v,A.self.RULES)){let n=v.$ref;if(v=eK.resolveRef.call(A.self,A.schemaEnv.root,A.baseId,n),v instanceof eK.SchemaEnv)v=v.schema;if(v===void 0)throw new qo.default(A.opts.uriResolver,A.baseId,n)}let k=(L=v===null||v===void 0?void 0:v.properties)===null||L===void 0?void 0:L[D];if(typeof k!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${D}"`);M=M&&(j||R(v)),B(k,C)}if(!M)throw Error(`discriminator: "${D}" must be required`);return F;function R({required:C}){return Array.isArray(C)&&C.includes(D)}function B(C,v){if(C.const)I(C.const,v);else if(C.enum)for(let k of C.enum)I(k,v);else throw Error(`discriminator: "properties/${D}" must have "const" or "enum"`)}function I(C,v){if(typeof C!="string"||C in F)throw Error(`discriminator: "${D}" values must be unique strings`);F[C]=v}}}};$V.default=bo});var EV=_((d40,Zo)=>{Zo.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var R9=_((Xw,T9)=>{Object.defineProperty(Xw,"__esModule",{value:!0});Xw.MissingRefError=Xw.ValidationError=Xw.CodeGen=Xw.Name=Xw.nil=Xw.stringify=Xw.str=Xw._=Xw.KeywordCxt=Xw.Ajv=void 0;var Co=NQ(),fo=pK(),vo=wV(),XV=EV(),xo=["/properties"],QO="http://json-schema.org/draft-07/schema";class WN extends Co.default{_addVocabularies(){if(super._addVocabularies(),fo.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(vo.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(XV,xo):XV;this.addMetaSchema($,QO,!1),this.refs["http://json-schema.org/schema"]=QO}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(QO)?QO:void 0)}}Xw.Ajv=WN;T9.exports=Xw=WN;T9.exports.Ajv=WN;Object.defineProperty(Xw,"__esModule",{value:!0});Xw.default=WN;var yo=lA();Object.defineProperty(Xw,"KeywordCxt",{enumerable:!0,get:function(){return yo.KeywordCxt}});var EG=J0();Object.defineProperty(Xw,"_",{enumerable:!0,get:function(){return EG._}});Object.defineProperty(Xw,"str",{enumerable:!0,get:function(){return EG.str}});Object.defineProperty(Xw,"stringify",{enumerable:!0,get:function(){return EG.stringify}});Object.defineProperty(Xw,"nil",{enumerable:!0,get:function(){return EG.nil}});Object.defineProperty(Xw,"Name",{enumerable:!0,get:function(){return EG.Name}});Object.defineProperty(Xw,"CodeGen",{enumerable:!0,get:function(){return EG.CodeGen}});var go=EO();Object.defineProperty(Xw,"ValidationError",{enumerable:!0,get:function(){return go.default}});var uo=sA();Object.defineProperty(Xw,"MissingRefError",{enumerable:!0,get:function(){return uo.default}})});var HV=_((UV)=>{Object.defineProperty(UV,"__esModule",{value:!0});UV.formatNames=UV.fastFormats=UV.fullFormats=void 0;function DE($,w){return{validate:$,compare:w}}UV.fullFormats={date:DE(DV,Q9),time:DE(B9(!0),K9),"date-time":DE(GV(!0),WV),"iso-time":DE(B9(),OV),"iso-date-time":DE(GV(),JV),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:io,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:wm,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:po,int32:{type:"number",validate:ao},int64:{type:"number",validate:eo},float:{type:"number",validate:NV},double:{type:"number",validate:NV},password:!0,binary:!0};UV.fastFormats={...UV.fullFormats,date:DE(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Q9),time:DE(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,K9),"date-time":DE(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,WV),"iso-time":DE(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,OV),"iso-date-time":DE(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,JV),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};UV.formatNames=Object.keys(UV.fullFormats);function co($){return $%4===0&&($%100!==0||$%400===0)}var ro=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,to=[0,31,28,31,30,31,30,31,31,30,31,30,31];function DV($){let w=ro.exec($);if(!w)return!1;let E=+w[1],X=+w[2],G=+w[3];return X>=1&&X<=12&&G>=1&&G<=(X===2&&co(E)?29:to[X])}function Q9($,w){if(!($&&w))return;if($>w)return 1;if($<w)return-1;return 0}var z9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function B9($){return function(E){let X=z9.exec(E);if(!X)return!1;let G=+X[1],A=+X[2],N=+X[3],D=X[4],O=X[5]==="-"?-1:1,W=+(X[6]||0),J=+(X[7]||0);if(W>23||J>59||$&&!D)return!1;if(G<=23&&A<=59&&N<60)return!0;let Y=A-J*O,H=G-W*O-(Y<0?1:0);return(H===23||H===-1)&&(Y===59||Y===-1)&&N<61}}function K9($,w){if(!($&&w))return;let E=new Date("2020-01-01T"+$).valueOf(),X=new Date("2020-01-01T"+w).valueOf();if(!(E&&X))return;return E-X}function OV($,w){if(!($&&w))return;let E=z9.exec($),X=z9.exec(w);if(!(E&&X))return;if($=E[1]+E[2]+E[3],w=X[1]+X[2]+X[3],$>w)return 1;if($<w)return-1;return 0}var I9=/t|\s/i;function GV($){let w=B9($);return function(X){let G=X.split(I9);return G.length===2&&DV(G[0])&&w(G[1])}}function WV($,w){if(!($&&w))return;let E=new Date($).valueOf(),X=new Date(w).valueOf();if(!(E&&X))return;return E-X}function JV($,w){if(!($&&w))return;let[E,X]=$.split(I9),[G,A]=w.split(I9),N=Q9(E,G);if(N===void 0)return;return N||K9(X,A)}var oo=/\/|:/,mo=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function io($){return oo.test($)&&mo.test($)}var AV=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function po($){return AV.lastIndex=0,AV.test($)}var lo=-2147483648,so=2147483647;function ao($){return Number.isInteger($)&&$<=so&&$>=lo}function eo($){return Number.isInteger($)}function NV(){return!0}var $m=/[^\\]\\Z/;function wm($){if($m.test($))return!1;try{return new RegExp($),!0}catch(w){return!1}}});var FV=_((LV)=>{Object.defineProperty(LV,"__esModule",{value:!0});LV.formatLimitDefinition=void 0;var Xm=R9(),tw=J0(),N1=tw.operators,KO={formatMaximum:{okStr:"<=",ok:N1.LTE,fail:N1.GT},formatMinimum:{okStr:">=",ok:N1.GTE,fail:N1.LT},formatExclusiveMaximum:{okStr:"<",ok:N1.LT,fail:N1.GTE},formatExclusiveMinimum:{okStr:">",ok:N1.GT,fail:N1.LTE}},Gm={message:({keyword:$,schemaCode:w})=>tw.str`should be ${KO[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>tw._`{comparison: ${KO[$].okStr}, limit: ${w}}`};LV.formatLimitDefinition={keyword:Object.keys(KO),type:"string",schemaType:"string",$data:!0,error:Gm,code($){let{gen:w,data:E,schemaCode:X,keyword:G,it:A}=$,{opts:N,self:D}=A;if(!N.validateFormats)return;let O=new Xm.KeywordCxt(A,D.RULES.all.format.definition,"format");if(O.$data)W();else J();function W(){let H=w.scopeValue("formats",{ref:D.formats,code:N.code.formats}),L=w.const("fmt",tw._`${H}[${O.schemaCode}]`);$.fail$data((0,tw.or)(tw._`typeof ${L} != "object"`,tw._`${L} instanceof RegExp`,tw._`typeof ${L}.compare != "function"`,Y(L)))}function J(){let H=O.schema,L=D.formats[H];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${G}": format "${H}" does not define "compare" function`);let F=w.scopeValue("formats",{key:H,ref:L,code:N.code.formats?tw._`${N.code.formats}${(0,tw.getProperty)(H)}`:void 0});$.fail$data(Y(F))}function Y(H){return tw._`${H}.compare(${E}, ${X}) ${KO[G].fail} 0`}},dependencies:["format"]};var Am=($)=>{return $.addKeyword(LV.formatLimitDefinition),$};LV.default=Am});var RV=_((JN,TV)=>{Object.defineProperty(JN,"__esModule",{value:!0});var XG=HV(),Dm=FV(),q9=J0(),jV=new q9.Name("fullFormats"),Om=new q9.Name("fastFormats"),S9=($,w={keywords:!0})=>{if(Array.isArray(w))return MV($,w,XG.fullFormats,jV),$;let[E,X]=w.mode==="fast"?[XG.fastFormats,Om]:[XG.fullFormats,jV],G=w.formats||XG.formatNames;if(MV($,G,E,X),w.keywords)(0,Dm.default)($);return $};S9.get=($,w="full")=>{let X=(w==="fast"?XG.fastFormats:XG.fullFormats)[$];if(!X)throw Error(`Unknown format "${$}"`);return X};function MV($,w,E,X){var G,A;(G=(A=$.opts.code).formats)!==null&&G!==void 0||(A.formats=q9._`require("ajv-formats/dist/formats").${X}`);for(let N of w)$.addFormat(N,E[N])}TV.exports=JN=S9;Object.defineProperty(JN,"__esModule",{value:!0});JN.default=S9});function Wm(){let $=new zV.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return BV.default($),$}class k9{constructor($){this._ajv=$??Wm()}getValidator($){let w="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(E)=>{if(w(E))return{valid:!0,data:E,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}var zV,BV;var IV=T(()=>{zV=UN(R9(),1),BV=UN(RV(),1)});class b9{constructor($){this._server=$}requestStream($,w,E){return this._server.requestStream($,w,E)}createMessageStream($,w){let E=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!E?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let X=$.messages[$.messages.length-1],G=Array.isArray(X.content)?X.content:[X.content],A=G.some((W)=>W.type==="tool_result"),N=$.messages.length>1?$.messages[$.messages.length-2]:void 0,D=N?Array.isArray(N.content)?N.content:[N.content]:[],O=D.some((W)=>W.type==="tool_use");if(A){if(G.some((W)=>W.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!O)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(O){let W=new Set(D.filter((Y)=>Y.type==="tool_use").map((Y)=>Y.id)),J=new Set(G.filter((Y)=>Y.type==="tool_result").map((Y)=>Y.toolUseId));if(W.size!==J.size||![...W].every((Y)=>J.has(Y)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},nA,w)}elicitInputStream($,w){let E=this._server.getClientCapabilities(),X=$.mode??"form";switch(X){case"url":{if(!E?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!E?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let G=X==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:G},tX,w)}async getTask($,w){return this._server.getTask({taskId:$},w)}async getTaskResult($,w,E){return this._server.getTaskResult({taskId:$},w,E)}async listTasks($,w){return this._server.listTasks($?{cursor:$}:void 0,w)}async cancelTask($,w){return this._server.cancelTask({taskId:$},w)}}var QV=T(()=>{oX()});function KV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!$.tools?.call)throw Error(`${E} does not support task creation for tools/call (required for ${w})`);break;default:break}}function VV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${E} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${E} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}var _9;var PV=T(()=>{rz();oX();IV();z6();QV();_9=class _9 extends VU{constructor($,w){super(w);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(uA.options.map((E,X)=>[E,X])),this.isMessageIgnored=(E,X)=>{let G=this._loggingLevels.get(X);return G?this.LOG_LEVEL_SEVERITY.get(E)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new k9,this.setRequestHandler(c8,(E)=>this._oninitialize(E)),this.setNotificationHandler(r8,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(s8,async(E,X)=>{let G=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:A}=E.params,N=uA.safeParse(A);if(N.success)this._loggingLevels.set(G,N.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new b9(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=cz(this._capabilities,$)}setRequestHandler($,w){let X=R6($)?.method;if(!X)throw Error("Schema is missing a method literal");let G;if(nX(X)){let N=X;G=N._zod?.def?.value??N.value}else{let N=X;G=N._def?.value??N.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let N=async(D,O)=>{let W=sE(gA,D);if(!W.success){let L=W.error instanceof Error?W.error.message:String(W.error);throw new D0(F0.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:J}=W.data,Y=await Promise.resolve(w(D,O));if(J.task){let L=sE(cX,Y);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new D0(F0.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let H=sE(x6,Y);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new D0(F0.InvalidParams,`Invalid tools/call result: ${L}`)}return H.data};return super.setRequestHandler($,N)}return super.setRequestHandler($,w)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){VV(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;KV(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let w=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:Bz.includes(w)?w:y8,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},P6)}async createMessage($,w){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let E=$.messages[$.messages.length-1],X=Array.isArray(E.content)?E.content:[E.content],G=X.some((O)=>O.type==="tool_result"),A=$.messages.length>1?$.messages[$.messages.length-2]:void 0,N=A?Array.isArray(A.content)?A.content:[A.content]:[],D=N.some((O)=>O.type==="tool_use");if(G){if(X.some((O)=>O.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let O=new Set(N.filter((J)=>J.type==="tool_use").map((J)=>J.id)),W=new Set(X.filter((J)=>J.type==="tool_result").map((J)=>J.toolUseId));if(O.size!==W.size||![...O].every((J)=>W.has(J)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},a8,w);return this.request({method:"sampling/createMessage",params:$},nA,w)}async elicitInput($,w){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},tX,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},G=await this.request({method:"elicitation/create",params:X},tX,w);if(G.action==="accept"&&G.content&&X.requestedSchema)try{let N=this._jsonSchemaValidator.getValidator(X.requestedSchema)(G.content);if(!N.valid)throw new D0(F0.InvalidParams,`Elicitation response content does not match requested schema: ${N.errorMessage}`)}catch(A){if(A instanceof D0)throw A;throw new D0(F0.InternalError,`Error validating elicitation response: ${A instanceof Error?A.message:String(A)}`)}return G}}}createElicitationCompletionNotifier($,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:$}},w)}async listRoots($,w){return this.request({method:"roots/list",params:$},e8,w)}async sendLoggingMessage($,w){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,w))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});class Z9{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
562
+ `);if($===-1)return null;let w=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),Jm(w)}clear(){this._buffer=void 0}}function Jm($){return kz.parse(JSON.parse($))}function qV($){return JSON.stringify($)+`
563
+ `}var SV=T(()=>{oX()});import kV from"process";class C9{constructor($=kV.stdin,w=kV.stdout){this._stdin=$,this._stdout=w,this._readBuffer=new Z9,this._started=!1,this._ondata=(E)=>{this._readBuffer.append(E),this.processReadBuffer()},this._onerror=(E)=>{this.onerror?.(E)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((w)=>{let E=qV($);if(this._stdout.write(E))w();else this._stdout.once("drain",w)})}}var bV=T(()=>{SV()});function GG($){let w=$._def,E=w.typeName;if(E==="ZodObject"){let X=w.shape(),G={},A=[];for(let[N,D]of Object.entries(X)){G[N]=GG(D);let O=D._def;if(O.typeName!=="ZodOptional"&&O.typeName!=="ZodDefault")A.push(N)}return{type:"object",properties:G,...A.length?{required:A}:{}}}if(E==="ZodString")return{type:"string"};if(E==="ZodNumber")return{type:"number"};if(E==="ZodBoolean")return{type:"boolean"};if(E==="ZodArray")return{type:"array",items:GG(w.type)};if(E==="ZodEnum")return{type:"string",enum:w.values};if(E==="ZodOptional"||E==="ZodDefault")return GG(w.innerType);if(E==="ZodUnion")return{oneOf:w.options.map(GG)};return{}}function _V(){let $=new _9({name:"orc",version:"0.0.1"},{capabilities:{tools:{}}});return $.setRequestHandler(l8,async()=>({tools:_X.map((w)=>({name:w.name,description:w.description,inputSchema:GG(w.inputSchema)}))})),$.setRequestHandler(gA,async(w)=>{let{name:E,arguments:X}=w.params;f9.debug(`Tool call: ${E}`,X);try{let G=_X.find((D)=>D.name===E);if(!G)return{content:[{type:"text",text:`Unknown tool: ${E}`}],isError:!0};let A=G.inputSchema.safeParse(X??{});if(!A.success)return{content:[{type:"text",text:`Invalid args: ${A.error.message}`}],isError:!0};return{content:[{type:"text",text:await HA(E,A.data)}]}}catch(G){return f9.error(`Tool error: ${E}`,G),{content:[{type:"text",text:G instanceof Error?G.message:"Unknown error"}],isError:!0}}}),$}async function Um(){let $=_V(),w=new C9;await $.connect(w),f9.info("MCP server running on stdio")}var f9;var ZV=T(()=>{PV();bV();oX();z$();pD();f9=B0("mcp")});var CV={};OE(CV,{toolDefinitions:()=>_X,startStdioServer:()=>Um,executeTool:()=>HA,createMcpServer:()=>_V});var fV=T(async()=>{ZV();pD()});R$();RN();import{existsSync as Ym,statSync as Hm}from"fs";var z5=UN(R5(),1),{program:Xi,createCommand:Gi,createArgument:Ai,createOption:Ni,CommanderError:Di,InvalidArgumentError:Oi,InvalidOptionArgumentError:Wi,Command:E$,Argument:Ji,Option:Ui,Help:Yi}=z5.default;R$();fJ();import{mkdirSync as Tf,readFileSync as Rf,writeFileSync as zf}from"fs";import{homedir as Bf}from"os";import{join as E6}from"path";cE();z$();J$();Q$();function x$($,w,E,X,G,A,N,D){return x$.fromTZ(x$.tp($,w,E,X,G,A,N),D)}x$.fromTZISO=($,w,E)=>x$.fromTZ(D_($,w),E);x$.fromTZ=function($,w){let E=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),X=vJ($.tz,E),G=new Date(E.getTime()-X),A=vJ($.tz,G);if(A-X===0)return G;{let N=new Date(E.getTime()-A),D=vJ($.tz,N);if(D-A===0)return N;if(!w&&D-A>0)return N;if(w)throw Error("Invalid date passed to fromTZ()");return G}};x$.toTZ=function($,w){let E=$.toLocaleString("en-US",{timeZone:w}).replace(/[\u202f]/," "),X=new Date(E);return{y:X.getFullYear(),m:X.getMonth()+1,d:X.getDate(),h:X.getHours(),i:X.getMinutes(),s:X.getSeconds(),tz:w}};x$.tp=($,w,E,X,G,A,N)=>({y:$,m:w,d:E,h:X,i:G,s:A,tz:N});function vJ($,w=new Date){let E=w.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],X=w.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${X} GMT`)-Date.parse(`${X} ${E}`)}function D_($,w){let E=new Date(Date.parse($));if(isNaN(E))throw Error("minitz: Invalid ISO8601 passed to parser.");let X=$.substring(9);return $.includes("Z")||X.includes("-")||X.includes("+")?x$.tp(E.getUTCFullYear(),E.getUTCMonth()+1,E.getUTCDate(),E.getUTCHours(),E.getUTCMinutes(),E.getUTCSeconds(),"Etc/UTC"):x$.tp(E.getFullYear(),E.getMonth()+1,E.getDate(),E.getHours(),E.getMinutes(),E.getSeconds(),w)}x$.minitz=x$;var xJ=32,iG=31|xJ,dL=[1,2,4,8,16],mL=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor($,w){this.pattern=$,this.timezone=w,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let $=this.pattern.replace(/\s+/g," ").split(" ");if($.length<5||$.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if($.length===5&&$.unshift("0"),$[3].indexOf("L")>=0&&($[3]=$[3].replace("L",""),this.lastDayOfMonth=!0),$[3]=="*"&&(this.starDOM=!0),$[4].length>=3&&($[4]=this.replaceAlphaMonths($[4])),$[5].length>=3&&($[5]=this.replaceAlphaDays($[5])),$[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let w=new Fw(new Date,this.timezone).getDate(!0);$[0]=$[0].replace("?",w.getSeconds().toString()),$[1]=$[1].replace("?",w.getMinutes().toString()),$[2]=$[2].replace("?",w.getHours().toString()),this.starDOM||($[3]=$[3].replace("?",w.getDate().toString())),$[4]=$[4].replace("?",(w.getMonth()+1).toString()),this.starDOW||($[5]=$[5].replace("?",w.getDay().toString()))}this.throwAtIllegalCharacters($),this.partToArray("second",$[0],0,1),this.partToArray("minute",$[1],0,1),this.partToArray("hour",$[2],0,1),this.partToArray("day",$[3],-1,1),this.partToArray("month",$[4],-1,1),this.partToArray("dayOfWeek",$[5],0,iG),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,w,E,X){let G=this[$],A=$==="day"&&this.lastDayOfMonth;if(w===""&&!A)throw TypeError("CronPattern: configuration entry "+$+" ("+w+") is empty, check for trailing spaces.");if(w==="*")return G.fill(X);let N=w.split(",");if(N.length>1)for(let D=0;D<N.length;D++)this.partToArray($,N[D],E,X);else w.indexOf("-")!==-1&&w.indexOf("/")!==-1?this.handleRangeWithStepping(w,$,E,X):w.indexOf("-")!==-1?this.handleRange(w,$,E,X):w.indexOf("/")!==-1?this.handleStepping(w,$,E,X):w!==""&&this.handleNumber(w,$,E,X)}throwAtIllegalCharacters($){for(let w=0;w<$.length;w++)if((w===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test($[w]))throw TypeError("CronPattern: configuration entry "+w+" ("+$[w]+") contains illegal characters.")}handleNumber($,w,E,X){let G=this.extractNth($,w),A=parseInt(G[0],10)+E;if(isNaN(A))throw TypeError("CronPattern: "+w+" is not a number: '"+$+"'");this.setPart(w,A,G[1]||X)}setPart($,w,E){if(!Object.prototype.hasOwnProperty.call(this,$))throw TypeError("CronPattern: Invalid part specified: "+$);if($==="dayOfWeek"){if(w===7&&(w=0),w<0||w>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+w);this.setNthWeekdayOfMonth(w,E);return}if($==="second"||$==="minute"){if(w<0||w>=60)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="hour"){if(w<0||w>=24)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="day"){if(w<0||w>=31)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="month"&&(w<0||w>=12))throw RangeError("CronPattern: Invalid value for "+$+": "+w);this[$][w]=E}handleRangeWithStepping($,w,E,X){let G=this.extractNth($,w),A=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(A===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,N,D,O]=A,W=parseInt(N,10)+E,J=parseInt(D,10)+E,Y=parseInt(O,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(J))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Y===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Y>this[w].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[w].length+")");if(W>J)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let H=W;H<=J;H+=Y)this.setPart(w,H,G[1]||X)}extractNth($,w){let E=$,X;if(E.includes("#")){if(w!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");X=E.split("#")[1],E=E.split("#")[0]}return[E,X]}handleRange($,w,E,X){let G=this.extractNth($,w),A=G[0].split("-");if(A.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let N=parseInt(A[0],10)+E,D=parseInt(A[1],10)+E;if(isNaN(N))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(N>D)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let O=N;O<=D;O++)this.setPart(w,O,G[1]||X)}handleStepping($,w,E,X){let G=this.extractNth($,w),A=G[0].split("/");if(A.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");A[0]===""&&(A[0]="*");let N=0;A[0]!=="*"&&(N=parseInt(A[0],10)+E);let D=parseInt(A[1],10);if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(D===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(D>this[w].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[w].length+")");for(let O=N;O<this[w].length;O+=D)this.setPart(w,O,G[1]||X)}replaceAlphaDays($){return $.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths($){return $.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames($){let w=$.trim().toLowerCase();return w==="@yearly"||w==="@annually"?"0 0 1 1 *":w==="@monthly"?"0 0 1 * *":w==="@weekly"?"0 0 * * 0":w==="@daily"?"0 0 * * *":w==="@hourly"?"0 * * * *":$}setNthWeekdayOfMonth($,w){if(typeof w!="number"&&w==="L")this.dayOfWeek[$]=this.dayOfWeek[$]|xJ;else if(w===iG)this.dayOfWeek[$]=iG;else if(w<6&&w>0)this.dayOfWeek[$]=this.dayOfWeek[$]|dL[w-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${w}, Type: ${typeof w}`)}},iL=[31,28,31,30,31,30,31,31,30,31,30,31],TE=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],Fw=class ${tz;ms;second;minute;hour;day;month;year;constructor(w,E){if(this.tz=E,w&&w instanceof Date)if(!isNaN(w))this.fromDate(w);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(w===void 0)this.fromDate(new Date);else if(w&&typeof w=="string")this.fromString(w);else if(w instanceof $)this.fromCronDate(w);else throw TypeError("CronDate: Invalid type ("+typeof w+") passed to CronDate constructor")}isNthWeekdayOfMonth(w,E,X,G){let A=new Date(Date.UTC(w,E,X)).getUTCDay(),N=0;for(let D=1;D<=X;D++)new Date(Date.UTC(w,E,D)).getUTCDay()===A&&N++;if(G&iG&&dL[N-1]&G)return!0;if(G&xJ){let D=new Date(Date.UTC(w,E+1,0)).getUTCDate();for(let O=X+1;O<=D;O++)if(new Date(Date.UTC(w,E,O)).getUTCDay()===A)return!1;return!0}return!1}fromDate(w){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes()+this.tz,this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),this.apply();else{let E=x$.toTZ(w,this.tz);this.ms=w.getMilliseconds(),this.second=E.s,this.minute=E.i,this.hour=E.h,this.day=E.d,this.month=E.m-1,this.year=E.y}else this.ms=w.getMilliseconds(),this.second=w.getSeconds(),this.minute=w.getMinutes(),this.hour=w.getHours(),this.day=w.getDate(),this.month=w.getMonth(),this.year=w.getFullYear()}fromCronDate(w){this.tz=w.tz,this.year=w.year,this.month=w.month,this.day=w.day,this.hour=w.hour,this.minute=w.minute,this.second=w.second,this.ms=w.ms}apply(){if(this.month>11||this.day>iL[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let w=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes(),this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),!0}else return!1}fromString(w){if(typeof this.tz=="number"){let E=x$.fromTZISO(w);this.ms=E.getUTCMilliseconds(),this.second=E.getUTCSeconds(),this.minute=E.getUTCMinutes(),this.hour=E.getUTCHours(),this.day=E.getUTCDate(),this.month=E.getUTCMonth(),this.year=E.getUTCFullYear(),this.apply()}else return this.fromDate(x$.fromTZISO(w,this.tz))}findNext(w,E,X,G){let A=this[E],N;X.lastDayOfMonth&&(this.month!==1?N=iL[this.month]:N=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let D=!X.starDOW&&E=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let O=this[E]+G;O<X[E].length;O++){let W=X[E][O];if(E==="day"&&X.lastDayOfMonth&&O-G==N&&(W=1),E==="day"&&!X.starDOW){let J=X.dayOfWeek[(D+(O-G-1))%7];if(J&&J&iG)J=this.isNthWeekdayOfMonth(this.year,this.month,O-G,J)?1:0;else if(J)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${J}`);w.legacyMode&&!X.starDOM?W=W||J:W=W&&J}if(W)return this[E]=O-G,A!==this[E]?2:1}return 3}recurse(w,E,X){let G=this.findNext(E,TE[X][0],w,TE[X][2]);if(G>1){let A=X+1;for(;A<TE.length;)this[TE[A][0]]=-TE[A][2],A++;if(G===3)return this[TE[X][1]]++,this[TE[X][0]]=-TE[X][2],this.apply(),this.recurse(w,E,0);if(this.apply())return this.recurse(w,E,X-1)}return X+=1,X>=TE.length?this:this.year>=3000?null:this.recurse(w,E,X)}increment(w,E,X){return this.second+=E.interval!==void 0&&E.interval>1&&X?E.interval:1,this.ms=0,this.apply(),this.recurse(w,E,0)}getDate(w){return w||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):x$.fromTZ(x$.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function O_($){if($===void 0&&($={}),delete $.name,$.legacyMode=$.legacyMode===void 0?!0:$.legacyMode,$.paused=$.paused===void 0?!1:$.paused,$.maxRuns=$.maxRuns===void 0?1/0:$.maxRuns,$.catch=$.catch===void 0?!1:$.catch,$.interval=$.interval===void 0?0:parseInt($.interval.toString(),10),$.utcOffset=$.utcOffset===void 0?void 0:parseInt($.utcOffset.toString(),10),$.unref=$.unref===void 0?!1:$.unref,$.startAt&&($.startAt=new Fw($.startAt,$.timezone)),$.stopAt&&($.stopAt=new Fw($.stopAt,$.timezone)),$.interval!==null){if(isNaN($.interval))throw Error("CronOptions: Supplied value for interval is not a number");if($.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if($.utcOffset!==void 0){if(isNaN($.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if($.utcOffset<-870||$.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if($.utcOffset!==void 0&&$.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if($.unref!==!0&&$.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return $}function mG($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function W_($){return mG($)}function J_($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var pL=30000,ID=[],yJ=class{name;options;_states;fn;constructor($,w,E){let X,G;if(mG(w))G=w;else if(typeof w=="object")X=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(mG(E))G=E;else if(typeof E=="object")X=E;else if(E!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=X?.name,this.options=O_(X),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:X?X.maxRuns:void 0,paused:X?X.paused:!1,pattern:new mL("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new Fw($,this.options.timezone||this.options.utcOffset):this._states.pattern=new mL($,this.options.timezone),this.name){if(ID.find((A)=>A.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");ID.push(this)}return G!==void 0&&W_(G)&&(this.fn=G,this.schedule()),this}nextRun($){let w=this._next($);return w?w.getDate(!1):null}nextRuns($,w){this._states.maxRuns!==void 0&&$>this._states.maxRuns&&($=this._states.maxRuns);let E=[],X=w||this._states.currentRun||void 0;for(;$--&&(X=this.nextRun(X));)E.push(X);return E}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),w=!this._states.paused,E=this.fn!==void 0,X=!this._states.kill;return w&&E&&X&&$!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext($){let w=this._next($);return w?$ instanceof Fw||$ instanceof Date?w.getTime()-$.getTime():w.getTime()-new Fw($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=ID.indexOf(this);$>=0&&ID.splice($,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule($){if($&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");$&&(this.fn=$);let w=this.msToNext(),E=this.nextRun(this._states.currentRun);return w==null||isNaN(w)||E===null?this:(w>pL&&(w=pL),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(E),w),this._states.currentTimeout&&this.options.unref&&J_(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new Fw(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(w){mG(this.options.catch)&&this.options.catch(w,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Fw($,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger($){let w=new Date,E=!this._states.paused&&w.getTime()>=$.getTime(),X=this._states.blocking&&this.options.protect;E&&!X?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):E&&X&&mG(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let w=!!($||this._states.currentRun),E=!1;!$&&this.options.startAt&&this.options.interval&&([$,w]=this._calculatePreviousRun($,w),E=!$),$=new Fw($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let X=this._states.once||new Fw($,this.options.timezone||this.options.utcOffset);return!E&&X!==this._states.once&&(X=X.increment(this._states.pattern,this.options,w)),this._states.once&&this._states.once.getTime()<=$.getTime()||X===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&X.getTime()>=this.options.stopAt.getTime()?null:X}_calculatePreviousRun($,w){let E=new Fw(void 0,this.options.timezone||this.options.utcOffset),X=$;if(this.options.startAt.getTime()<=E.getTime()){X=this.options.startAt;let G=X.getTime()+this.options.interval*1000;for(;G<=E.getTime();)X=new Fw(X,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=X.getTime()+this.options.interval*1000;w=!0}return X===null&&(X=void 0),[X,w]}};f$();cE();var RE=B0("runner:scheduler"),BX=new Map,tE=new Map;async function lL(){let w=await f().query.jobs.findMany({where:V(I0.enabled,!0)}),E=new Set(["cron","one-shot","watch","webhook","manual","bridge-msg"]),X=w.filter((G)=>!E.has(G.trigger_type));if(X.length>0)RE.warn(`${X.length} job(s) have an unsupported trigger type and will not fire: ${X.map((G)=>`${G.name} (${G.trigger_type})`).join(", ")}. Use 'cron' with a 6-field expression (e.g. '*/30 * * * * *') for sub-minute intervals.`);for(let G of w)if(G.trigger_type==="cron"&&G.cron_expr)U_(G.id,G.name,G.cron_expr);else if(G.trigger_type==="one-shot"&&G.run_at)Y_(G.id,G.name,G.run_at,G.run_count);RE.info(`Scheduler started. ${BX.size} cron + ${tE.size} one-shot jobs scheduled.`)}function U_($,w,E){if(BX.has($))BX.get($)?.stop();let X=new yJ(E,async()=>{RE.info(`Cron trigger: ${w}`);try{await Nw({jobId:$,triggerBy:"cron"})}catch(G){RE.error(`Cron job failed: ${w}`,G)}});BX.set($,X),RE.info(`Scheduled cron job: ${w} (${E})`)}function Y_($,w,E,X){if(X>0)return;if(tE.has($))clearTimeout(tE.get($)),tE.delete($);let G=Math.max(0,E.getTime()-Date.now()),A=setTimeout(async()=>{tE.delete($),RE.info(`One-shot trigger: ${w}`);try{await Nw({jobId:$,triggerBy:"one-shot"})}catch(D){RE.error(`One-shot job failed: ${w}`,D)}},G);tE.set($,A);let N=G<1000?"now":`in ${Math.round(G/1000)}s`;RE.info(`Scheduled one-shot job: ${w} (${N})`)}function sL(){for(let[,$]of BX)$.stop();BX.clear();for(let[,$]of tE)clearTimeout($);tE.clear(),RE.info("Scheduler stopped.")}WX();R$();B$();z$();J$();Q$();PD();var e$0=B0("runner:task-loop");z$();J$();Q$();import{stat as c_}from"fs";import{stat as r_,readdir as t_}from"fs/promises";import{EventEmitter as o_}from"events";import*as Y0 from"path";import{stat as H_,lstat as w3,readdir as L_,realpath as F_}from"fs/promises";import{Readable as j_}from"stream";import{resolve as E3,relative as M_,join as T_,sep as R_}from"path";var Dw={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},cJ={root:".",fileFilter:($)=>!0,directoryFilter:($)=>!0,type:Dw.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(cJ);var N3="READDIRP_RECURSIVE_ERROR",z_=new Set(["ENOENT","EPERM","EACCES","ELOOP",N3]),X3=[Dw.DIR_TYPE,Dw.EVERYTHING_TYPE,Dw.FILE_DIR_TYPE,Dw.FILE_TYPE],B_=new Set([Dw.DIR_TYPE,Dw.EVERYTHING_TYPE,Dw.FILE_DIR_TYPE]),I_=new Set([Dw.EVERYTHING_TYPE,Dw.FILE_DIR_TYPE,Dw.FILE_TYPE]),Q_=($)=>z_.has($.code),K_=process.platform==="win32",G3=($)=>!0,A3=($)=>{if($===void 0)return G3;if(typeof $==="function")return $;if(typeof $==="string"){let w=$.trim();return(E)=>E.basename===w}if(Array.isArray($)){let w=$.map((E)=>E.trim());return(E)=>w.some((X)=>E.basename===X)}return G3};class D3 extends j_{constructor($={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:$.highWaterMark});let w={...cJ,...$},{root:E,type:X}=w;this._fileFilter=A3(w.fileFilter),this._directoryFilter=A3(w.directoryFilter);let G=w.lstat?w3:H_;if(K_)this._stat=(A)=>G(A,{bigint:!0});else this._stat=G;this._maxDepth=w.depth??cJ.depth,this._wantsDir=X?B_.has(X):!1,this._wantsFile=X?I_.has(X):!1,this._wantsEverything=X===Dw.EVERYTHING_TYPE,this._root=E3(E),this._isDirent=!w.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(E,1)],this.reading=!1,this.parent=void 0}async _read($){if(this.reading)return;this.reading=!0;try{while(!this.destroyed&&$>0){let w=this.parent,E=w&&w.files;if(E&&E.length>0){let{path:X,depth:G}=w,A=E.splice(0,$).map((D)=>this._formatEntry(D,X)),N=await Promise.all(A);for(let D of N){if(!D)continue;if(this.destroyed)return;let O=await this._getEntryType(D);if(O==="directory"&&this._directoryFilter(D)){if(G<=this._maxDepth)this.parents.push(this._exploreDir(D.fullPath,G+1));if(this._wantsDir)this.push(D),$--}else if((O==="file"||this._includeAsFile(D))&&this._fileFilter(D)){if(this._wantsFile)this.push(D),$--}}}else{let X=this.parents.pop();if(!X){this.push(null);break}if(this.parent=await X,this.destroyed)return}}}catch(w){this.destroy(w)}finally{this.reading=!1}}async _exploreDir($,w){let E;try{E=await L_($,this._rdOptions)}catch(X){this._onError(X)}return{files:E,depth:w,path:$}}async _formatEntry($,w){let E,X=this._isDirent?$.name:$;try{let G=E3(T_(w,X));E={path:M_(this._root,G),fullPath:G,basename:X},E[this._statsProp]=this._isDirent?$:await this._stat(G)}catch(G){this._onError(G);return}return E}_onError($){if(Q_($)&&!this.destroyed)this.emit("warn",$);else this.destroy($)}async _getEntryType($){if(!$&&this._statsProp in $)return"";let w=$[this._statsProp];if(w.isFile())return"file";if(w.isDirectory())return"directory";if(w&&w.isSymbolicLink()){let E=$.fullPath;try{let X=await F_(E),G=await w3(X);if(G.isFile())return"file";if(G.isDirectory()){let A=X.length;if(E.startsWith(X)&&E.substr(A,1)===R_){let N=Error(`Circular symlink detected: "${E}" points to "${X}"`);return N.code=N3,this._onError(N)}return"directory"}}catch(X){return this._onError(X),""}}}_includeAsFile($){let w=$&&$[this._statsProp];return w&&this._wantsEverything&&!w.isDirectory()}}function O3($,w={}){let E=w.entryType||w.type;if(E==="both")E=Dw.FILE_DIR_TYPE;if(E)w.type=E;if(!$)throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");else if(typeof $!=="string")throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if(E&&!X3.includes(E))throw Error(`readdirp: Invalid type passed. Use one of ${X3.join(", ")}`);return w.root=$,new D3(w)}import{watchFile as V_,unwatchFile as W3,watch as P_}from"fs";import{open as q_,stat as U3,lstat as S_,realpath as rJ}from"fs/promises";import*as o0 from"path";import{type as k_}from"os";var b_="data",mJ="end",Y3="close",bD=()=>{};var _D=process.platform,iJ=_D==="win32",__=_D==="darwin",Z_=_D==="linux",C_=_D==="freebsd",H3=k_()==="OS400",g0={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Cw=g0,f_="watch",v_={lstat:S_,stat:U3},I1="listeners",qD="errHandlers",QX="rawEmitters",x_=[I1,qD,QX],y_=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),g_=($)=>y_.has(o0.extname($).slice(1).toLowerCase()),oJ=($,w)=>{if($ instanceof Set)$.forEach(w);else w($)},lG=($,w,E)=>{let X=$[w];if(!(X instanceof Set))$[w]=X=new Set([X]);X.add(E)},u_=($)=>(w)=>{let E=$[w];if(E instanceof Set)E.clear();else delete $[w]},sG=($,w,E)=>{let X=$[w];if(X instanceof Set)X.delete(E);else if(X===E)delete $[w]},L3=($)=>$ instanceof Set?$.size===0:!$,SD=new Map;function J3($,w,E,X,G){let A=(N,D)=>{if(E($),G(N,D,{watchedPath:$}),D&&$!==D)kD(o0.resolve($,D),I1,o0.join($,D))};try{return P_($,{persistent:w.persistent},A)}catch(N){X(N);return}}var kD=($,w,E,X,G)=>{let A=SD.get($);if(!A)return;oJ(A[w],(N)=>{N(E,X,G)})},n_=($,w,E,X)=>{let{listener:G,errHandler:A,rawEmitter:N}=X,D=SD.get(w),O;if(!E.persistent){if(O=J3($,E,G,A,N),!O)return;return O.close.bind(O)}if(D)lG(D,I1,G),lG(D,qD,A),lG(D,QX,N);else{if(O=J3($,E,kD.bind(null,w,I1),A,kD.bind(null,w,QX)),!O)return;O.on(Cw.ERROR,async(W)=>{let J=kD.bind(null,w,qD);if(D)D.watcherUnusable=!0;if(iJ&&W.code==="EPERM")try{await(await q_($,"r")).close(),J(W)}catch(Y){}else J(W)}),D={listeners:G,errHandlers:A,rawEmitters:N,watcher:O},SD.set(w,D)}return()=>{if(sG(D,I1,G),sG(D,qD,A),sG(D,QX,N),L3(D.listeners))D.watcher.close(),SD.delete(w),x_.forEach(u_(D)),D.watcher=void 0,Object.freeze(D)}},tJ=new Map,h_=($,w,E,X)=>{let{listener:G,rawEmitter:A}=X,N=tJ.get(w),D=N&&N.options;if(D&&(D.persistent<E.persistent||D.interval>E.interval))W3(w),N=void 0;if(N)lG(N,I1,G),lG(N,QX,A);else N={listeners:G,rawEmitters:A,options:E,watcher:V_(w,E,(O,W)=>{oJ(N.rawEmitters,(Y)=>{Y(Cw.CHANGE,w,{curr:O,prev:W})});let J=O.mtimeMs;if(O.size!==W.size||J>W.mtimeMs||J===0)oJ(N.listeners,(Y)=>Y($,O))})},tJ.set(w,N);return()=>{if(sG(N,I1,G),sG(N,QX,A),L3(N.listeners))tJ.delete(w),W3(w),N.options=N.watcher=void 0,Object.freeze(N)}};class pJ{constructor($){this.fsw=$,this._boundHandleError=(w)=>$._handleError(w)}_watchWithNodeFs($,w){let E=this.fsw.options,X=o0.dirname($),G=o0.basename($);this.fsw._getWatchedDir(X).add(G);let N=o0.resolve($),D={persistent:E.persistent};if(!w)w=bD;let O;if(E.usePolling){let W=E.interval!==E.binaryInterval;D.interval=W&&g_(G)?E.binaryInterval:E.interval,O=h_($,N,D,{listener:w,rawEmitter:this.fsw._emitRaw})}else O=n_($,N,D,{listener:w,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return O}_handleFile($,w,E){if(this.fsw.closed)return;let X=o0.dirname($),G=o0.basename($),A=this.fsw._getWatchedDir(X),N=w;if(A.has(G))return;let D=async(W,J)=>{if(!this.fsw._throttle(f_,$,5))return;if(!J||J.mtimeMs===0)try{let Y=await U3($);if(this.fsw.closed)return;let{atimeMs:H,mtimeMs:L}=Y;if(!H||H<=L||L!==N.mtimeMs)this.fsw._emit(Cw.CHANGE,$,Y);if((__||Z_||C_)&&N.ino!==Y.ino){this.fsw._closeFile(W),N=Y;let F=this._watchWithNodeFs($,D);if(F)this.fsw._addPathCloser(W,F)}else N=Y}catch(Y){this.fsw._remove(X,G)}else if(A.has(G)){let{atimeMs:Y,mtimeMs:H}=J;if(!Y||Y<=H||H!==N.mtimeMs)this.fsw._emit(Cw.CHANGE,$,J);N=J}},O=this._watchWithNodeFs($,D);if(!(E&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored($)){if(!this.fsw._throttle(Cw.ADD,$,0))return;this.fsw._emit(Cw.ADD,$,w)}return O}async _handleSymlink($,w,E,X){if(this.fsw.closed)return;let G=$.fullPath,A=this.fsw._getWatchedDir(w);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let N;try{N=await rJ(E)}catch(D){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;if(A.has(X)){if(this.fsw._symlinkPaths.get(G)!==N)this.fsw._symlinkPaths.set(G,N),this.fsw._emit(Cw.CHANGE,E,$.stats)}else A.add(X),this.fsw._symlinkPaths.set(G,N),this.fsw._emit(Cw.ADD,E,$.stats);return this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(G))return!0;this.fsw._symlinkPaths.set(G,!0)}_handleRead($,w,E,X,G,A,N){if($=o0.join($,""),N=this.fsw._throttle("readdir",$,1000),!N)return;let D=this.fsw._getWatchedDir(E.path),O=new Set,W=this.fsw._readdirp($,{fileFilter:(J)=>E.filterPath(J),directoryFilter:(J)=>E.filterDir(J)});if(!W)return;return W.on(b_,async(J)=>{if(this.fsw.closed){W=void 0;return}let Y=J.path,H=o0.join($,Y);if(O.add(Y),J.stats.isSymbolicLink()&&await this._handleSymlink(J,$,H,Y))return;if(this.fsw.closed){W=void 0;return}if(Y===X||!X&&!D.has(Y))this.fsw._incrReadyCount(),H=o0.join(G,o0.relative(G,H)),this._addToNodeFs(H,w,E,A+1)}).on(Cw.ERROR,this._boundHandleError),new Promise((J,Y)=>{if(!W)return Y();W.once(mJ,()=>{if(this.fsw.closed){W=void 0;return}let H=N?N.clear():!1;if(J(void 0),D.getChildren().filter((L)=>{return L!==$&&!O.has(L)}).forEach((L)=>{this.fsw._remove($,L)}),W=void 0,H)this._handleRead($,!1,E,X,G,A,N)})})}async _handleDir($,w,E,X,G,A,N){let D=this.fsw._getWatchedDir(o0.dirname($)),O=D.has(o0.basename($));if(!(E&&this.fsw.options.ignoreInitial)&&!G&&!O)this.fsw._emit(Cw.ADD_DIR,$,w);D.add(o0.basename($)),this.fsw._getWatchedDir($);let W,J,Y=this.fsw.options.depth;if((Y==null||X<=Y)&&!this.fsw._symlinkPaths.has(N)){if(!G){if(await this._handleRead($,E,A,G,$,X,W),this.fsw.closed)return}J=this._watchWithNodeFs($,(H,L)=>{if(L&&L.mtimeMs===0)return;this._handleRead(H,!1,A,G,$,X,W)})}return J}async _addToNodeFs($,w,E,X,G){let A=this.fsw._emitReady;if(this.fsw._isIgnored($)||this.fsw.closed)return A(),!1;let N=this.fsw._getWatchHelpers($);if(E)N.filterPath=(D)=>E.filterPath(D),N.filterDir=(D)=>E.filterDir(D);try{let D=await v_[N.statMethod](N.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(N.watchPath,D))return A(),!1;let O=this.fsw.options.followSymlinks,W;if(D.isDirectory()){let J=o0.resolve($),Y=O?await rJ($):$;if(this.fsw.closed)return;if(W=await this._handleDir(N.watchPath,D,w,X,G,N,Y),this.fsw.closed)return;if(J!==Y&&Y!==void 0)this.fsw._symlinkPaths.set(J,Y)}else if(D.isSymbolicLink()){let J=O?await rJ($):$;if(this.fsw.closed)return;let Y=o0.dirname(N.watchPath);if(this.fsw._getWatchedDir(Y).add(N.watchPath),this.fsw._emit(Cw.ADD,N.watchPath,D),W=await this._handleDir(Y,D,w,X,$,N,J),this.fsw.closed)return;if(J!==void 0)this.fsw._symlinkPaths.set(o0.resolve($),J)}else W=this._handleFile(N.watchPath,D,w);if(A(),W)this.fsw._addPathCloser($,W);return!1}catch(D){if(this.fsw._handleError(D))return A(),$}}}/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */var dJ="/",m_="//",z3=".",i_="..",p_="string",d_=/\\/g,F3=/\/\//,l_=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,s_=/^\.[/\\]/;function ZD($){return Array.isArray($)?$:[$]}var lJ=($)=>typeof $==="object"&&$!==null&&!($ instanceof RegExp);function a_($){if(typeof $==="function")return $;if(typeof $==="string")return(w)=>$===w;if($ instanceof RegExp)return(w)=>$.test(w);if(typeof $==="object"&&$!==null)return(w)=>{if($.path===w)return!0;if($.recursive){let E=Y0.relative($.path,w);if(!E)return!1;return!E.startsWith("..")&&!Y0.isAbsolute(E)}return!1};return()=>!1}function e_($){if(typeof $!=="string")throw Error("string expected");$=Y0.normalize($),$=$.replace(/\\/g,"/");let w=!1;if($.startsWith("//"))w=!0;let E=/\/\//;while($.match(E))$=$.replace(E,"/");if(w)$="/"+$;return $}function j3($,w,E){let X=e_(w);for(let G=0;G<$.length;G++){let A=$[G];if(A(X,E))return!0}return!1}function $Z($,w){if($==null)throw TypeError("anymatch: specify first argument");let X=ZD($).map((G)=>a_(G));if(w==null)return(G,A)=>{return j3(X,G,A)};return j3(X,w)}var M3=($)=>{let w=ZD($).flat();if(!w.every((E)=>typeof E===p_))throw TypeError(`Non-string provided as watch path: ${w}`);return w.map(B3)},T3=($)=>{let w=$.replace(d_,dJ),E=!1;if(w.startsWith(m_))E=!0;while(w.match(F3))w=w.replace(F3,dJ);if(E)w=dJ+w;return w},B3=($)=>T3(Y0.normalize(T3($))),R3=($="")=>(w)=>{if(typeof w==="string")return B3(Y0.isAbsolute(w)?w:Y0.join($,w));else return w},wZ=($,w)=>{if(Y0.isAbsolute($))return $;return Y0.join(w,$)},EZ=Object.freeze(new Set);class I3{constructor($,w){this.path=$,this._removeWatcher=w,this.items=new Set}add($){let{items:w}=this;if(!w)return;if($!==z3&&$!==i_)w.add($)}async remove($){let{items:w}=this;if(!w)return;if(w.delete($),w.size>0)return;let E=this.path;try{await t_(E)}catch(X){if(this._removeWatcher)this._removeWatcher(Y0.dirname(E),Y0.basename(E))}}has($){let{items:w}=this;if(!w)return;return w.has($)}getChildren(){let{items:$}=this;if(!$)return[];return[...$.values()]}dispose(){this.items.clear(),this.path="",this._removeWatcher=bD,this.items=EZ,Object.freeze(this)}}var XZ="stat",GZ="lstat";class Q3{constructor($,w,E){this.fsw=E;let X=$;this.path=$=$.replace(s_,""),this.watchPath=X,this.fullWatchPath=Y0.resolve(X),this.dirParts=[],this.dirParts.forEach((G)=>{if(G.length>1)G.pop()}),this.followSymlinks=w,this.statMethod=w?XZ:GZ}entryPath($){return Y0.join(this.watchPath,Y0.relative(this.watchPath,$.fullPath))}filterPath($){let{stats:w}=$;if(w&&w.isSymbolicLink())return this.filterDir($);let E=this.entryPath($);return this.fsw._isntIgnored(E,w)&&this.fsw._hasReadPermissions(w)}filterDir($){return this.fsw._isntIgnored(this.entryPath($),$.stats)}}class sJ extends o_{constructor($={}){super();this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let w=$.awaitWriteFinish,E={stabilityThreshold:2000,pollInterval:100},X={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...$,ignored:$.ignored?ZD($.ignored):ZD([]),awaitWriteFinish:w===!0?E:typeof w==="object"?{...E,...w}:!1};if(H3)X.usePolling=!0;if(X.atomic===void 0)X.atomic=!X.usePolling;let G=process.env.CHOKIDAR_USEPOLLING;if(G!==void 0){let D=G.toLowerCase();if(D==="false"||D==="0")X.usePolling=!1;else if(D==="true"||D==="1")X.usePolling=!0;else X.usePolling=!!D}let A=process.env.CHOKIDAR_INTERVAL;if(A)X.interval=Number.parseInt(A,10);let N=0;this._emitReady=()=>{if(N++,N>=this._readyCount)this._emitReady=bD,this._readyEmitted=!0,process.nextTick(()=>this.emit(g0.READY))},this._emitRaw=(...D)=>this.emit(g0.RAW,...D),this._boundRemove=this._remove.bind(this),this.options=X,this._nodeFsHandler=new pJ(this),Object.freeze(X)}_addIgnoredPath($){if(lJ($)){for(let w of this._ignoredPaths)if(lJ(w)&&w.path===$.path&&w.recursive===$.recursive)return}this._ignoredPaths.add($)}_removeIgnoredPath($){if(this._ignoredPaths.delete($),typeof $==="string"){for(let w of this._ignoredPaths)if(lJ(w)&&w.path===$)this._ignoredPaths.delete(w)}}add($,w,E){let{cwd:X}=this.options;this.closed=!1,this._closePromise=void 0;let G=M3($);if(X)G=G.map((A)=>{return wZ(A,X)});if(G.forEach((A)=>{this._removeIgnoredPath(A)}),this._userIgnored=void 0,!this._readyCount)this._readyCount=0;return this._readyCount+=G.length,Promise.all(G.map(async(A)=>{let N=await this._nodeFsHandler._addToNodeFs(A,!E,void 0,0,w);if(N)this._emitReady();return N})).then((A)=>{if(this.closed)return;A.forEach((N)=>{if(N)this.add(Y0.dirname(N),Y0.basename(w||N))})}),this}unwatch($){if(this.closed)return this;let w=M3($),{cwd:E}=this.options;return w.forEach((X)=>{if(!Y0.isAbsolute(X)&&!this._closers.has(X)){if(E)X=Y0.join(E,X);X=Y0.resolve(X)}if(this._closePath(X),this._addIgnoredPath(X),this._watched.has(X))this._addIgnoredPath({path:X,recursive:!0});this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let $=[];return this._closers.forEach((w)=>w.forEach((E)=>{let X=E();if(X instanceof Promise)$.push(X)})),this._streams.forEach((w)=>w.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach((w)=>w.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=$.length?Promise.all($).then(()=>{return}):Promise.resolve(),this._closePromise}getWatched(){let $={};return this._watched.forEach((w,E)=>{let G=(this.options.cwd?Y0.relative(this.options.cwd,E):E)||z3;$[G]=w.getChildren().sort()}),$}emitWithAll($,w){if(this.emit($,...w),$!==g0.ERROR)this.emit(g0.ALL,$,...w)}async _emit($,w,E){if(this.closed)return;let X=this.options;if(iJ)w=Y0.normalize(w);if(X.cwd)w=Y0.relative(X.cwd,w);let G=[w];if(E!=null)G.push(E);let A=X.awaitWriteFinish,N;if(A&&(N=this._pendingWrites.get(w)))return N.lastChange=new Date,this;if(X.atomic){if($===g0.UNLINK)return this._pendingUnlinks.set(w,[$,...G]),setTimeout(()=>{this._pendingUnlinks.forEach((D,O)=>{this.emit(...D),this.emit(g0.ALL,...D),this._pendingUnlinks.delete(O)})},typeof X.atomic==="number"?X.atomic:100),this;if($===g0.ADD&&this._pendingUnlinks.has(w))$=g0.CHANGE,this._pendingUnlinks.delete(w)}if(A&&($===g0.ADD||$===g0.CHANGE)&&this._readyEmitted){let D=(O,W)=>{if(O)$=g0.ERROR,G[0]=O,this.emitWithAll($,G);else if(W){if(G.length>1)G[1]=W;else G.push(W);this.emitWithAll($,G)}};return this._awaitWriteFinish(w,A.stabilityThreshold,$,D),this}if($===g0.CHANGE){if(!this._throttle(g0.CHANGE,w,50))return this}if(X.alwaysStat&&E===void 0&&($===g0.ADD||$===g0.ADD_DIR||$===g0.CHANGE)){let D=X.cwd?Y0.join(X.cwd,w):w,O;try{O=await r_(D)}catch(W){}if(!O||this.closed)return;G.push(O)}return this.emitWithAll($,G),this}_handleError($){let w=$&&$.code;if($&&w!=="ENOENT"&&w!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||w!=="EPERM"&&w!=="EACCES"))this.emit(g0.ERROR,$);return $||this.closed}_throttle($,w,E){if(!this._throttled.has($))this._throttled.set($,new Map);let X=this._throttled.get($);if(!X)throw Error("invalid throttle");let G=X.get(w);if(G)return G.count++,!1;let A,N=()=>{let O=X.get(w),W=O?O.count:0;if(X.delete(w),clearTimeout(A),O)clearTimeout(O.timeoutObject);return W};A=setTimeout(N,E);let D={timeoutObject:A,clear:N,count:0};return X.set(w,D),D}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish($,w,E,X){let G=this.options.awaitWriteFinish;if(typeof G!=="object")return;let A=G.pollInterval,N,D=$;if(this.options.cwd&&!Y0.isAbsolute($))D=Y0.join(this.options.cwd,$);let O=new Date,W=this._pendingWrites;function J(Y){c_(D,(H,L)=>{if(H||!W.has($)){if(H&&H.code!=="ENOENT")X(H);return}let F=Number(new Date);if(Y&&L.size!==Y.size)W.get($).lastChange=F;let j=W.get($);if(F-j.lastChange>=w)W.delete($),X(void 0,L);else N=setTimeout(J,A,L)})}if(!W.has($))W.set($,{lastChange:O,cancelWait:()=>{return W.delete($),clearTimeout(N),E}}),N=setTimeout(J,A)}_isIgnored($,w){if(this.options.atomic&&l_.test($))return!0;if(!this._userIgnored){let{cwd:E}=this.options,G=(this.options.ignored||[]).map(R3(E)),N=[...[...this._ignoredPaths].map(R3(E)),...G];this._userIgnored=$Z(N,void 0)}return this._userIgnored($,w)}_isntIgnored($,w){return!this._isIgnored($,w)}_getWatchHelpers($){return new Q3($,this.options.followSymlinks,this)}_getWatchedDir($){let w=Y0.resolve($);if(!this._watched.has(w))this._watched.set(w,new I3(w,this._boundRemove));return this._watched.get(w)}_hasReadPermissions($){if(this.options.ignorePermissionErrors)return!0;return Boolean(Number($.mode)&256)}_remove($,w,E){let X=Y0.join($,w),G=Y0.resolve(X);if(E=E!=null?E:this._watched.has(X)||this._watched.has(G),!this._throttle("remove",X,100))return;if(!E&&this._watched.size===1)this.add($,w,!0);this._getWatchedDir(X).getChildren().forEach((Y)=>this._remove(X,Y));let D=this._getWatchedDir($),O=D.has(w);if(D.remove(w),this._symlinkPaths.has(G))this._symlinkPaths.delete(G);let W=X;if(this.options.cwd)W=Y0.relative(this.options.cwd,X);if(this.options.awaitWriteFinish&&this._pendingWrites.has(W)){if(this._pendingWrites.get(W).cancelWait()===g0.ADD)return}this._watched.delete(X),this._watched.delete(G);let J=E?g0.UNLINK_DIR:g0.UNLINK;if(O&&!this._isIgnored(X))this._emit(J,X);this._closePath(X)}_closePath($){this._closeFile($);let w=Y0.dirname($);this._getWatchedDir(w).remove(Y0.basename($))}_closeFile($){let w=this._closers.get($);if(!w)return;w.forEach((E)=>E()),this._closers.delete($)}_addPathCloser($,w){if(!w)return;let E=this._closers.get($);if(!E)E=[],this._closers.set($,E);E.push(w)}_readdirp($,w){if(this.closed)return;let E={type:g0.ALL,alwaysStat:!0,lstat:!0,...w,depth:0},X=O3($,E);return this._streams.add(X),X.once(Y3,()=>{X=void 0}),X.once(mJ,()=>{if(X)this._streams.delete(X),X=void 0}),X}}function AZ($,w={}){let E=new sJ(w);return E.add($),E}var K3={watch:AZ,FSWatcher:sJ};f$();cE();var aG=B0("runner:watcher"),KX=new Map;async function P3(){let w=await f().query.jobs.findMany({where:V(I0.enabled,!0)});for(let E of w)if(E.trigger_type==="watch"&&E.watch_path)NZ(E.id,E.name,E.watch_path);aG.info(`Watchers started. ${KX.size} paths watched.`)}function NZ($,w,E){if(KX.has($))KX.get($)?.close().catch(()=>{});let X=K3.watch(E,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});X.on("add",(G)=>V3($,w,G)),X.on("change",(G)=>V3($,w,G)),KX.set($,X),aG.info(`Watching: ${E} \u2192 ${w}`)}async function V3($,w,E){aG.info(`Watch trigger: ${w} (${E})`);try{await Nw({jobId:$,triggerBy:"watch",envOverrides:{WATCH_PATH:E}})}catch(X){aG.error(`Watch job failed: ${w}`,X)}}async function q3(){for(let[,$]of KX)await $.close();KX.clear(),aG.info("Watchers stopped.")}R$();async function DZ($,w,E,X,G,A){let N=`${$}${X}`;if(A){let O=new URLSearchParams;for(let[J,Y]of Object.entries(A))if(Y!==void 0)O.set(J,String(Y));let W=O.toString();if(W)N+=`?${W}`}let D={"Content-Type":"application/json"};if(w)D.Authorization=`Bearer ${w}`;try{let O=await fetch(N,{method:E,headers:D,...G!==void 0?{body:JSON.stringify(G)}:{}});if(O.status===204)return{data:null,error:null};let W=await O.json();if(!O.ok){let J=W;return{data:null,error:{error:J.error??"Unknown error",code:J.code??"UNKNOWN"}}}return{data:W,error:null}}catch(O){return{data:null,error:{error:String(O),code:"NETWORK_ERROR"}}}}function e($){let w=G0(),E=$?.baseUrl??`http://${w.api.host}:${w.api.port}`,X=$?.secret??w.api.secret,G=(A,N,D,O)=>DZ(E,X,A,N,D,O);return{tasks:{list:(A)=>G("GET","/tasks",void 0,A),get:(A)=>G("GET",`/tasks/${A}`),create:(A)=>G("POST","/tasks",A),update:(A,N)=>G("PATCH",`/tasks/${A}`,N),delete:(A)=>G("DELETE",`/tasks/${A}`),addComment:(A,N,D="human")=>G("POST",`/tasks/${A}/comments`,{content:N,author:D}),listComments:(A)=>G("GET",`/tasks/${A}/comments`),listLinks:(A)=>G("GET",`/tasks/${A}/links`),addLink:(A,N)=>G("POST",`/tasks/${A}/links`,N),deleteLink:(A,N)=>G("DELETE",`/tasks/${A}/links/${N}`)},memories:{list:(A)=>G("GET","/memories",void 0,A),search:(A,N)=>G("GET","/memories/search",void 0,{q:A,scope:N?.scope,project_id:N?.project_id,limit:N?.limit}),create:(A)=>G("POST","/memories",A),delete:(A)=>G("DELETE",`/memories/${A}`)},jobs:{list:(A)=>G("GET","/jobs",void 0,A),get:(A)=>G("GET",`/jobs/${A}`),create:(A)=>G("POST","/jobs",A),update:(A,N)=>G("PATCH",`/jobs/${A}`,N),delete:(A)=>G("DELETE",`/jobs/${A}`),trigger:(A)=>G("POST",`/jobs/${A}/trigger`),runs:(A,N)=>G("GET",`/jobs/${A}/runs`,void 0,{limit:N}),runLogs:(A,N,D)=>G("GET",`/jobs/${A}/runs/${N}/logs`,void 0,D)},prompts:{list:(A)=>G("GET","/prompts",void 0,A),get:(A)=>G("GET",`/prompts/${A}`),create:(A)=>G("POST","/prompts",A),update:(A,N)=>G("PATCH",`/prompts/${A}`,N),delete:(A)=>G("DELETE",`/prompts/${A}`),render:(A,N)=>G("POST",`/prompts/${A}/render`,{vars:N??{}}),history:(A,N)=>G("GET",`/prompts/${A}/history`,void 0,{limit:N})},projects:{list:(A)=>G("GET","/projects",void 0,A),get:(A)=>G("GET",`/projects/${A}`),getByName:(A)=>G("GET",`/projects/by-name/${encodeURIComponent(A)}`),summary:(A)=>G("GET",`/projects/${A}/summary`),create:(A)=>G("POST","/projects",A),update:(A,N)=>G("PATCH",`/projects/${A}`,N),delete:(A)=>G("DELETE",`/projects/${A}`),addComment:(A,N,D="human")=>G("POST",`/projects/${A}/comments`,{content:N,author:D}),listComments:(A)=>G("GET",`/projects/${A}/comments`)},sessions:{list:(A)=>G("GET","/sessions",void 0,A),get:(A)=>G("GET",`/sessions/${A}`)},health:{check:()=>G("GET","/health")},gateway:{status:()=>G("GET","/gateway/status"),send:(A)=>G("POST","/gateway/send",A)}}}var pE=process.env.ORC_HOME??E6(Bf(),".orc"),hG0=E6(pE,"daemon.log"),fX=E6(pE,"daemon.pid");function If(){Tf(E6(pE,"logs"),{recursive:!0})}function w6(){try{return Number(Rf(fX,"utf-8").trim())}catch{return null}}function Qf(){zf(fX,String(process.pid))}function Cj(){try{b$("fs").unlinkSync(fX)}catch{}}function fj(){let $=new E$("daemon").description("Run the API + scheduler + file watchers + gateway as one persistent process");return $.command("start",{isDefault:!0}).description("Start the daemon (use global --port / --host / --db / --secret to configure)").action(async()=>{If();let w=w6();if(w)try{process.kill(w,0),console.error(`[orc] daemon already running (pid ${w}). Use: orc daemon stop`),process.exit(1)}catch{}let E=G0();Qf(),await Promise.resolve().then(() => (C4(),Z4)),console.log(`[orc] home ${pE}`),console.log(`[orc] db ${E.db.path}`),console.log(`[orc] API http://${E.api.host}:${E.api.port}`),console.log(`[orc] pid ${process.pid} -> ${fX}`),await lL(),await P3(),await bJ(),console.log(`[orc] Scheduler + watchers + gateway active. Ctrl+C to stop.
580
564
  `);let X=async(G)=>{process.stdout.write(`
581
565
  [orc] ${G} - shutting down...
582
- `),pL(),await R3(),await qN(),Vj(),process.stdout.write(`[orc] Stopped.
583
- `),process.exit(0)};process.on("SIGINT",()=>void X("SIGINT")),process.on("SIGTERM",()=>void X("SIGTERM")),await new Promise(()=>{})}),$.command("stop").description("Stop the running daemon").action(()=>{let w=aA();if(!w){console.log("No daemon running (no pid file at ~/.orc/daemon.pid).");return}try{process.kill(w,"SIGTERM"),console.log(`Sent SIGTERM to daemon (pid ${w}).`)}catch{console.error(`Could not signal pid ${w} - process may already be stopped.`),Vj()}}),$.command("status").description("Show scheduler state and next run times for all active jobs").action(async()=>{let w=e(),{data:E,error:X}=await w.jobs.list();if(X)return console.error("Error:",X);let G=(E?.jobs??[]).filter((J)=>J.enabled&&(J.trigger_type==="cron"||J.trigger_type==="watch"));if(G.length===0){console.log("No scheduled jobs defined."),console.log("Create one with: orc job add <name> --trigger cron --cron '0 22 * * *' ...");return}console.log(`Scheduled jobs:
584
- `);for(let J of G){let A=J.trigger_type==="cron"?`cron(${J.cron_expr??"?"})`:J.trigger_type,D=J.last_run_at?new Date(J.last_run_at).toISOString().slice(0,19):"never",N=`runs:${J.run_count}`,W=J.enabled?"\u25CF":"\u25CB";console.log(` ${W} ${J.name.padEnd(24)} ${A.padEnd(24)} last:${D.padEnd(20)} ${N}`)}}),$}function qj(){let $=new $$("gateway").description("Inspect and send channel gateway messages");return $.command("status").description("Show enabled adapters and active sessions").action(async()=>{let w=e(),{data:E,error:X}=await w.gateway.status();if(X)console.error(`Error: ${X.error}`),process.exit(1);console.log(E.status)}),$.command("send").description("Send a message to a configured Telegram or Slack chat").requiredOption("--platform <platform>","telegram or slack").requiredOption("--chat <id>","Platform chat/channel ID").requiredOption("--text <text>","Message text").option("--thread <id>","Optional Telegram thread or Slack thread timestamp").action(async(w)=>{let E=e(),{error:X}=await E.gateway.send({platform:w.platform,chat_id:w.chat,text:w.text,thread_id:w.thread});if(X)console.error(`Error: ${X.error}`),process.exit(1);console.log(`Sent message to ${w.platform}:${w.chat}`)}),$}function t(){return process.argv.includes("--json")}function $0($){console.log(JSON.stringify($,null,2))}function M1($){console.error(JSON.stringify({error:$})),process.exit(1)}function g$(){return process.argv.includes("--dry-run")}function u$($,w,E){if(console.log(`[dry-run] Would ${$} ${w}`),E)console.log(JSON.stringify(E,null,2))}C$();import{existsSync as Ov,readFileSync as Uv,writeFileSync as Yv}from"fs";import{homedir as Hv}from"os";import{join as Lv}from"path";async function g1($,w){if(w.noProject)return null;let E=w.project??O0().activeProject;if(!E)console.error("No project set. Use -p <name> or 'orc project use <name>'"),process.exit(1);let{data:X,error:G}=await $.projects.getByName(E);if(G||!X)console.error(`Project not found: ${E}`),process.exit(1);return{id:X.id,name:X.name}}function Fv($){return{active:"\u25CF",paused:"\u25D0",archived:"\u25CB"}[$]??"?"}function jv($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function Mv($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function Rv($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function kj(){return Lv(Hv(),".orc","config.json")}function Sj(){let $=kj();if(!Ov($))return{};return JSON.parse(Uv($,"utf-8"))}function q9($){Yv(kj(),`${JSON.stringify($,null,2)}
585
- `)}function bj(){let $=new $$("project").description("Manage projects");return $.command("list").description("List projects").option("--status <s>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.list({status:w.status,tag:w.tag,limit:Number(w.limit)});if(G)return console.error("Error:",G);let J=X?.projects??[];if(t())return $0({projects:J});if(J.length===0)return console.log("No projects found.");for(let A of J){let{data:D}=await E.projects.summary(A.id),W=`${Fv(A.status)} ${A.name.padEnd(18)} (${A.status})`;if(D){let O=D.tasks.total,Y=D.tasks.by_status.review??0,H=Y>0?`${O} tasks (${Y} review)`:`${O} tasks`;W+=` ${H} ${D.memories} mems ${D.jobs} jobs`}console.log(W)}}),$.command("add <name>").description("Create a new project").option("-d, --description <text>","Project description").option("--scope <s>","Project scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{if(!/^[a-zA-Z0-9_-]+$/.test(w))return console.error("Invalid project name: only [a-zA-Z0-9_-] characters allowed.");let X=e(),G=E.tags?E.tags.split(",").map((N)=>N.trim()):void 0,{data:J,error:A}=await X.projects.create({name:w,description:E.description,scope:E.scope,tags:G});if(A)return console.error("Error:",A);if(t())return $0(J);if(!O0().activeProject){let N=Sj();N.activeProject=w,q9(N)}console.log(`Created: ${J?.name} [${J?.id.slice(-6)}]`)}),$.command("show [name]").description("Show project details").action(async(w)=>{let E=e(),X=w??O0().activeProject;if(!X)return console.error("No project set. Use -p <name> or 'orc project use <name>'");let{data:G,error:J}=await E.projects.getByName(X);if(J||!G)return console.error(`Project not found: ${X}`);let[A,D,N,W]=await Promise.all([E.projects.summary(G.id),E.tasks.list({project_id:G.id}),E.jobs.list({project_id:G.id}),E.memories.list({project_id:G.id})]),O=A.data,Y=D.data?.tasks??[],H=N.data?.jobs??[],L=W.data?.memories??[];if(t())return $0({project:G,summary:O??null,tasks:Y,jobs:H,memories:L});if(console.log(`${G.name} (${G.status})`),G.description)console.log(` ${G.description}`);if(console.log(),O){let M=O.tasks.by_status,z=Object.entries(M).filter(([,B])=>B>0).map(([B,Q])=>`${B}: ${Q}`);if(console.log(`Tasks (${O.tasks.total})`),z.length>0)console.log(` ${z.join(" ")}`);console.log()}for(let M of Y.slice(0,10)){let z=Mv(M.status),B=Rv(M.priority);console.log(` ${z} ${B} [${M.id.slice(-6)}] ${M.title.padEnd(36)} ${M.status}`)}if(Y.length>10)console.log(` ... and ${Y.length-10} more`);console.log(),console.log(`Jobs (${H.length})`);for(let M of H){let z=M.trigger_type==="cron"&&M.cron_expr?`cron(${M.cron_expr})`:M.trigger_type;console.log(` \u25CF ${M.name.padEnd(20)} ${z} runs:${M.run_count}`)}console.log();let F=O?.memories??L.length,j=L.slice(0,5);console.log(`Memories (${j.length} of ${F})`);for(let M of j){let z=M.scope?`[${M.scope}]`:"",B=jv(M.created_at);console.log(` \u2022 ${z} ${M.content.slice(0,50).padEnd(50)} ${B}`)}}),$.command("use <name>").description("Set active project").option("--clear","Unset active project").action(async(w,E)=>{let X=Sj();if(E.clear)return delete X.activeProject,q9(X),console.log("Active project cleared");let G=e(),{data:J,error:A}=await G.projects.getByName(w);if(A||!J)return console.error(`Project not found: ${w}`);if(X.activeProject=w,q9(X),t())return $0({activeProject:w});console.log(`Active project: ${w}`)}),$.command("update <name>").description("Update a project").option("--name <n>","New name").option("-d, --description <text>","Description").option("--status <s>","Status (active/paused/archived)").option("--scope <s>","Scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.projects.getByName(w);if(J||!G)return console.error(`Project not found: ${w}`);if(g$())return u$("update",`project ${w}`);let A=E.tags?E.tags.split(",").map((W)=>W.trim()):void 0,{data:D,error:N}=await X.projects.update(G.id,{name:E.name,description:E.description,status:E.status,scope:E.scope,tags:A});if(N)return console.error("Error:",N);if(t())return $0(D);console.log(`Updated: ${D?.name} [${D?.id.slice(-6)}]`)}),$.command("archive <name>").description("Archive a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(g$())return u$("archive",`project ${w}`);let{data:J,error:A}=await E.projects.update(X.id,{status:"archived"});if(A)return console.error("Error:",A);if(t())return $0(J);console.log(`Archived: ${J?.name} [${J?.id.slice(-6)}]`)}),$.command("delete <name>").description("Delete a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(g$())return u$("delete",`project ${w}`);let{error:J}=await E.projects.delete(X.id);if(J)return console.error("Error:",J);if(t())return $0({deleted:X.id,name:w});console.log(`Deleted project: ${w} [${X.id.slice(-6)}]`)}),$}function Zj(){let $=new $$("job").description("Manage jobs");return $.command("list").description("List jobs").option("-p, --project <name>","Filter by project name").option("--no-project","Show all jobs").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.jobs.list(G?{project_id:G.id}:{});if(A)return console.error("Error:",A);let D=J?.jobs??[];if(t())return $0({jobs:D});if(D.length===0)return console.log("No jobs found.");for(let N of D){let W=N.enabled?"\u25CF":"\u25CB",O=N.cron_expr?`cron(${N.cron_expr})`:N.trigger_type;console.log(`${W} ${N.name.padEnd(24)} ${O.padEnd(20)} runs:${N.run_count}`)}}),$.command("add <name>").description("Create a job").requiredOption("-c, --command <cmd>","Shell command to run").option("--trigger <type>","Trigger type (manual/cron/watch/one-shot/webhook)","manual").option("--cron <expr>","Cron expression (e.g. '0 22 * * *' or '*/30 * * * * *' every 30s)").option("--watch <path>","Watch path for file changes").option("--timeout <secs>","Timeout in seconds","300").option("--retries <n>","Max retries","0").option("--notify <when>","Notify on: never/failure/always","failure").option("-d, --description <text>","Description").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.jobs.create({name:w,...J?{project_id:J.id}:{},description:E.description,command:E.command,trigger_type:E.trigger,cron_expr:E.cron,watch_path:E.watch,timeout_secs:Number(E.timeout),max_retries:Number(E.retries),notify_on:E.notify});if(D||!A)return console.error("Error:",D);if(t())return $0(A);console.log(`Created job: ${A.name} [${A.id.slice(-6)}]`)}),$.command("run <name-or-id>").description("Manually trigger a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((N)=>N.name===w||N.id===w);if(!J)return console.error(`Job not found: ${w}`);let{data:A,error:D}=await E.jobs.trigger(J.id);if(D||!A)return console.error("Error:",D);if(t())return $0(A);console.log(`Triggered job ${J.name} \u2192 run: ${A.run_id}`)}),$.command("show <name-or-id>").description("Show job details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((W)=>W.name===w||W.id===w);if(!J)return console.error(`Job not found: ${w}`);let{data:A,error:D}=await E.jobs.get(J.id);if(D||!A)return console.error("Error:",D);if(t())return $0(A);let N=[["Name",A.name],["ID",A.id],["Description",A.description],["Command",A.command],["Trigger",A.trigger_type],["Cron",A.cron_expr],["Enabled",A.enabled],["Timeout (s)",A.timeout_secs],["Max retries",A.max_retries],["Overlap",A.overlap],["Notify on",A.notify_on],["Project ID",A.project_id],["Run count",A.run_count],["Last run",A.last_run_at],["Created",A.created_at],["Updated",A.updated_at]];for(let[W,O]of N)if(O!==void 0&&O!==null&&O!=="")console.log(`${W.padEnd(14)} ${O}`)}),$.command("delete <name-or-id>").description("Delete a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((D)=>D.name===w||D.id===w);if(!J)return console.error(`Job not found: ${w}`);if(g$())return u$("delete",`job ${J.name}`);let{error:A}=await E.jobs.delete(J.id);if(A)return console.error("Error:",A);if(t())return $0({deleted:J.id,name:J.name});console.log(`Deleted job: ${J.name} [${J.id.slice(-6)}]`)}),$.command("update <name-or-id>").description("Update a job").option("--name <n>","New name").option("-d, --description <text>","Description").option("-c, --command <cmd>","Shell command").option("--trigger <type>","Trigger type").option("--cron <expr>","Cron expression").option("--timeout <secs>","Timeout in seconds").option("--retries <n>","Max retries").option("--notify <when>","Notify on: never/failure/always").option("--enabled","Enable the job").option("--disabled","Disable the job").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.jobs.list();if(J)return console.error("Error:",J);let A=G?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let D={};if(E.name)D.name=E.name;if(E.description)D.description=E.description;if(E.command)D.command=E.command;if(E.trigger)D.trigger_type=E.trigger;if(E.cron)D.cron_expr=E.cron;if(E.timeout)D.timeout_secs=Number(E.timeout);if(E.retries)D.max_retries=Number(E.retries);if(E.notify)D.notify_on=E.notify;if(E.enabled)D.enabled=!0;if(E.disabled)D.enabled=!1;if(g$())return u$("update",`job ${A.name}`,D);let{data:N,error:W}=await X.jobs.update(A.id,D);if(W||!N)return console.error("Error:",W);if(t())return $0(N);console.log(`Updated job: ${N.name} [${N.id.slice(-6)}]`)}),$.command("runs <name-or-id>").description("Show recent runs for a job").option("-l, --limit <n>","Max results","10").option("-s, --sessions","Show linked agent sessions per run").option("--logs","Show stdout/stderr logs for each run").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.jobs.list();if(J)return console.error("Error:",J);let A=G?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let{data:D,error:N}=await X.jobs.runs(A.id,Number(E.limit));if(N)return console.error("Error:",N);let W=D?.runs??[];if(t())return $0({runs:W});if(W.length===0)return console.log("No runs yet.");for(let O of W){let Y=zv(O.status),H=O.started_at&&O.ended_at?`${Math.round((new Date(O.ended_at).getTime()-new Date(O.started_at).getTime())/1000)}s`:"-";if(console.log(`${Y} ${O.status.padEnd(10)} ${O.created_at.slice(0,19)} ${H} [${O.id.slice(-6)}]`),E.logs){let{data:L}=await X.jobs.runLogs(A.id,O.id);for(let F of L?.logs??[]){let j=F.stream==="stderr"?" ERR":" OUT";console.log(`${j} ${F.line}`)}}if(E.sessions){let{data:L}=await X.sessions.list({job_run_id:O.id,limit:5});for(let F of L?.sessions??[]){let j=F.summary?` ${F.summary.split(`
586
- `)[0]?.slice(0,60)}`:"";console.log(` \u21B3 session ${F.agent}${F.agent_version?`/${F.agent_version}`:""}${j}`)}}}}),$}function zv($){return{pending:"\u25CB",running:"\u25D0",success:"\u25CF",failed:"\u2715",cancelled:"\u2298",skipped:"\u21B7"}[$]??"?"}function _j(){let $=new $$("mem").description("Manage memory");return $.command("search <query>").description("Search memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","10").option("-p, --project <name>","Filter by project name").option("--no-project","Search all memories").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.memories.search(w,{scope:E.scope,...J?{project_id:J.id}:{},limit:Number(E.limit)});if(D)return console.error("Error:",D);let N=A?.results??[];if(t())return $0({results:N});if(N.length===0)return console.log("No memories found.");for(let W of N){let O=Cj(W.created_at),Y=W.scope?`[${W.scope}]`:"";console.log(`\u2022 ${W.content.slice(0,80)} ${Y} ${O}`)}}),$.command("add <content>").description("Store a memory").option("-s, --scope <scope>","Scope").option("--type <type>","Type (fact/decision/event/rule/discovery)","fact").option("--source <source>","Source reference").option("--importance <level>","Importance (low/normal/high/critical)","normal").option("-t, --tags <tags>","Comma-separated tags").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.memories.create({content:w,...J?{project_id:J.id}:{},type:E.type,scope:E.scope,source:E.source,importance:E.importance,...E.tags?{tags:E.tags.split(",").map((N)=>N.trim())}:{}});if(D)return console.error("Error:",D);if(t())return $0(A);console.log(`Stored: [${A?.id.slice(-6)}] [${E.type}] ${A?.content.slice(0,60)}`)}),$.command("list").description("List recent memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","20").option("-p, --project <name>","Filter by project name").option("--no-project","Show all memories").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.memories.list({scope:w.scope,...G?{project_id:G.id}:{},limit:Number(w.limit)});if(A)return console.error("Error:",A);let D=J?.memories??[];if(t())return $0({memories:D});if(D.length===0)return console.log("No memories found.");for(let N of D){let W=Cj(N.created_at),O=N.scope?`[${N.scope}]`:"";console.log(`\u2022 [${N.id.slice(-6)}] ${N.content.slice(0,70)} ${O} ${W}`)}}),$.command("show <id>").description("Show memory details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let J=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!J)return console.error(`Memory not found: ${w}`);if(t())return $0(J);let A=[["ID",J.id],["Content",J.content],["Scope",J.scope],["Source",J.source],["Importance",J.importance],["Project ID",J.project_id],["Tags",J.tags?.join(", ")],["Expires",J.expires_at],["Created",J.created_at],["Updated",J.updated_at]];for(let[D,N]of A)if(N!==void 0&&N!==null&&N!=="")console.log(`${D.padEnd(14)} ${N}`)}),$.command("delete <id>").description("Delete a memory").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let J=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!J)return console.error(`Memory not found: ${w}`);if(g$())return u$("delete",`memory [${J.id.slice(-6)}]`,{content:J.content.slice(0,80)});let{error:A}=await E.memories.delete(J.id);if(A)return console.error("Error:",A);if(t())return $0({deleted:J.id});console.log(`Deleted memory: [${J.id.slice(-6)}] ${J.content.slice(0,60)}`)}),$}function Cj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function vj(){let $=new $$("prompt").description("Manage prompts and skills");return $.command("list").description("List prompts").option("--skill","Show skills only").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.prompts.list({limit:Number(w.limit)});if(G)return console.error("Error:",G);let J=X?.prompts??[];if(w.skill)J=J.filter((A)=>A.is_skill);if(t())return $0({prompts:J});if(J.length===0)return console.log("No prompts found.");for(let A of J){let D=A.id.slice(-6),N=A.is_skill?H6(" [skill]","36"):"",W=H6(`v${A.version}`,"2"),O=A.name.length>40?`${A.name.slice(0,39)}\u2026`:A.name;console.log(` [${D}] ${O.padEnd(42)} ${W}${N}`)}}),$.command("show <id>").description("Show prompt details").action(async(w)=>{let E=e(),X=await Y6(E,w);if(!X)return;let{data:G,error:J}=await E.prompts.get(X);if(J)return console.error("Error:",J);if(!G)return console.error("Prompt not found.");if(t())return $0(G);if(console.log(H6(G.name,"1")),console.log(),G.description)console.log(` ${G.description}`);if(console.log(` id: ${G.id}`),console.log(` version: ${G.version}`),console.log(` is_skill: ${G.is_skill}`),G.skill_dir)console.log(` skill_dir: ${G.skill_dir}`);if(G.skill_version)console.log(` skill_ver: ${G.skill_version}`);if(console.log(` pinned: ${G.pinned}`),G.tags?.length)console.log(` tags: ${G.tags.join(", ")}`);if(G.last_used_at)console.log(` last_used: ${G.last_used_at}`);console.log(` created: ${G.created_at}`),console.log(` updated: ${G.updated_at}`),console.log(),console.log(H6("\u2500\u2500 template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","2")),console.log(G.template)}),$.command("add <name>").description("Create a new prompt").option("-c, --content <text>","Prompt template content").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").action(async(w,E)=>{let X=e(),G=E.content??"",{data:J,error:A}=await X.prompts.create({name:w,template:G,description:E.description,is_skill:E.skill??!1,tags:E.tags?E.tags.split(",").map((D)=>D.trim()):void 0,pinned:E.pinned??!1});if(A)return console.error("Error:",A);if(t())return $0(J);console.log(`Created: [${J?.id.slice(-6)}] ${J?.name}`)}),$.command("update <id>").description("Update a prompt").option("-c, --content <text>","Prompt template content").option("-n, --name <name>","Prompt name").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--no-skill","Unmark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").option("--no-pinned","Unpin this prompt").action(async(w,E)=>{let X=e(),G=await Y6(X,w);if(!G)return;let J={};if(E.content!==void 0)J.template=E.content;if(E.name!==void 0)J.name=E.name;if(E.description!==void 0)J.description=E.description;if(E.skill!==void 0)J.is_skill=E.skill;if(E.tags)J.tags=E.tags.split(",").map((N)=>N.trim());if(E.pinned!==void 0)J.pinned=E.pinned;if(g$())return u$("update",`prompt [${G.slice(-6)}]`,J);let{data:A,error:D}=await X.prompts.update(G,J);if(D)return console.error("Error:",D);if(t())return $0(A);console.log(`Updated: [${A?.id.slice(-6)}] ${A?.name}`)}),$.command("delete <id>").description("Delete a prompt").action(async(w)=>{let E=e(),X=await Y6(E,w);if(!X)return;if(g$())return u$("delete",`prompt ${X}`);let{error:G}=await E.prompts.delete(X);if(G)return console.error("Error:",G);if(t())return $0({deleted:X});console.log(`Deleted: ${X}`)}),$.command("render <id>").description("Render a prompt with variables").option("--var <key=value>","Variable (repeatable)",Tv,[]).action(async(w,E)=>{let X=e(),G=await Y6(X,w);if(!G)return;let J={};for(let N of E.var){let W=N.indexOf("=");if(W===-1)return console.error(`Invalid variable format: ${N} (expected key=value)`);J[N.slice(0,W)]=N.slice(W+1)}let{data:A,error:D}=await X.prompts.render(G,J);if(D)return console.error("Error:",D);if(t())return $0(A);console.log(A?.rendered)}),$.command("history <id>").description("Show version history").option("-l, --limit <n>","Max results","20").action(async(w,E)=>{let X=e(),G=await Y6(X,w);if(!G)return;let{data:J,error:A}=await X.prompts.history(G,Number(E.limit));if(A)return console.error("Error:",A);let D=J?.history??[];if(t())return $0({history:D});if(D.length===0)return console.log("No history found.");for(let N of D){let W=N.changed_at.slice(0,19).replace("T"," ");console.log(` v${String(N.version).padEnd(4)} ${H6(W,"2")} by ${N.changed_by} ${N.name}`)}}),$}function Tv($,w){return w.concat([$])}async function Y6($,w){if(w.length===26)return w;let{data:E}=await $.prompts.list({limit:200}),X=(E?.prompts??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Prompt not found: ${w}`),null;return X.id}function H6($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}C$();var fj=["task","memory","job","project","prompt","session"];function Bv(){try{let $=O0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function Qv(){let $={},w=process.env.ORC_API_SECRET??(()=>{try{return O0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}var Iv={task:["Task","CreateTask","UpdateTask","Comment","TaskLink"],memory:["Memory","CreateMemory"],job:["Job","CreateJob","UpdateJob","JobRun"],project:["Project","CreateProject","UpdateProject"],prompt:["Prompt","CreatePrompt","UpdatePrompt"],session:["Session"]};function xj(){return new $$("schema").description("Show resource schemas from the OpenAPI spec (requires running API)").argument("[resource]",`Resource name: ${fj.join(", ")}`).option("--list","List available schema names").action(async(w,E)=>{let X;try{X=await fetch(`${Bv()}/openapi.json`,{headers:Qv()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let J=(await X.json()).components?.schemas;if(!J)return console.error("No schemas found in OpenAPI spec.");if(E?.list||!w){console.log("Available schemas:");for(let W of Object.keys(J).sort())console.log(` ${W}`);return}let A=w.toLowerCase(),D=Iv[A];if(!D)return console.error(`Unknown resource: ${w}. Available: ${fj.join(", ")}`);let N={};for(let W of D)if(J[W])N[W]=J[W];if(Object.keys(N).length===0)return console.error(`No schemas found for: ${w}`);console.log(JSON.stringify(N,null,2))})}C$();function yj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function S9(){try{let $=O0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function k9(){let $={"Content-Type":"application/json"},w=process.env.ORC_API_SECRET??(()=>{try{return O0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}function gj(){let $=new $$("session").description("View session history");return $.command("list").description("List recent sessions").option("-a, --agent <agent>","Filter by agent (claude-code, cursor, codex)").option("-n, --limit <n>","Max results","20").action(async(w)=>{let E=new URLSearchParams({limit:w.limit});if(w.agent)E.set("agent",w.agent);let X;try{X=await fetch(`${S9()}/sessions?${E}`,{headers:k9()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let J=(await X.json()).sessions;if(t())return $0({sessions:J});if(J.length===0)return console.log("No sessions recorded yet.");console.log(`${"ID".padEnd(8)} ${"AGENT".padEnd(16)} ${"WHEN".padEnd(10)} SUMMARY`),console.log("\u2500".repeat(72));for(let A of J){let D=A.id.slice(-6),N=A.agent.padEnd(16),W=yj(A.created_at).padEnd(10),O=(A.summary??"\u2014").slice(0,40);console.log(`${D} ${N} ${W} ${O}`)}}),$.command("show <id>").description("Show session detail with events").option("-e, --events","Show recorded events").option("-s, --snapshot","Show snapshot XML").option("-n, --limit <n>","Max events to show","50").action(async(w,E)=>{let X=w;if(w.length<26){let A=await fetch(`${S9()}/sessions?limit=100`,{headers:k9()}).catch(()=>null);if(A?.ok){let N=(await A.json()).sessions.find((W)=>W.id.endsWith(w)||W.id===w);if(N)X=N.id}}let G;try{G=await fetch(`${S9()}/sessions/${X}`,{headers:k9()})}catch{return console.error("Cannot connect to orc API.")}if(G.status===404)return console.error(`Session not found: ${w}`);if(!G.ok)return console.error(`API error: ${G.status}`);let J=await G.json();if(t())return $0(J);if(console.log(`Session: ${J.id}`),console.log(`Agent: ${J.agent}`),console.log(`When: ${new Date(J.created_at).toLocaleString()} (${yj(J.created_at)})`),J.project_id)console.log(`Project: ${J.project_id}`);if(J.tokens_used)console.log(`Tokens: ${J.tokens_used}`);if(J.summary)console.log(`
587
- Summary:`),console.log(` ${J.summary}`);if(E.events&&J.events.length>0){let A=Number(E.limit),D=J.events.slice(0,A);console.log(`
588
- Events (${D.length}/${J.events.length}):`);let N={file:"\uD83D\uDCC4",task:"\u2713",decision:"\uD83D\uDCA1",git:"\u2387",error:"\u2717",env:"\u2699",rule:"\uD83D\uDCCC",plan:"\uD83D\uDCCB",intent:"\u2192",subagent:"\u25CE"};for(let W of D){let O=N[W.type]??"\xB7",Y=new Date(W.created_at).toLocaleTimeString(),H=(()=>{try{let L=JSON.parse(W.data);return Object.entries(L).map(([F,j])=>`${F}=${String(j).slice(0,50)}`).join(" ")}catch{return W.data.slice(0,80)}})();console.log(` ${O} [${W.type.padEnd(10)}] ${Y} ${H}`)}}if(E.snapshot&&J.snapshot)console.log(`
589
- Snapshot:`),console.log(J.snapshot);else if(E.snapshot&&!J.snapshot)console.log(`
590
- No snapshot stored for this session.`)}),$.command("log <summary>").description("Log a session summary (calls session_log MCP tool)").option("-a, --agent <name>","Agent name","human").option("--agent-version <v>","Agent version string").action(async(w,E)=>{let X=O0(),G=`http://${X.api.host}:${X.api.port}`,J={"Content-Type":"application/json"};if(X.api.secret)J.Authorization=`Bearer ${X.api.secret}`;let A=await fetch(`${G}/mcp/tool`,{method:"POST",headers:J,body:JSON.stringify({name:"session_log",args:{agent:E.agent,agent_version:E.agentVersion,summary:w}})}),D=await A.json();if(!A.ok)return console.error("Error:",D.error);if(t())return $0(D);console.log(D.result)}),$}function uj(){return new $$("status").description("Show system status").action(async()=>{let $=e(),{data:w,error:E}=await $.health.check();if(E){console.error("API unreachable \u2014 is `orc api` running?");return}console.log(`orc API \u25CF running v${w?.version} uptime: ${w?.uptime}s`);let{data:X}=await $.tasks.list({limit:100}),{data:G}=await $.jobs.list(),{data:J}=await $.memories.list();if(t())return $0({api:w,tasks:X?.tasks??[],jobs:G?.jobs??[],memories:J?.memories??[]});let A=Kv(X?.tasks??[],"status");console.log(`
591
- Tasks:`);for(let[D,N]of Object.entries(A))console.log(` ${D.padEnd(20)} ${N}`);console.log(`
592
- Jobs: ${G?.jobs.length??0} defined`),console.log(`Memory: ${J?.memories.length??0} recent entries`)})}function Kv($,w){return $.reduce((E,X)=>{let G=String(X[w]);return E[G]=(E[G]??0)+1,E},{})}async function KE($,w){if(w.length===26)return w;let{data:E}=await $.tasks.list({limit:100}),X=(E?.tasks??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Task not found: ${w}`),null;return X.id}function cj(){let $=new $$("task").description("Manage tasks");return $.command("list").description("List tasks").option("-p, --project <name>","Filter by project name").option("--no-project","Show all tasks across projects").option("-s, --status <status>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").option("--flat","Disable status grouping").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.tasks.list({...G?{project_id:G.id}:{},status:w.status,tag:w.tag,limit:Number(w.limit)});if(A){if(t())return M1(String(A));return console.error("Error:",A)}let D=J?.tasks??[];if(t())return $0({tasks:D,project:G?.name??null});if(D.length===0)return console.log("No tasks found.");let N=new Map;if(X){let{data:O}=await E.projects.list({limit:100});for(let Y of O?.projects??[])N.set(Y.id,Y.name)}else if(G)console.log(VE(G.name,"1")),console.log();let W=X;if(w.status||w.flat)for(let O of D){let Y=hj(O,W?N:void 0);console.log(Y)}else{let O=["review","changes_requested","doing","blocked","todo"],Y=new Map;for(let H of D){let L=Y.get(H.status)??[];L.push(H),Y.set(H.status,L)}for(let H of O){let L=Y.get(H);if(!L||L.length===0)continue;let F=`\u2500\u2500 ${H} (${L.length}) `;console.log(b9(F.padEnd(50,"\u2500"),H));for(let j of L)console.log(hj(j,W?N:void 0));console.log()}}}),$.command("add <title>").description("Create a new task").option("-p, --project <name>","Project name").option("--no-project","Create without project").option("--priority <p>","Priority (low/normal/high/critical)","normal").option("-b, --body <text>","Task body").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.tasks.create({title:w,body:E.body,...J?{project_id:J.id}:{},priority:E.priority});if(D){if(t())return M1(String(D));return console.error("Error:",D)}if(t())return $0(A);console.log(`Created: [${A?.id.slice(-6)}] ${A?.title}`)}),$.command("done <id>").description("Mark task as done (accepts full ULID or last-6 suffix)").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;let{data:G,error:J}=await E.tasks.update(X,{status:"done"});if(J){if(t())return M1(String(J));return console.error("Error:",J)}if(t())return $0(G);console.log(`Done: [${G?.id.slice(-6)}] ${G?.title}`)}),$.command("review <id>").description("Submit task for review").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;let{data:G,error:J}=await E.tasks.update(X,{status:"review"});if(J){if(t())return M1(String(J));return console.error("Error:",J)}if(t())return $0(G);console.log(`In review: [${G?.id.slice(-6)}] ${G?.title}`)}),$.command("approve <id>").description("Approve a task in review (HITL)").option("-c, --comment <text>","Optional comment to add").action(async(w,E)=>{let X=e(),G=await KE(X,w);if(!G)return;let{data:J,error:A}=await X.tasks.get(G);if(A){if(t())return M1(String(A));return console.error("Error:",A)}if(J?.status!=="review")return console.error(`Task is not in review (current: ${J?.status})`);let{data:D,error:N}=await X.tasks.update(G,{status:"done"});if(N){if(t())return M1(String(N));return console.error("Error:",N)}if(E.comment)await X.tasks.addComment(G,E.comment,"human");if(t())return $0(D);console.log(`Approved: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("reject <id>").description("Reject a task in review, request changes (HITL)").option("-r, --reason <text>","Reason for rejection").action(async(w,E)=>{let X=e(),G=await KE(X,w);if(!G)return;let{data:J,error:A}=await X.tasks.get(G);if(A){if(t())return M1(String(A));return console.error("Error:",A)}if(J?.status!=="review")return console.error(`Task is not in review (current: ${J?.status})`);let{data:D,error:N}=await X.tasks.update(G,{status:"changes_requested"});if(N){if(t())return M1(String(N));return console.error("Error:",N)}if(E.reason)await X.tasks.addComment(G,E.reason,"human");if(t())return $0(D);console.log(`Changes requested: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("show <id>").description("Show task details").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;let{data:G,error:J}=await E.tasks.get(X);if(J){if(t())return M1(String(J));return console.error("Error:",J)}if(!G)return console.error("Task not found");if(t()){let{data:W}=await E.tasks.listLinks(X),O=W?.links??[];return $0({...G,links:O})}let A=(W,O)=>{if(O!=null)console.log(` ${VE(W.padEnd(14),"2")} ${O}`)};if(console.log(),console.log(` ${b9(Z9(G.status),G.status)} ${VE(G.title,"1")}`),console.log(),A("ID",G.id),A("Status",`${Z9(G.status)} ${G.status}`),A("Priority",`${nj(G.priority)} ${G.priority}`),A("Progress",`${G.progress}%`),A("Project",G.project_id??void 0),A("Tags",G.tags?.join(", ")??void 0),A("Due",G.due_at??void 0),A("Author",G.author),A("Claimed by",G.claimed_by??void 0),A("Created",G.created_at),A("Updated",G.updated_at),G.body)console.log(),console.log(` ${VE("Body","2")}`),console.log(` ${G.body}`);let{data:D}=await E.tasks.listLinks(X),N=D?.links??[];if(N.length>0){console.log(),console.log(` ${VE("Links","2")}`);for(let W of N){let O=W.from_task_id===X?W.to_task_id:W.from_task_id;console.log(` ${W.link_type} \u2192 [${O.slice(-6)}]`)}}console.log()}),$.command("update <id>").description("Update a task").option("--title <t>","New title").option("--body <text>","New body").option("--status <s>","New status (todo/doing/review/changes_requested/blocked/done/cancelled)").option("--priority <p>","Priority (low/normal/high/critical)").option("--progress <n>","Progress (0-100)").option("--tags <csv>","Comma-separated tags").option("-p, --project <name>","Move to project").option("--no-project","Remove from project").action(async(w,E)=>{let X=e(),G=await KE(X,w);if(!G)return;let J={};if(E.title)J.title=E.title;if(E.body)J.body=E.body;if(E.status)J.status=E.status;if(E.priority)J.priority=E.priority;if(E.progress!==void 0&&E.progress!==!0)J.progress=Number(E.progress);if(E.tags)J.tags=E.tags.split(",").map((W)=>W.trim());if(E.project===!1)J.project_id=null;else if(typeof E.project==="string"){let W=await g1(X,{project:E.project,noProject:!1});if(W)J.project_id=W.id}if(Object.keys(J).length===0)return console.error("No updates specified. Use --help to see options.");if(g$())return u$("update",`task [${G.slice(-6)}]`,J);let{data:D,error:N}=await X.tasks.update(G,J);if(N){if(t())return M1(String(N));return console.error("Error:",N)}if(t())return $0(D);console.log(`Updated: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("delete <id>").description("Delete a task").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;if(g$())return u$("delete",`task [${X.slice(-6)}]`);let{error:G}=await E.tasks.delete(X);if(G){if(t())return M1(String(G));return console.error("Error:",G)}if(t())return $0({deleted:X});console.log(`Deleted: [${X.slice(-6)}]`)}),$}function VE($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}var Vv={review:"33",changes_requested:"33",doing:"36",blocked:"31",todo:"2",done:"32",cancelled:"2"};function b9($,w){return VE($,Vv[w]??"0")}function Z9($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function nj($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function hj($,w){let E=Z9($.status),X=nj($.priority),G=$.id.slice(-6),J=$.title.length>40?`${$.title.slice(0,39)}\u2026`:$.title,A=` ${b9(E,$.status)} ${X} [${G}] ${J.padEnd(40)}`;if(w&&$.project_id)A+=` ${VE(w.get($.project_id)??$.project_id.slice(-6),"2")}`;return A}var m$=new $$().name("orc").description("Human + AI Orchestration Hub").version(lE).option("--db <path>","DB file path (overrides ORC_DB_PATH / config.json)").option("--port <n>","API port (overrides ORC_API_PORT / config.json)").option("--host <host>","API host (overrides ORC_API_HOST / config.json)").option("--secret <secret>","API bearer secret (overrides ORC_API_SECRET / config.json)").option("--log-level <level>","Log level: debug|info|warn|error (overrides ORC_LOG_LEVEL)").option("--runner-timeout <secs>","Default job timeout in seconds (overrides ORC_RUNNER_TIMEOUT)").option("--runner-max-jobs <n>","Max concurrent jobs (overrides ORC_RUNNER_MAX_JOBS)").option("--snapshot-max-bytes <n>","Session snapshot budget bytes (overrides ORC_SNAPSHOT_MAX_BYTES)").option("--json","Machine-readable JSON output").option("--dry-run","Preview changes without executing").hook("preSubcommand",($,w)=>{let E=m$.opts();if(E.db)process.env.ORC_DB_PATH=E.db;if(E.port)process.env.ORC_API_PORT=E.port;if(E.host)process.env.ORC_API_HOST=E.host;if(E.secret)process.env.ORC_API_SECRET=E.secret;if(E.logLevel)process.env.ORC_LOG_LEVEL=E.logLevel;if(E.runnerTimeout)process.env.ORC_RUNNER_TIMEOUT=E.runnerTimeout;if(E.runnerMaxJobs)process.env.ORC_RUNNER_MAX_JOBS=E.runnerMaxJobs;if(E.snapshotMaxBytes)process.env.ORC_SNAPSHOT_MAX_BYTES=E.snapshotMaxBytes});m$.addCommand(cj());m$.addCommand(bj());m$.addCommand(_j());m$.addCommand(Zj());m$.addCommand(gj());m$.addCommand(Pj());m$.addCommand(qj());m$.addCommand(vj());m$.addCommand(uj());m$.addCommand(xj());m$.command("api").description("Start the API server (use --port / --host / --db / --secret to configure)").action(async()=>{await Promise.resolve().then(() => (P9(),V9)),await new Promise(()=>{})});m$.command("home").description("Show ~/.orc directory contents and daemon state").action(()=>{let $=O0();console.log(`ORC home: ${tw}
593
- `);let w=[{label:"DB",path:$.db.path},{label:"config",path:`${tw}/config.json`},{label:"pid",path:bX},{label:"daemon log",path:`${tw}/daemon.log`}];for(let X of w)if(sp(X.path)){let G=Math.round(ap(X.path).size/1024);console.log(` \u2713 ${X.label.padEnd(12)} ${X.path} (${G}KB)`)}else console.log(` \xB7 ${X.label.padEnd(12)} ${X.path} (not found)`);let E=aA();if(console.log(),E)try{process.kill(E,0),console.log(` daemon \u25CF running pid:${E}`)}catch{console.log(` daemon \u25CB stopped (stale pid: ${E})`)}else console.log(" daemon \u25CB not running");console.log(),console.log(` config port:${$.api.port} host:${$.api.host} secret:${$.api.secret?"***":"(none)"}`)});m$.command("mcp").description("Start the MCP server (stdio)").action(async()=>{let{startStdioServer:$}=await PV().then(() => VV);await $()});m$.parseAsync(process.argv).catch(($)=>{console.error($ instanceof Error?$.message:$),process.exit(1)});
566
+ `),sL(),await q3(),await _J(),Cj(),process.stdout.write(`[orc] Stopped.
567
+ `),process.exit(0)};process.on("SIGINT",()=>void X("SIGINT")),process.on("SIGTERM",()=>void X("SIGTERM")),await new Promise(()=>{})}),$.command("stop").description("Stop the running daemon").action(()=>{let w=w6();if(!w){console.log("No daemon running (no pid file at ~/.orc/daemon.pid).");return}try{process.kill(w,"SIGTERM"),console.log(`Sent SIGTERM to daemon (pid ${w}).`)}catch{console.error(`Could not signal pid ${w} - process may already be stopped.`),Cj()}}),$.command("status").description("Show scheduler state and next run times for all active jobs").action(async()=>{let w=e(),{data:E,error:X}=await w.jobs.list();if(X)return console.error("Error:",X);let G=(E?.jobs??[]).filter((A)=>A.enabled&&(A.trigger_type==="cron"||A.trigger_type==="watch"));if(G.length===0){console.log("No scheduled jobs defined."),console.log("Create one with: orc job add <name> --trigger cron --cron '0 22 * * *' ...");return}console.log(`Scheduled jobs:
568
+ `);for(let A of G){let N=A.trigger_type==="cron"?`cron(${A.cron_expr??"?"})`:A.trigger_type,D=A.last_run_at?new Date(A.last_run_at).toISOString().slice(0,19):"never",O=`runs:${A.run_count}`,W=A.enabled?"\u25CF":"\u25CB";console.log(` ${W} ${A.name.padEnd(24)} ${N.padEnd(24)} last:${D.padEnd(20)} ${O}`)}}),$}function vj(){let $=new E$("gateway").description("Inspect and send channel gateway messages");return $.command("status").description("Show enabled adapters and active sessions").action(async()=>{let w=e(),{data:E,error:X}=await w.gateway.status();if(X)console.error(`Error: ${X.error}`),process.exit(1);console.log(E.status)}),$.command("send").description("Send a message to a configured Telegram or Slack chat").requiredOption("--platform <platform>","telegram or slack").requiredOption("--chat <id>","Platform chat/channel ID").requiredOption("--text <text>","Message text").option("--thread <id>","Optional Telegram thread or Slack thread timestamp").action(async(w)=>{let E=e(),{error:X}=await E.gateway.send({platform:w.platform,chat_id:w.chat,text:w.text,thread_id:w.thread});if(X)console.error(`Error: ${X.error}`),process.exit(1);console.log(`Sent message to ${w.platform}:${w.chat}`)}),$}function p(){return process.argv.includes("--json")}function $0($){console.log(JSON.stringify($,null,2))}function jw($){console.error(JSON.stringify({error:$})),process.exit(1)}function c$(){return process.argv.includes("--dry-run")}function r$($,w,E){if(console.log(`[dry-run] Would ${$} ${w}`),E)console.log(JSON.stringify(E,null,2))}R$();import{existsSync as Kf,readFileSync as Vf,writeFileSync as Pf}from"fs";import{homedir as qf}from"os";import{join as Sf}from"path";async function yw($,w){if(w.noProject)return null;let E=w.project??G0().activeProject;if(!E)console.error("No project set. Use -p <name> or 'orc project use <name>'"),process.exit(1);let{data:X,error:G}=await $.projects.getByName(E);if(G||!X)console.error(`Project not found: ${E}`),process.exit(1);return{id:X.id,name:X.name}}function kf($){return{active:"\u25CF",paused:"\u25D0",archived:"\u25CB"}[$]??"?"}function bf($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function _f($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function Zf($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function yj(){return Sf(qf(),".orc","config.json")}function xj(){let $=yj();if(!Kf($))return{};return JSON.parse(Vf($,"utf-8"))}function f4($){Pf(yj(),`${JSON.stringify($,null,2)}
569
+ `)}function gj(){let $=new E$("project").description("Manage projects");return $.command("list").description("List projects").option("--status <s>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.list({status:w.status,tag:w.tag,limit:Number(w.limit)});if(G)return console.error("Error:",G);let A=X?.projects??[];if(p())return $0({projects:A});if(A.length===0)return console.log("No projects found.");for(let N of A){let{data:D}=await E.projects.summary(N.id),W=`${kf(N.status)} ${N.name.padEnd(18)} (${N.status})`;if(D){let J=D.tasks.total,Y=D.tasks.by_status.review??0,H=Y>0?`${J} tasks (${Y} review)`:`${J} tasks`;W+=` ${H} ${D.memories} mems ${D.jobs} jobs`}console.log(W)}}),$.command("add <name>").description("Create a new project").option("-d, --description <text>","Project description").option("--scope <s>","Project scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{if(!/^[a-zA-Z0-9_-]+$/.test(w))return console.error("Invalid project name: only [a-zA-Z0-9_-] characters allowed.");let X=e(),G=E.tags?E.tags.split(",").map((O)=>O.trim()):void 0,{data:A,error:N}=await X.projects.create({name:w,description:E.description,scope:E.scope,tags:G});if(N)return console.error("Error:",N);if(p())return $0(A);if(!G0().activeProject){let O=xj();O.activeProject=w,f4(O)}console.log(`Created: ${A?.name} [${A?.id.slice(-6)}]`)}),$.command("show [name]").description("Show project details").action(async(w)=>{let E=e(),X=w??G0().activeProject;if(!X)return console.error("No project set. Use -p <name> or 'orc project use <name>'");let{data:G,error:A}=await E.projects.getByName(X);if(A||!G)return console.error(`Project not found: ${X}`);let[N,D,O,W]=await Promise.all([E.projects.summary(G.id),E.tasks.list({project_id:G.id}),E.jobs.list({project_id:G.id}),E.memories.list({project_id:G.id})]),J=N.data,Y=D.data?.tasks??[],H=O.data?.jobs??[],L=W.data?.memories??[];if(p())return $0({project:G,summary:J??null,tasks:Y,jobs:H,memories:L});if(console.log(`${G.name} (${G.status})`),G.description)console.log(` ${G.description}`);if(console.log(),J){let M=J.tasks.by_status,R=Object.entries(M).filter(([,B])=>B>0).map(([B,I])=>`${B}: ${I}`);if(console.log(`Tasks (${J.tasks.total})`),R.length>0)console.log(` ${R.join(" ")}`);console.log()}for(let M of Y.slice(0,10)){let R=_f(M.status),B=Zf(M.priority);console.log(` ${R} ${B} [${M.id.slice(-6)}] ${M.title.padEnd(36)} ${M.status}`)}if(Y.length>10)console.log(` ... and ${Y.length-10} more`);console.log(),console.log(`Jobs (${H.length})`);for(let M of H){let R=M.trigger_type==="cron"&&M.cron_expr?`cron(${M.cron_expr})`:M.trigger_type;console.log(` \u25CF ${M.name.padEnd(20)} ${R} runs:${M.run_count}`)}console.log();let F=J?.memories??L.length,j=L.slice(0,5);console.log(`Memories (${j.length} of ${F})`);for(let M of j){let R=M.scope?`[${M.scope}]`:"",B=bf(M.created_at);console.log(` \u2022 ${R} ${M.content.slice(0,50).padEnd(50)} ${B}`)}}),$.command("use <name>").description("Set active project").option("--clear","Unset active project").action(async(w,E)=>{let X=xj();if(E.clear)return delete X.activeProject,f4(X),console.log("Active project cleared");let G=e(),{data:A,error:N}=await G.projects.getByName(w);if(N||!A)return console.error(`Project not found: ${w}`);if(X.activeProject=w,f4(X),p())return $0({activeProject:w});console.log(`Active project: ${w}`)}),$.command("update <name>").description("Update a project").option("--name <n>","New name").option("-d, --description <text>","Description").option("--status <s>","Status (active/paused/archived)").option("--scope <s>","Scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{let X=e(),{data:G,error:A}=await X.projects.getByName(w);if(A||!G)return console.error(`Project not found: ${w}`);if(c$())return r$("update",`project ${w}`);let N=E.tags?E.tags.split(",").map((W)=>W.trim()):void 0,{data:D,error:O}=await X.projects.update(G.id,{name:E.name,description:E.description,status:E.status,scope:E.scope,tags:N});if(O)return console.error("Error:",O);if(p())return $0(D);console.log(`Updated: ${D?.name} [${D?.id.slice(-6)}]`)}),$.command("archive <name>").description("Archive a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(c$())return r$("archive",`project ${w}`);let{data:A,error:N}=await E.projects.update(X.id,{status:"archived"});if(N)return console.error("Error:",N);if(p())return $0(A);console.log(`Archived: ${A?.name} [${A?.id.slice(-6)}]`)}),$.command("delete <name>").description("Delete a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(c$())return r$("delete",`project ${w}`);let{error:A}=await E.projects.delete(X.id);if(A)return console.error("Error:",A);if(p())return $0({deleted:X.id,name:w});console.log(`Deleted project: ${w} [${X.id.slice(-6)}]`)}),$}function uj(){let $=new E$("job").description("Manage jobs");return $.command("list").description("List jobs").option("-p, --project <name>","Filter by project name").option("--no-project","Show all jobs").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await yw(E,{project:w.project,noProject:X}),{data:A,error:N}=await E.jobs.list(G?{project_id:G.id}:{});if(N)return console.error("Error:",N);let D=A?.jobs??[];if(p())return $0({jobs:D});if(D.length===0)return console.log("No jobs found.");for(let O of D){let W=O.enabled?"\u25CF":"\u25CB",J=O.cron_expr?`cron(${O.cron_expr})`:O.trigger_type;console.log(`${W} ${O.name.padEnd(24)} ${J.padEnd(20)} runs:${O.run_count}`)}}),$.command("add <name>").description("Create a job").requiredOption("-c, --command <cmd>","Shell command to run").option("--trigger <type>","Trigger type (manual/cron/watch/one-shot/webhook)","manual").option("--cron <expr>","Cron expression (e.g. '0 22 * * *' or '*/30 * * * * *' every 30s)").option("--watch <path>","Watch path for file changes").option("--timeout <secs>","Timeout in seconds","300").option("--retries <n>","Max retries","0").option("--notify <when>","Notify on: never/failure/always","failure").option("-d, --description <text>","Description").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,A=G?null:await yw(X,{project:E.project,noProject:G}),{data:N,error:D}=await X.jobs.create({name:w,...A?{project_id:A.id}:{},description:E.description,command:E.command,trigger_type:E.trigger,cron_expr:E.cron,watch_path:E.watch,timeout_secs:Number(E.timeout),max_retries:Number(E.retries),notify_on:E.notify});if(D||!N)return console.error("Error:",D);if(p())return $0(N);console.log(`Created job: ${N.name} [${N.id.slice(-6)}]`)}),$.command("run <name-or-id>").description("Manually trigger a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let A=X?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let{data:N,error:D}=await E.jobs.trigger(A.id);if(D||!N)return console.error("Error:",D);if(p())return $0(N);console.log(`Triggered job ${A.name} \u2192 run: ${N.run_id}`)}),$.command("show <name-or-id>").description("Show job details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let A=X?.jobs.find((W)=>W.name===w||W.id===w);if(!A)return console.error(`Job not found: ${w}`);let{data:N,error:D}=await E.jobs.get(A.id);if(D||!N)return console.error("Error:",D);if(p())return $0(N);let O=[["Name",N.name],["ID",N.id],["Description",N.description],["Command",N.command],["Trigger",N.trigger_type],["Cron",N.cron_expr],["Enabled",N.enabled],["Timeout (s)",N.timeout_secs],["Max retries",N.max_retries],["Overlap",N.overlap],["Notify on",N.notify_on],["Project ID",N.project_id],["Run count",N.run_count],["Last run",N.last_run_at],["Created",N.created_at],["Updated",N.updated_at]];for(let[W,J]of O)if(J!==void 0&&J!==null&&J!=="")console.log(`${W.padEnd(14)} ${J}`)}),$.command("delete <name-or-id>").description("Delete a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let A=X?.jobs.find((D)=>D.name===w||D.id===w);if(!A)return console.error(`Job not found: ${w}`);if(c$())return r$("delete",`job ${A.name}`);let{error:N}=await E.jobs.delete(A.id);if(N)return console.error("Error:",N);if(p())return $0({deleted:A.id,name:A.name});console.log(`Deleted job: ${A.name} [${A.id.slice(-6)}]`)}),$.command("update <name-or-id>").description("Update a job").option("--name <n>","New name").option("-d, --description <text>","Description").option("-c, --command <cmd>","Shell command").option("--trigger <type>","Trigger type").option("--cron <expr>","Cron expression").option("--timeout <secs>","Timeout in seconds").option("--retries <n>","Max retries").option("--notify <when>","Notify on: never/failure/always").option("--enabled","Enable the job").option("--disabled","Disable the job").action(async(w,E)=>{let X=e(),{data:G,error:A}=await X.jobs.list();if(A)return console.error("Error:",A);let N=G?.jobs.find((J)=>J.name===w||J.id===w);if(!N)return console.error(`Job not found: ${w}`);let D={};if(E.name)D.name=E.name;if(E.description)D.description=E.description;if(E.command)D.command=E.command;if(E.trigger)D.trigger_type=E.trigger;if(E.cron)D.cron_expr=E.cron;if(E.timeout)D.timeout_secs=Number(E.timeout);if(E.retries)D.max_retries=Number(E.retries);if(E.notify)D.notify_on=E.notify;if(E.enabled)D.enabled=!0;if(E.disabled)D.enabled=!1;if(c$())return r$("update",`job ${N.name}`,D);let{data:O,error:W}=await X.jobs.update(N.id,D);if(W||!O)return console.error("Error:",W);if(p())return $0(O);console.log(`Updated job: ${O.name} [${O.id.slice(-6)}]`)}),$.command("runs <name-or-id>").description("Show recent runs for a job").option("-l, --limit <n>","Max results","10").option("-s, --sessions","Show linked agent sessions per run").option("--logs","Show stdout/stderr logs for each run").action(async(w,E)=>{let X=e(),{data:G,error:A}=await X.jobs.list();if(A)return console.error("Error:",A);let N=G?.jobs.find((J)=>J.name===w||J.id===w);if(!N)return console.error(`Job not found: ${w}`);let{data:D,error:O}=await X.jobs.runs(N.id,Number(E.limit));if(O)return console.error("Error:",O);let W=D?.runs??[];if(p())return $0({runs:W});if(W.length===0)return console.log("No runs yet.");for(let J of W){let Y=Cf(J.status),H=J.started_at&&J.ended_at?`${Math.round((new Date(J.ended_at).getTime()-new Date(J.started_at).getTime())/1000)}s`:"-";if(console.log(`${Y} ${J.status.padEnd(10)} ${J.created_at.slice(0,19)} ${H} [${J.id.slice(-6)}]`),E.logs){let{data:L}=await X.jobs.runLogs(N.id,J.id);for(let F of L?.logs??[]){let j=F.stream==="stderr"?" ERR":" OUT";console.log(`${j} ${F.line}`)}}if(E.sessions){let{data:L}=await X.sessions.list({job_run_id:J.id,limit:5});for(let F of L?.sessions??[]){let j=F.summary?` ${F.summary.split(`
570
+ `)[0]?.slice(0,60)}`:"";console.log(` \u21B3 session ${F.agent}${F.agent_version?`/${F.agent_version}`:""}${j}`)}}}}),$}function Cf($){return{pending:"\u25CB",running:"\u25D0",success:"\u25CF",failed:"\u2715",cancelled:"\u2298",skipped:"\u21B7"}[$]??"?"}function hj(){let $=new E$("mem").description("Manage memory");return $.command("search <query>").description("Search memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","10").option("-p, --project <name>","Filter by project name").option("--no-project","Search all memories").action(async(w,E)=>{let X=e(),G=E.project===!1,A=G?null:await yw(X,{project:E.project,noProject:G}),{data:N,error:D}=await X.memories.search(w,{scope:E.scope,...A?{project_id:A.id}:{},limit:Number(E.limit)});if(D)return console.error("Error:",D);let O=N?.results??[];if(p())return $0({results:O});if(O.length===0)return console.log("No memories found.");for(let W of O){let J=nj(W.created_at),Y=W.scope?`[${W.scope}]`:"";console.log(`\u2022 ${W.content.slice(0,80)} ${Y} ${J}`)}}),$.command("add <content>").description("Store a memory").option("-s, --scope <scope>","Scope").option("--type <type>","Type (fact/decision/event/rule/discovery)","fact").option("--source <source>","Source reference").option("--importance <level>","Importance (low/normal/high/critical)","normal").option("-t, --tags <tags>","Comma-separated tags").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,A=G?null:await yw(X,{project:E.project,noProject:G}),{data:N,error:D}=await X.memories.create({content:w,...A?{project_id:A.id}:{},type:E.type,scope:E.scope,source:E.source,importance:E.importance,...E.tags?{tags:E.tags.split(",").map((O)=>O.trim())}:{}});if(D)return console.error("Error:",D);if(p())return $0(N);console.log(`Stored: [${N?.id.slice(-6)}] [${E.type}] ${N?.content.slice(0,60)}`)}),$.command("list").description("List recent memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","20").option("-p, --project <name>","Filter by project name").option("--no-project","Show all memories").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await yw(E,{project:w.project,noProject:X}),{data:A,error:N}=await E.memories.list({scope:w.scope,...G?{project_id:G.id}:{},limit:Number(w.limit)});if(N)return console.error("Error:",N);let D=A?.memories??[];if(p())return $0({memories:D});if(D.length===0)return console.log("No memories found.");for(let O of D){let W=nj(O.created_at),J=O.scope?`[${O.scope}]`:"";console.log(`\u2022 [${O.id.slice(-6)}] ${O.content.slice(0,70)} ${J} ${W}`)}}),$.command("show <id>").description("Show memory details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let A=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!A)return console.error(`Memory not found: ${w}`);if(p())return $0(A);let N=[["ID",A.id],["Content",A.content],["Scope",A.scope],["Source",A.source],["Importance",A.importance],["Project ID",A.project_id],["Tags",A.tags?.join(", ")],["Expires",A.expires_at],["Created",A.created_at],["Updated",A.updated_at]];for(let[D,O]of N)if(O!==void 0&&O!==null&&O!=="")console.log(`${D.padEnd(14)} ${O}`)}),$.command("delete <id>").description("Delete a memory").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let A=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!A)return console.error(`Memory not found: ${w}`);if(c$())return r$("delete",`memory [${A.id.slice(-6)}]`,{content:A.content.slice(0,80)});let{error:N}=await E.memories.delete(A.id);if(N)return console.error("Error:",N);if(p())return $0({deleted:A.id});console.log(`Deleted memory: [${A.id.slice(-6)}] ${A.content.slice(0,60)}`)}),$}function nj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function cj(){let $=new E$("prompt").description("Manage prompts and skills");return $.command("list").description("List prompts").option("--skill","Show skills only").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.prompts.list({limit:Number(w.limit)});if(G)return console.error("Error:",G);let A=X?.prompts??[];if(w.skill)A=A.filter((N)=>N.is_skill);if(p())return $0({prompts:A});if(A.length===0)return console.log("No prompts found.");for(let N of A){let D=N.id.slice(-6),O=N.is_skill?MA(" [skill]","36"):"",W=MA(`v${N.version}`,"2"),J=N.name.length>40?`${N.name.slice(0,39)}\u2026`:N.name;console.log(` [${D}] ${J.padEnd(42)} ${W}${O}`)}}),$.command("show <id>").description("Show prompt details").action(async(w)=>{let E=e(),X=await jA(E,w);if(!X)return;let{data:G,error:A}=await E.prompts.get(X);if(A)return console.error("Error:",A);if(!G)return console.error("Prompt not found.");if(p())return $0(G);if(console.log(MA(G.name,"1")),console.log(),G.description)console.log(` ${G.description}`);if(console.log(` id: ${G.id}`),console.log(` version: ${G.version}`),console.log(` is_skill: ${G.is_skill}`),G.skill_dir)console.log(` skill_dir: ${G.skill_dir}`);if(G.skill_version)console.log(` skill_ver: ${G.skill_version}`);if(console.log(` pinned: ${G.pinned}`),G.tags?.length)console.log(` tags: ${G.tags.join(", ")}`);if(G.last_used_at)console.log(` last_used: ${G.last_used_at}`);console.log(` created: ${G.created_at}`),console.log(` updated: ${G.updated_at}`),console.log(),console.log(MA("\u2500\u2500 template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","2")),console.log(G.template)}),$.command("add <name>").description("Create a new prompt").option("-c, --content <text>","Prompt template content").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").action(async(w,E)=>{let X=e(),G=E.content??"",{data:A,error:N}=await X.prompts.create({name:w,template:G,description:E.description,is_skill:E.skill??!1,tags:E.tags?E.tags.split(",").map((D)=>D.trim()):void 0,pinned:E.pinned??!1});if(N)return console.error("Error:",N);if(p())return $0(A);console.log(`Created: [${A?.id.slice(-6)}] ${A?.name}`)}),$.command("update <id>").description("Update a prompt").option("-c, --content <text>","Prompt template content").option("-n, --name <name>","Prompt name").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--no-skill","Unmark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").option("--no-pinned","Unpin this prompt").action(async(w,E)=>{let X=e(),G=await jA(X,w);if(!G)return;let A={};if(E.content!==void 0)A.template=E.content;if(E.name!==void 0)A.name=E.name;if(E.description!==void 0)A.description=E.description;if(E.skill!==void 0)A.is_skill=E.skill;if(E.tags)A.tags=E.tags.split(",").map((O)=>O.trim());if(E.pinned!==void 0)A.pinned=E.pinned;if(c$())return r$("update",`prompt [${G.slice(-6)}]`,A);let{data:N,error:D}=await X.prompts.update(G,A);if(D)return console.error("Error:",D);if(p())return $0(N);console.log(`Updated: [${N?.id.slice(-6)}] ${N?.name}`)}),$.command("delete <id>").description("Delete a prompt").action(async(w)=>{let E=e(),X=await jA(E,w);if(!X)return;if(c$())return r$("delete",`prompt ${X}`);let{error:G}=await E.prompts.delete(X);if(G)return console.error("Error:",G);if(p())return $0({deleted:X});console.log(`Deleted: ${X}`)}),$.command("render <id>").description("Render a prompt with variables").option("--var <key=value>","Variable (repeatable)",ff,[]).action(async(w,E)=>{let X=e(),G=await jA(X,w);if(!G)return;let A={};for(let O of E.var){let W=O.indexOf("=");if(W===-1)return console.error(`Invalid variable format: ${O} (expected key=value)`);A[O.slice(0,W)]=O.slice(W+1)}let{data:N,error:D}=await X.prompts.render(G,A);if(D)return console.error("Error:",D);if(p())return $0(N);console.log(N?.rendered)}),$.command("history <id>").description("Show version history").option("-l, --limit <n>","Max results","20").action(async(w,E)=>{let X=e(),G=await jA(X,w);if(!G)return;let{data:A,error:N}=await X.prompts.history(G,Number(E.limit));if(N)return console.error("Error:",N);let D=A?.history??[];if(p())return $0({history:D});if(D.length===0)return console.log("No history found.");for(let O of D){let W=O.changed_at.slice(0,19).replace("T"," ");console.log(` v${String(O.version).padEnd(4)} ${MA(W,"2")} by ${O.changed_by} ${O.name}`)}}),$}function ff($,w){return w.concat([$])}async function jA($,w){if(w.length===26)return w;let{data:E}=await $.prompts.list({limit:200}),X=(E?.prompts??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Prompt not found: ${w}`),null;return X.id}function MA($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}R$();var rj=["task","memory","job","project","prompt","session"];function vf(){try{let $=G0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function xf(){let $={},w=process.env.ORC_API_SECRET??(()=>{try{return G0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}var yf={task:["Task","CreateTask","UpdateTask","Comment","TaskLink"],memory:["Memory","CreateMemory"],job:["Job","CreateJob","UpdateJob","JobRun"],project:["Project","CreateProject","UpdateProject"],prompt:["Prompt","CreatePrompt","UpdatePrompt"],session:["Session"]};function tj(){return new E$("schema").description("Show resource schemas from the OpenAPI spec (requires running API)").argument("[resource]",`Resource name: ${rj.join(", ")}`).option("--list","List available schema names").action(async(w,E)=>{let X;try{X=await fetch(`${vf()}/openapi.json`,{headers:xf()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let A=(await X.json()).components?.schemas;if(!A)return console.error("No schemas found in OpenAPI spec.");if(E?.list||!w){console.log("Available schemas:");for(let W of Object.keys(A).sort())console.log(` ${W}`);return}let N=w.toLowerCase(),D=yf[N];if(!D)return console.error(`Unknown resource: ${w}. Available: ${rj.join(", ")}`);let O={};for(let W of D)if(A[W])O[W]=A[W];if(Object.keys(O).length===0)return console.error(`No schemas found for: ${w}`);console.log(JSON.stringify(O,null,2))})}R$();function oj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function v4(){try{let $=G0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function x4(){let $={"Content-Type":"application/json"},w=process.env.ORC_API_SECRET??(()=>{try{return G0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}function mj(){let $=new E$("session").description("View session history");return $.command("list").description("List recent sessions").option("-a, --agent <agent>","Filter by agent (claude-code, cursor, codex)").option("-n, --limit <n>","Max results","20").action(async(w)=>{let E=new URLSearchParams({limit:w.limit});if(w.agent)E.set("agent",w.agent);let X;try{X=await fetch(`${v4()}/sessions?${E}`,{headers:x4()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let A=(await X.json()).sessions;if(p())return $0({sessions:A});if(A.length===0)return console.log("No sessions recorded yet.");console.log(`${"ID".padEnd(8)} ${"AGENT".padEnd(16)} ${"WHEN".padEnd(10)} SUMMARY`),console.log("\u2500".repeat(72));for(let N of A){let D=N.id.slice(-6),O=N.agent.padEnd(16),W=oj(N.created_at).padEnd(10),J=(N.summary??"\u2014").slice(0,40);console.log(`${D} ${O} ${W} ${J}`)}}),$.command("show <id>").description("Show session detail with events").option("-e, --events","Show recorded events").option("-s, --snapshot","Show snapshot XML").option("-n, --limit <n>","Max events to show","50").action(async(w,E)=>{let X=w;if(w.length<26){let N=await fetch(`${v4()}/sessions?limit=100`,{headers:x4()}).catch(()=>null);if(N?.ok){let O=(await N.json()).sessions.find((W)=>W.id.endsWith(w)||W.id===w);if(O)X=O.id}}let G;try{G=await fetch(`${v4()}/sessions/${X}`,{headers:x4()})}catch{return console.error("Cannot connect to orc API.")}if(G.status===404)return console.error(`Session not found: ${w}`);if(!G.ok)return console.error(`API error: ${G.status}`);let A=await G.json();if(p())return $0(A);if(console.log(`Session: ${A.id}`),console.log(`Agent: ${A.agent}`),console.log(`When: ${new Date(A.created_at).toLocaleString()} (${oj(A.created_at)})`),A.project_id)console.log(`Project: ${A.project_id}`);if(A.tokens_used)console.log(`Tokens: ${A.tokens_used}`);if(A.summary)console.log(`
571
+ Summary:`),console.log(` ${A.summary}`);if(E.events&&A.events.length>0){let N=Number(E.limit),D=A.events.slice(0,N);console.log(`
572
+ Events (${D.length}/${A.events.length}):`);let O={file:"\uD83D\uDCC4",task:"\u2713",decision:"\uD83D\uDCA1",git:"\u2387",error:"\u2717",env:"\u2699",rule:"\uD83D\uDCCC",plan:"\uD83D\uDCCB",intent:"\u2192",subagent:"\u25CE"};for(let W of D){let J=O[W.type]??"\xB7",Y=new Date(W.created_at).toLocaleTimeString(),H=(()=>{try{let L=JSON.parse(W.data);return Object.entries(L).map(([F,j])=>`${F}=${String(j).slice(0,50)}`).join(" ")}catch{return W.data.slice(0,80)}})();console.log(` ${J} [${W.type.padEnd(10)}] ${Y} ${H}`)}}if(E.snapshot&&A.snapshot)console.log(`
573
+ Snapshot:`),console.log(A.snapshot);else if(E.snapshot&&!A.snapshot)console.log(`
574
+ No snapshot stored for this session.`)}),$.command("log <summary>").description("Log a session summary (calls session_log MCP tool)").option("-a, --agent <name>","Agent name","human").option("--agent-version <v>","Agent version string").action(async(w,E)=>{let X=G0(),G=`http://${X.api.host}:${X.api.port}`,A={"Content-Type":"application/json"};if(X.api.secret)A.Authorization=`Bearer ${X.api.secret}`;let N=await fetch(`${G}/mcp/tool`,{method:"POST",headers:A,body:JSON.stringify({name:"session_log",args:{agent:E.agent,agent_version:E.agentVersion,summary:w}})}),D=await N.json();if(!N.ok)return console.error("Error:",D.error);if(p())return $0(D);console.log(D.result)}),$}function ij(){return new E$("status").description("Show system status").action(async()=>{let $=e(),{data:w,error:E}=await $.health.check();if(E){console.error("API unreachable \u2014 is `orc api` running?");return}console.log(`orc API \u25CF running v${w?.version} uptime: ${w?.uptime}s`);let{data:X}=await $.tasks.list({limit:100}),{data:G}=await $.jobs.list(),{data:A}=await $.memories.list();if(p())return $0({api:w,tasks:X?.tasks??[],jobs:G?.jobs??[],memories:A?.memories??[]});let N=gf(X?.tasks??[],"status");console.log(`
575
+ Tasks:`);for(let[D,O]of Object.entries(N))console.log(` ${D.padEnd(20)} ${O}`);console.log(`
576
+ Jobs: ${G?.jobs.length??0} defined`),console.log(`Memory: ${A?.memories.length??0} recent entries`)})}function gf($,w){return $.reduce((E,X)=>{let G=String(X[w]);return E[G]=(E[G]??0)+1,E},{})}async function P1($,w){if(w.length===26)return w;let{data:E}=await $.tasks.list({limit:100}),X=(E?.tasks??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Task not found: ${w}`),null;return X.id}function dj(){let $=new E$("task").description("Manage tasks");return $.command("list").description("List tasks").option("-p, --project <name>","Filter by project name").option("--no-project","Show all tasks across projects").option("-s, --status <status>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").option("--flat","Disable status grouping").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await yw(E,{project:w.project,noProject:X}),{data:A,error:N}=await E.tasks.list({...G?{project_id:G.id}:{},status:w.status,tag:w.tag,limit:Number(w.limit)});if(N){if(p())return jw(String(N));return console.error("Error:",N)}let D=A?.tasks??[];if(p())return $0({tasks:D,project:G?.name??null});if(D.length===0)return console.log("No tasks found.");let O=new Map;if(X){let{data:J}=await E.projects.list({limit:100});for(let Y of J?.projects??[])O.set(Y.id,Y.name)}else if(G)console.log(q1(G.name,"1")),console.log();let W=X;if(w.status||w.flat)for(let J of D){let Y=pj(J,W?O:void 0);console.log(Y)}else{let J=["review","changes_requested","doing","blocked","todo"],Y=new Map;for(let H of D){let L=Y.get(H.status)??[];L.push(H),Y.set(H.status,L)}for(let H of J){let L=Y.get(H);if(!L||L.length===0)continue;let F=`\u2500\u2500 ${H} (${L.length}) `;console.log(y4(F.padEnd(50,"\u2500"),H));for(let j of L)console.log(pj(j,W?O:void 0));console.log()}}}),$.command("add <title>").description("Create a new task").option("-p, --project <name>","Project name").option("--no-project","Create without project").option("--priority <p>","Priority (low/normal/high/critical)","normal").option("-b, --body <text>","Task body").action(async(w,E)=>{let X=e(),G=E.project===!1,A=G?null:await yw(X,{project:E.project,noProject:G}),{data:N,error:D}=await X.tasks.create({title:w,body:E.body,...A?{project_id:A.id}:{},priority:E.priority});if(D){if(p())return jw(String(D));return console.error("Error:",D)}if(p())return $0(N);console.log(`Created: [${N?.id.slice(-6)}] ${N?.title}`)}),$.command("done <id>").description("Mark task as done (accepts full ULID or last-6 suffix)").action(async(w)=>{let E=e(),X=await P1(E,w);if(!X)return;let{data:G,error:A}=await E.tasks.update(X,{status:"done"});if(A){if(p())return jw(String(A));return console.error("Error:",A)}if(p())return $0(G);console.log(`Done: [${G?.id.slice(-6)}] ${G?.title}`)}),$.command("review <id>").description("Submit task for review").action(async(w)=>{let E=e(),X=await P1(E,w);if(!X)return;let{data:G,error:A}=await E.tasks.update(X,{status:"review"});if(A){if(p())return jw(String(A));return console.error("Error:",A)}if(p())return $0(G);console.log(`In review: [${G?.id.slice(-6)}] ${G?.title}`)}),$.command("approve <id>").description("Approve a task in review (HITL)").option("-c, --comment <text>","Optional comment to add").action(async(w,E)=>{let X=e(),G=await P1(X,w);if(!G)return;let{data:A,error:N}=await X.tasks.get(G);if(N){if(p())return jw(String(N));return console.error("Error:",N)}if(A?.status!=="review")return console.error(`Task is not in review (current: ${A?.status})`);let{data:D,error:O}=await X.tasks.update(G,{status:"done"});if(O){if(p())return jw(String(O));return console.error("Error:",O)}if(E.comment)await X.tasks.addComment(G,E.comment,"human");if(p())return $0(D);console.log(`Approved: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("reject <id>").description("Reject a task in review, request changes (HITL)").option("-r, --reason <text>","Reason for rejection").action(async(w,E)=>{let X=e(),G=await P1(X,w);if(!G)return;let{data:A,error:N}=await X.tasks.get(G);if(N){if(p())return jw(String(N));return console.error("Error:",N)}if(A?.status!=="review")return console.error(`Task is not in review (current: ${A?.status})`);let{data:D,error:O}=await X.tasks.update(G,{status:"changes_requested"});if(O){if(p())return jw(String(O));return console.error("Error:",O)}if(E.reason)await X.tasks.addComment(G,E.reason,"human");if(p())return $0(D);console.log(`Changes requested: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("show <id>").description("Show task details").action(async(w)=>{let E=e(),X=await P1(E,w);if(!X)return;let{data:G,error:A}=await E.tasks.get(X);if(A){if(p())return jw(String(A));return console.error("Error:",A)}if(!G)return console.error("Task not found");if(p()){let{data:W}=await E.tasks.listLinks(X),J=W?.links??[];return $0({...G,links:J})}let N=(W,J)=>{if(J!=null)console.log(` ${q1(W.padEnd(14),"2")} ${J}`)};if(console.log(),console.log(` ${y4(g4(G.status),G.status)} ${q1(G.title,"1")}`),console.log(),N("ID",G.id),N("Status",`${g4(G.status)} ${G.status}`),N("Priority",`${lj(G.priority)} ${G.priority}`),N("Progress",`${G.progress}%`),N("Project",G.project_id??void 0),N("Tags",G.tags?.join(", ")??void 0),N("Due",G.due_at??void 0),N("Author",G.author),N("Claimed by",G.claimed_by??void 0),N("Created",G.created_at),N("Updated",G.updated_at),G.body)console.log(),console.log(` ${q1("Body","2")}`),console.log(` ${G.body}`);let{data:D}=await E.tasks.listLinks(X),O=D?.links??[];if(O.length>0){console.log(),console.log(` ${q1("Links","2")}`);for(let W of O){let J=W.from_task_id===X?W.to_task_id:W.from_task_id;console.log(` ${W.link_type} \u2192 [${J.slice(-6)}]`)}}console.log()}),$.command("update <id>").description("Update a task").option("--title <t>","New title").option("--body <text>","New body").option("--status <s>","New status (todo/doing/review/changes_requested/blocked/done/cancelled)").option("--priority <p>","Priority (low/normal/high/critical)").option("--progress <n>","Progress (0-100)").option("--tags <csv>","Comma-separated tags").option("-p, --project <name>","Move to project").option("--no-project","Remove from project").action(async(w,E)=>{let X=e(),G=await P1(X,w);if(!G)return;let A={};if(E.title)A.title=E.title;if(E.body)A.body=E.body;if(E.status)A.status=E.status;if(E.priority)A.priority=E.priority;if(E.progress!==void 0&&E.progress!==!0)A.progress=Number(E.progress);if(E.tags)A.tags=E.tags.split(",").map((W)=>W.trim());if(E.project===!1)A.project_id=null;else if(typeof E.project==="string"){let W=await yw(X,{project:E.project,noProject:!1});if(W)A.project_id=W.id}if(Object.keys(A).length===0)return console.error("No updates specified. Use --help to see options.");if(c$())return r$("update",`task [${G.slice(-6)}]`,A);let{data:D,error:O}=await X.tasks.update(G,A);if(O){if(p())return jw(String(O));return console.error("Error:",O)}if(p())return $0(D);console.log(`Updated: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("delete <id>").description("Delete a task").action(async(w)=>{let E=e(),X=await P1(E,w);if(!X)return;if(c$())return r$("delete",`task [${X.slice(-6)}]`);let{error:G}=await E.tasks.delete(X);if(G){if(p())return jw(String(G));return console.error("Error:",G)}if(p())return $0({deleted:X});console.log(`Deleted: [${X.slice(-6)}]`)}),$}function q1($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}var uf={review:"33",changes_requested:"33",doing:"36",blocked:"31",todo:"2",done:"32",cancelled:"2"};function y4($,w){return q1($,uf[w]??"0")}function g4($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function lj($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function pj($,w){let E=g4($.status),X=lj($.priority),G=$.id.slice(-6),A=$.title.length>40?`${$.title.slice(0,39)}\u2026`:$.title,N=` ${y4(E,$.status)} ${X} [${G}] ${A.padEnd(40)}`;if(w&&$.project_id)N+=` ${q1(w.get($.project_id)??$.project_id.slice(-6),"2")}`;return N}var i$=new E$().name("orc").description("Human + AI Orchestration Hub").version(a1).option("--db <path>","DB file path (overrides ORC_DB_PATH / config.json)").option("--port <n>","API port (overrides ORC_API_PORT / config.json)").option("--host <host>","API host (overrides ORC_API_HOST / config.json)").option("--secret <secret>","API bearer secret (overrides ORC_API_SECRET / config.json)").option("--log-level <level>","Log level: debug|info|warn|error (overrides ORC_LOG_LEVEL)").option("--runner-timeout <secs>","Default job timeout in seconds (overrides ORC_RUNNER_TIMEOUT)").option("--runner-max-jobs <n>","Max concurrent jobs (overrides ORC_RUNNER_MAX_JOBS)").option("--snapshot-max-bytes <n>","Session snapshot budget bytes (overrides ORC_SNAPSHOT_MAX_BYTES)").option("--json","Machine-readable JSON output").option("--dry-run","Preview changes without executing").hook("preSubcommand",($,w)=>{let E=i$.opts();if(E.db)process.env.ORC_DB_PATH=E.db;if(E.port)process.env.ORC_API_PORT=E.port;if(E.host)process.env.ORC_API_HOST=E.host;if(E.secret)process.env.ORC_API_SECRET=E.secret;if(E.logLevel)process.env.ORC_LOG_LEVEL=E.logLevel;if(E.runnerTimeout)process.env.ORC_RUNNER_TIMEOUT=E.runnerTimeout;if(E.runnerMaxJobs)process.env.ORC_RUNNER_MAX_JOBS=E.runnerMaxJobs;if(E.snapshotMaxBytes)process.env.ORC_SNAPSHOT_MAX_BYTES=E.snapshotMaxBytes});i$.addCommand(dj());i$.addCommand(gj());i$.addCommand(hj());i$.addCommand(uj());i$.addCommand(mj());i$.addCommand(fj());i$.addCommand(vj());i$.addCommand(cj());i$.addCommand(ij());i$.addCommand(tj());i$.command("api").description("Start the API server (use --port / --host / --db / --secret to configure)").action(async()=>{await Promise.resolve().then(() => (C4(),Z4)),await new Promise(()=>{})});i$.command("home").description("Show ~/.orc directory contents and daemon state").action(()=>{let $=G0();console.log(`ORC home: ${pE}
577
+ `);let w=[{label:"DB",path:$.db.path},{label:"config",path:`${pE}/config.json`},{label:"pid",path:fX},{label:"daemon log",path:`${pE}/daemon.log`}];for(let X of w)if(Ym(X.path)){let G=Math.round(Hm(X.path).size/1024);console.log(` \u2713 ${X.label.padEnd(12)} ${X.path} (${G}KB)`)}else console.log(` \xB7 ${X.label.padEnd(12)} ${X.path} (not found)`);let E=w6();if(console.log(),E)try{process.kill(E,0),console.log(` daemon \u25CF running pid:${E}`)}catch{console.log(` daemon \u25CB stopped (stale pid: ${E})`)}else console.log(" daemon \u25CB not running");console.log(),console.log(` config port:${$.api.port} host:${$.api.host} secret:${$.api.secret?"***":"(none)"}`)});i$.command("mcp").description("Start the MCP server (stdio)").action(async()=>{let{startStdioServer:$}=await fV().then(() => CV);await $()});i$.parseAsync(process.argv).catch(($)=>{console.error($ instanceof Error?$.message:$),process.exit(1)});