tempest.games 0.1.19 → 0.1.21

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.
@@ -1,25 +1,56 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var z4=Object.create;var{getPrototypeOf:_4,defineProperty:hW,getOwnPropertyNames:H4}=Object;var D4=Object.prototype.hasOwnProperty;var R7=(T,S,$)=>{$=T!=null?z4(_4(T)):{};let f=S||!T||!T.__esModule?hW($,"default",{value:T,enumerable:!0}):$;for(let M of H4(T))if(!D4.call(f,M))hW(f,M,{get:()=>T[M],enumerable:!0});return f};var O7=(T,S)=>()=>(S||T((S={exports:{}}).exports,S),S.exports);var E4=(T,S)=>{for(var $ in S)hW(T,$,{get:S[$],enumerable:!0,configurable:!0,set:(f)=>S[$]=()=>f})};function Cf(T=Math.random){return T().toString(36).slice(2)}class LM extends Promise{fate;resolve;reject;done=!1;constructor(T){let S,$;super((f,M)=>{S=f,$=M});this.resolve=S,this.reject=$,this.use(T instanceof Promise?T:new Promise(T))}pass(T,S){if(T===this.fate)this.resolve(S),this.done=!0}fail(T,S){if(T===this.fate)this.reject(S),this.done=!0}use(T){if(T instanceof Promise){let S=T;this.fate=S,S.then(($)=>{this.pass(S,$)},($)=>{this.fail(S,$)})}else this.resolve(T),this.fate=void 0}}function H7(T){return Object.entries(T)}var zA=(T,S,$=XT.STORE)=>{return pS($,{key:`${T.key}:JSON`,get:({get:f})=>S.toJson(f(T)),set:({set:f},M)=>{f(T,S.fromJson(M))}})};function I(T){while(T.child!==null)T=T.child;return T}function _A(T){while(T.parent!==null)T=T.parent;return T}class JT{Subscriber;subscribers=new Map;subscribe(T,S){return this.subscribers.set(T,S),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let S=this.subscribers.values();for(let $ of S)$(T)}}class vW extends JT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function W$(T,S,$){let f={key:S.key,type:"atom_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","atom_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new JT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},y=`${S.key}(${k})`,K=I(T),G=S.default,z={key:y,default:G instanceof Function?G(A):G};if(S.effects)z.effects=S.effects(A);let Q=_S(K,z,X);return J.next({type:"state_creation",token:Q}),Q},f,{subject:J,install:(A)=>W$(A,S),internalRoles:$});return T.families.set(S.key,W),T.defaults.set(S.key,S.default),f}function HA(T,S){if("mutable"in S)return NM(T,S);return W$(T,S)}function R$(T,S,$){let f={key:S.key,type:"readonly_selector_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","readonly_selector_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new JT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},y=`${S.key}(${k})`,K=I(T),G=CM(K,{key:y,get:S.get(A)},X);return J.next({type:"state_creation",token:G}),G},f,{internalRoles:$,subject:J,install:(A)=>R$(A,S),default:(A)=>{return S.get(A)({get:(...X)=>KT(T,...X),find:(X,y)=>OT(T,X,y),seek:(X,y)=>jT(T,X,y),json:(X)=>nT(T,X)})}});return T.families.set(S.key,W),f}function xM(T,S){if("set"in S)return jM(T,S);return R$(T,S)}var Q4={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function xf(T,S){let $=e(S),f=`${T.key}(${$})`,M=Q4[T.type],J={key:f,type:M};if(M==="molecule")Object.assign(J,{key:S,family:T});else Object.assign(J,{family:{key:T.key,subKey:$}});return Object.assign(J,{counterfeit:!0}),J}function kS(T){let S={key:T.key,type:T.type};if("family"in T)S.family=T.family;return S}var d7=Symbol("provenance");function PW(T,S,$){let f=e($);try{let M=[],J;if(S==="root")M.push(T.molecules.get('"root"')),J="all";else if(typeof S==="string"&&S.startsWith(U4)){J="any";let X=e(S),y=T.molecules.get(X);if(!y)throw new Error(`Molecule ${X} not found in store "${T.config.name}"`);M.push(y)}else if($.startsWith("T$--")){J="all";for(let y of S){let K=e(y),G=T.molecules.get(K);if(!G)throw new Error(`Molecule ${K} not found in store "${T.config.name}"`);M.push(G)}}else{J="any";let y=e(S),K=T.molecules.get(y);if(!K)throw new Error(`Molecule ${y} not found in store "${T.config.name}"`);M.push(K)}let F=new jf(M,$);F._dependsOn=J,T.molecules.set(f,F);for(let X of M)X.below.set(F.stringKey,F);let W={type:"molecule_creation",subType:"modern",key:F.key,provenance:S},A=I(T);if(wT(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(W);else A.on.moleculeCreationStart.next(W)}catch(M){if(M instanceof Error)T.logger.error("\u274C","molecule",f,"allocation failed:",M.message)}return $}function IM(T,S){let $=e(S),f=T.molecules.get($);if(!f)throw new Error(`Molecule ${$} not found in store "${T.config.name}"`);for(let k of f.joins.values())k.relations.delete(f.key),k.molecules.delete(f.stringKey);let M;if(f.above.size===1)M=f.above.values().next().value.key;else M=[...f.above.values()].map(({key:k})=>k);let J=[];for(let k of f.tokens.values()){let X=k.family;J.push([X.key,T.valueMap.get(k.key)])}for(let k of f.tokens.values())RS(T,k);for(let k of f.below.values())if(k.dependsOn==="all")IM(T,k.key);else if(k.above.delete(f.stringKey),k.above.size===0)IM(T,k.key);f.below.clear();let F={type:"molecule_disposal",subType:"modern",key:f.key,values:J,provenance:M},W=I(T);if(wT(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(F);else W.on.moleculeDisposal.next(F);W.molecules.delete(f.stringKey);for(let k of f.above.values())k.below.delete(f.stringKey)}var U4="T$";function If(T){return DA(XT.STORE,T)}function e$(T){return HA(XT.STORE,T)}function nW(...T){if(T.length===2)return KT(XT.STORE,...T);return KT(XT.STORE,...T)}var cW=(T)=>(S,$,f,M,...J)=>{console[T](`${S} ${$} "${f}" ${M}`,...J)},V4={error:cW("error"),info:cW("info"),warn:cW("warn")};class oW{T;S;$;constructor(T,S,$=V4){this.logLevel=T;this.filter=S;this.logger=$}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}function iJ(T){return xM(XT.STORE,T)}function bM(T){return gW(T,XT.STORE)}class BS{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,S)=>`${T}:${S}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,S){let $=this.relations.get(T),f=this.relations.get(S);if($)$.add(S);else $=new Set([S]),this.relations.set(T,$);if(f)f.add(T);else f=new Set([T]),this.relations.set(S,f)}deleteRelation(T,S){let $=this.relations.get(T);if($){if($.delete(S),$.size===0)this.relations.delete(T);let f=this.relations.get(S);if(f){if(f.delete(T),f.size===0)this.relations.delete(S)}}}replaceRelationsUnsafely(T,S){this.relations.set(T,new Set(S));for(let $ of S){let f=new Set().add(T);this.relations.set($,f)}}replaceRelationsSafely(T,S){let $=this.relations.get(T),f=this.isAType?.(T)?T:void 0,M=f===void 0?T:void 0;if($)for(let J of $){f??=J,M??=J;let F=this.relations.get(J);if(F){if(F.size===1)this.relations.delete(J);else F.delete(T);this.contents.delete(this.makeContentKey(f,M))}}this.relations.set(T,new Set(S));for(let J of S){let F=this.relations.get(J);if(F)F.add(T);else F=new Set().add(T),this.relations.set(J,F)}}getContentInternal(T){return this.contents.get(T)}setContent(T,S){this.contents.set(T,S)}deleteContent(T){this.contents.delete(T)}constructor(T,S){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!S?.externalStore)this.relations=new Map(T.relations?.map(([$,f])=>[$,new Set(f)])),this.contents=new Map(T.contents);if(this.isAType=S?.isAType??null,this.isBType=S?.isBType??null,this.isContent=S?.isContent??null,S?.makeContentKey)this.makeContentKey=S.makeContentKey;if(S?.externalStore){let $=S.externalStore;if(this.has=(f,M)=>$.has(f,M),this.addRelation=(f,M)=>{$.addRelation(f,M)},this.deleteRelation=(f,M)=>{$.deleteRelation(f,M)},this.replaceRelationsSafely=(f,M)=>{$.replaceRelationsSafely(f,M)},this.replaceRelationsUnsafely=(f,M)=>{$.replaceRelationsUnsafely(f,M)},this.getRelatedKeys=(f)=>$.getRelatedKeys(f),$.getContent)this.getContentInternal=(f)=>{return $.getContent(f)},this.setContent=(f,M)=>{$.setContent(f,M)},this.deleteContent=(f)=>{$.deleteContent(f)};for(let[f,M]of T.relations??[]){let J=this.isAType?.(f)?f:void 0,F=J===void 0?f:void 0;for(let W of M)J??=W,F??=W,this.addRelation(J,F)}for(let[f,M]of T.contents??[])this.setContent(f,M)}if(S?.warn)this.warn=S.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,S])=>[T,[...S]]),contents:[...this.contents.entries()]}}set(T,...S){let $=typeof S[0]==="string"?S[0]:T[this.b],f=S[1]??typeof S[0]==="string"?void 0:S[0];switch(T=typeof T==="string"?T:T[this.a],this.cardinality){case"1:1":{let M=this.getRelatedKey(T);if(M&&M!==$)this.delete(T,M)}case"1:n":{let M=this.getRelatedKey($);if(M&&M!==T)this.delete(M,$)}}if(f){let M=this.makeContentKey(T,$);this.setContent(M,f)}return this.addRelation(T,$),this}delete(T,S){S=typeof S==="string"?S:T[this.b];let $=typeof T==="string"?T:T[this.a];if($===void 0&&typeof S==="string"){let f=this.getRelatedKeys(S);if(f)for(let M of f)this.delete(M,S)}if(typeof $==="string"&&S===void 0){let f=this.getRelatedKeys($);if(f)for(let M of f)this.delete($,M)}if(typeof $==="string"&&typeof S==="string"){this.deleteRelation($,S);let f=this.makeContentKey($,S);this.deleteContent(f)}return this}getRelatedKey(T){let S=this.getRelatedKeys(T);if(S){if(S.size>1)this.warn?.(`${S.size} related keys were found for key "${T}": (${[...S].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let $;for(let f of S){$=f;break}return $}}replaceRelations(T,S,$){let f=!Array.isArray(S),M=f?Object.keys(S):S;if($?.reckless)this.replaceRelationsUnsafely(T,M);else this.replaceRelationsSafely(T,M);if(f)for(let J of M){let F=this.makeContentKey(T,J),W=S[J];this.setContent(F,W)}return this}getContent(T,S){let $=this.makeContentKey(T,S);return this.getContentInternal($)}getRelationEntries(T){let S=T[this.a],$=T[this.b];if(S!==void 0&&$===void 0){let f=this.getRelatedKeys(S);if(f)return[...f].map((M)=>{return[M,this.getContent(S,M)]})}if(S===void 0&&$!==void 0){let f=this.getRelatedKeys($);if(f)return[...f].map((M)=>{return[M,this.getContent(M,$)]})}return[]}has(T,S){if(S)return this.getRelatedKeys(T)?.has(S)??!1;return this.relations.has(T)}}function cT(T){return"epoch"in T.transactionMeta}function wT(T){return"phase"in T.transactionMeta}var QA=(T)=>{let S=I(T);if(!wT(S)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",S.transactionMeta.update.key,"Aborting transaction"),S.parent.child=null};var B4=(T)=>T[0].toUpperCase()+T.slice(1);function iS(T){return T.type.split("_").map(B4).join(" ")}class HS extends Error{constructor(...T){let S=T[0],$=T.length===2?T[1]:T[2];if(T.length===2)super(`${iS(S)} ${e(S.key)} not found in store "${$.config.name}".`);else{let f=T[1];super(`${iS(S)} "${S.key}" member ${e(f)} not found in store "${$.config.name}".`)}}}function Z$(T,S,$){return(...f)=>{let M=TT(T,$);if(M)return M.run(f,S);throw new HS(T,$)}}var lJ=(T)=>(S)=>T instanceof Function?T(S):T;var m$=(T,S)=>{if(S.valueMap.has(T.key))return S.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),UA(T,S);if(T.type==="selector"||T.type==="readonly_selector")return S.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();let $=T.default instanceof Function?T.default():T.default;return S.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",$),T.default instanceof Function?T.default():T.default};var VA=(T,S)=>{if(T.operation.open){let $=performance.now();return T.logger.info("\u2757",S.type,S.key,`deferring setState at T-${$} until setState for "${T.operation.token.key}" is done`),$}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:S},T.logger.info("\u2B55",S.type,S.key,`operation start in store "${T.config.name}"${!wT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},BA=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},LA=(T,S)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",S,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(S)},bf=(T,S)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",S,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(S)};var NA=(T,S,$)=>{switch(T.type){case"mutable_atom":$.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",S.newValue,") subscribers:",T.subject.subscribers);break;default:$.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",S.oldValue,"->",S.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(S)};var tW=(T,S)=>{let $=I(S),f=$.selectorAtoms.getRelatedKeys(T.key);if($.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if($.operation.open)$.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...$.operation.done].join(", ")} ] already done`);for(let M of f){if(LA($,M))continue;CA(M,$),bf($,M)}}};function L4(T,S){if(jA(S.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var xA=(T,S,$)=>{let{key:f}=T,M=I($);if(!wT(M)||M.transactionMeta.phase!=="building"){$.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!L4(f,S))return;let F={type:"atom_update",key:f,...S};if(T.family)F.family=T.family;M.transactionMeta.update.updates.push(F),$.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")};var IA=(T,S,$)=>{let f=m$(T,$),M=f;if(T.type==="mutable_atom"&&wT($)){let{parent:F}=$;M=qM(T,F,$)}if(M=lJ(S)(M),$.logger.info("\uD83D\uDCDD","atom",T.key,"set to",M),M=ZS(T.key,M,T.subject,$),bA(T.key,$))qA(T.key,$);bf($,T.key),tW(T,$);let J={oldValue:f,newValue:M};if(cT($))NA(T,J,$);else if($.parent){if($.on.transactionApplying.state===null)xA(T,J,$);else if(T.key.startsWith("*")){let F=T.key.slice(1),W=$.atoms.get(F),A=$.valueMap.get(F);if(W.type==="mutable_atom"&&wT($)){let{parent:X}=$;A=qM(W,X,$)}if(A.do(J.newValue)===null)tW(W,$)}}};var uJ=(T,S,$)=>{switch(T.type){case"atom":case"mutable_atom":IA(T,S,$);break;case"selector":T.set(S);break}};function dJ(T,S){if(S.family){let $=T.families.get(S.family.key);if($)return $}}function qT(T,...S){let $,f,M,J;if(S.length===2){if($=S[0],J=S[1],f=dJ(T,$)??null,f)M=$.family?lT($.family.subKey):null,$=OT(T,f,M)}else f=S[0],M=S[1],J=S[2],$=OT(T,f,M);if("counterfeit"in $){let A=T.disposalTraces.buffer.find((k)=>k?.key===$.key);T.logger.error("\u274C",$.type,$.key,`could not be set because it was not found in the store "${T.config.name}".`,A?`This state was previously disposed:\n${A.trace}`:"No previous disposal trace was found.");return}let F=VA(T,$);if(F){let A=T.on.operationClose.subscribe(`waiting to set "${$.key}" at T-${F}`,()=>{A(),T.logger.info("\uD83D\uDFE2",$.type,$.key,`resuming deferred setState from T-${F}`),qT(T,$,J)});return}let W=TT($,T);uJ(W,J,T),BA(T)}function rJ(T,S,$){let{key:f,newValue:M,oldValue:J}=S,F=T==="newValue"?M:J,W={key:f,type:"atom"};if(S.family)Object.assign(W,{family:S.family});qT($,W,F)}function ZA(T,S){let $=new JT,f={type:"molecule_family",key:S.key,dependsOn:S.dependsOn??"all"},M={...f,subject:$,new:S.new};return T.moleculeFamilies.set(S.key,M),f}function lS(T,S,$){let f=O$($,S,T.key);T.tokens.set(f.key,f);let M=wT($)&&$.transactionMeta.phase==="building",J=$.moleculeInProgress===T.key;if(!M&&!J)T.subject.next({type:"state_creation",token:f});return f}function aJ(T){return{store:T}}function KT(T,...S){let $,f,M;if(S.length===1){if($=S[0],$.type!=="molecule"){if(f=dJ(T,$)??null,f)M=$.family?lT($.family.subKey):null,$=OT(T,f,M)}}else{f=S[0],M=S[1];let J;if(f.type==="molecule_family")J=jT(T,f,M)??xf(f,M);else J=OT(T,f,M);$=J}if("counterfeit"in $&&"family"in $){f=$.type==="molecule"?TT($.family,T):T.families.get($.family.key);let J=$.type==="molecule"?$.key:$.family.subKey,F=T.disposalTraces.buffer.find((W)=>W?.key===$.key);switch(T.logger.error("\u274C",$.type,$.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,F?`This state was previously disposed:\n${F.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(f.key))return T.defaults.get($.family.key);let W=TT(f,T).default(J);return T.defaults.set(f.key,W),W}case"molecule_family":throw new HS(f,J,T)}}switch($.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return m$(TT($,T),T);case"molecule":return TT($,T).instance}}class jf{S;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new JT;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(T,S,$){this.key=S;if(this.stringKey=e(S),$)this.family=$,this._dependsOn=$.dependsOn;if(T)for(let f of T)this.above.set(f.stringKey,f)}}function mA(T){return T[0].toUpperCase()+T.slice(1)}function G$(T,S,$,f,...M){let J=_A(T),F=I(T),W=e(f);F.moleculeInProgress=W;let A=Array.isArray(S)?S:[S],k=A.map((E)=>{if(E instanceof jf)return E;let B=e(E.key),L=T.molecules.get(B);if(!L)throw new Error(`Molecule ${B} not found in store "${T.config.name}"`);return L}),X=new jf(k,f,$);F.molecules.set(W,X);for(let E of k)E.below.set(X.stringKey,X);let y={get:(...E)=>KT(I(J),...E),set:(...E)=>{qT(I(J),...E)},seek:(E,B)=>jT(I(J),E,B),json:(E)=>nT(I(J),E),run:(E,B=Cf())=>Z$(E,B,I(T)),make:(E,B,L,...b)=>G$(I(J),E,B,L,...b),dispose:(E)=>{RS(I(J),E)},env:()=>aJ(I(J)),bond:(E,B)=>{if(E.type==="join"){let{as:L}=B,b=ZM(E,J);b.molecules.set(W,X),X.joins.set(E.key,b);let C=K.subject.subscribe(`join:${E.key}-${W}`,(O)=>{if(O.type==="molecule_disposal"){if(e(O.token.key)===W)C(),b.molecules.delete(W)}});if(L===null)return;let D=E.a===L?E.b:E.a,H=hA(E,f),U=H[`${D}KeysOf${mA(L)}`],Z=H[`${D}EntriesOf${mA(L)}`],h={relatedKeys:U};if(Z)h=Object.assign(h,{relatedEntries:Z});return h}return lS(X,TT(E,J),I(J))},claim:(E,B)=>{let{exclusive:L}=B,b=I(T).molecules.get(e(E.key));if(b)if(L){for(let C of b.above.values())C.below.delete(b.stringKey);b.above.clear(),b.above.set(X.stringKey,X),X.below.set(b.stringKey,b)}else b.above.set(X.stringKey,X),X.below.set(b.stringKey,b)},spawn:(E,B,...L)=>G$(I(T),[X],TT(E,T),B,...L)},K=TT($,T),G=K.new;X.instance=new G(y,f,...M);let z={type:"molecule",key:f,family:$},Q={type:"molecule_creation",subType:"classic",token:z,family:$,context:A,params:M};if(cT(F))K.subject.next(Q);else if(wT(F)&&F.on.transactionApplying.state===null)F.transactionMeta.update.updates.push(Q);return F.moleculeInProgress=null,z}function pW(T,S,$){switch(S){case"newValue":{vA(T,$);break}case"oldValue":{RS($,T.token);break}}}function iW(T,S,$){switch(S){case"newValue":{RS($,T.token);break}case"oldValue":{vA(T,$),$.valueMap.set(T.token.key,T.value);break}}}function vA(T,S){let{family:$}=T.token;if($){let f=S.families.get($.key);if(f)OT(S,f,lT($.subKey))}}function lW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":G$($,T.context,T.family,T.token.key,...T.params);break;case"modern":PW($,T.provenance,T.key);break}break;case"oldValue":switch(T.subType){case"classic":RS($,T.token);break;case"modern":IM($,T.key);break}break}}function uW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":RS($,T.token);break;case"modern":IM($,T.key);break}break;case"oldValue":switch(T.subType){case"classic":{let f=G$($,T.context,T.family,T.token.key);for(let[M,J]of T.values){let F=`${M}(${e(f.key)})`,W=TT(f,$),A=W.tokens.has(F),k=$.families.get(M);if(k&&!A)lS(W,k,$);$.valueMap.set(F,J)}}break;case"modern":{PW($,T.provenance,T.key);for(let[f,M]of T.values){let J=$.families.get(f);if(J){OT($,J,T.key);let F=`${f}(${e(T.key)})`;$.valueMap.set(F,M)}}}}break}}function eJ(T,S,$){let f=T==="newValue"?S.updates:[...S.updates].reverse();for(let M of f)switch(M.type){case"atom_update":case"selector_update":rJ(T,M,$);break;case"state_creation":pW(M,T,$);break;case"state_disposal":iW(M,T,$);break;case"molecule_creation":lW(M,T,$);break;case"molecule_disposal":uW(M,T,$);break;case"transaction_update":eJ(T,M,$);break}}function PA(T,S,$){if(cT($)&&T)$.transactionMeta.epoch.set(T,S)}function nA(T,S,$){if(!cT($))return;let M=$.transactionMeta.actionContinuities.getRelatedKey(T);if(M!==void 0)$.transactionMeta.epoch.set(M,S)}var cA=(T,S)=>{let $=I(S),{parent:f}=$;if(f===null||!wT($)||$.transactionMeta?.phase!=="building"){S.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}$.transactionMeta.phase="applying",$.transactionMeta.update.output=T,f.child=null,f.on.transactionApplying.next($.transactionMeta);let{updates:M}=$.transactionMeta.update;if(S.logger.info("\uD83D\uDEC4","transaction",$.transactionMeta.update.key,`Applying transaction with ${M.length} updates:`,M),eJ("newValue",$.transactionMeta.update,f),cT(f))nA($.transactionMeta.update.key,$.transactionMeta.update.epoch,f),TT({key:$.transactionMeta.update.key,type:"transaction"},S)?.subject.next($.transactionMeta.update),S.logger.info("\uD83D\uDEEC","transaction",$.transactionMeta.update.key,"Finished applying transaction.");else if(wT(f))f.transactionMeta.update.updates.push($.transactionMeta.update);f.on.transactionApplying.next(null)};function oA(T,S,$){if(!cT($))return;let{epoch:M,actionContinuities:J}=$.transactionMeta;if(J.set(T,S),!M.has(T))M.set(T,-1)}class mS extends Map{T;deleted=new Set;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,S){return this.deleted.delete(T),super.set(T,S)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var gA=(T,S,$,f)=>{let M=I($),J={parent:M,child:null,on:M.on,loggers:M.loggers,logger:M.logger,config:M.config,atoms:new mS(M.atoms),atomsThatAreDefault:new Set(M.atomsThatAreDefault),families:new mS(M.families),operation:{open:!1},readonlySelectors:new mS(M.readonlySelectors),timelines:new mS(M.timelines),timelineTopics:new BS(M.timelineTopics.toJSON()),trackers:new Map,transactions:new mS(M.transactions),selectorAtoms:new BS(M.selectorAtoms.toJSON()),selectorGraph:new BS(M.selectorGraph.toJSON(),{makeContentKey:(...k)=>k.sort().join(":")}),selectors:new mS(M.selectors),valueMap:new mS(M.valueMap),defaults:M.defaults,disposalTraces:$.disposalTraces.copy(),molecules:new mS(M.molecules),moleculeFamilies:new mS(M.moleculeFamilies),moleculeInProgress:M.moleculeInProgress,miscResources:new mS(M.miscResources)},F=tA(T,$),W={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:F===void 0?Number.NaN:F+1,updates:[],params:S,output:void 0},toolkit:{get:(...k)=>KT(A,...k),set:(...k)=>{qT(A,...k)},run:(k,X=Cf())=>Z$(k,X,A),find:(k,X)=>OT(A,k,X),seek:(k,X)=>jT(A,k,X),json:(k)=>nT(A,k),make:(k,X,y,...K)=>G$(A,k,X,y,...K),dispose:(...k)=>{RS(A,...k)},env:()=>aJ(A)}},A=Object.assign(J,{transactionMeta:W});return M.child=A,$.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",S),A};function gW(T,S){let $={key:T.key,type:"transaction",run:(J,F)=>{let W=gA(T.key,J,S,F);try{let A=I(S),{toolkit:k}=W.transactionMeta,X=T.do(k,...J);return cA(X,A),X}catch(A){throw QA(f),S.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",A),A}},install:(J)=>gW(T,J),subject:new JT},f=I(S);f.transactions.set($.key,$);let M=kS($);return S.on.transactionCreation.next(M),M}function tA(T,S){let $=cT(S),f=$?S.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return $&&f!==void 0?S.transactionMeta.epoch.get(f):void 0}class sJ{_buffer;_index=0;constructor(T){let S;if(typeof T==="number")S=T;else S=T.length;this._buffer=Array.from({length:S})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new sJ([...this._buffer]);return T._index=this._index,T}}class pA{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new BS({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new BS({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new BS({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new BS({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new sJ(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new JT,atomDisposal:new JT,selectorCreation:new JT,selectorDisposal:new JT,timelineCreation:new JT,transactionCreation:new JT,transactionApplying:new vW(null),operationClose:new JT,moleculeCreationStart:new JT,moleculeCreationDone:new JT,moleculeDisposal:new JT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new oW("warn",(T,S,$)=>!$.includes("\uD83D\uDD0D"))];logger={error:(...T)=>{for(let S of this.loggers)S.error(...T)},info:(...T)=>{for(let S of this.loggers)S.info(...T)},warn:(...T)=>{for(let S of this.loggers)S.warn(...T)}};constructor(T,S=null){if(this.config={...S?.config,...T},S!==null){if(this.valueMap=new Map(S?.valueMap),this.operation={...S?.operation},cT(S))this.transactionMeta={epoch:new Map(S?.transactionMeta.epoch),actionContinuities:new BS(S?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of S.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let $=new Set;for(let[,f]of S.atoms){if($.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let M=nT(S,f),J=z$(f);$.add(M.key),$.add(J.key)}}for(let[,f]of S.readonlySelectors)f.install(this);for(let[,f]of S.selectors){if($.has(f.key))continue;f.install(this)}for(let[,f]of S.transactions)f.install(this);for(let[,f]of S.timelines)f.install(this)}}}var XT={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new pA({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function TT(T,S){let $,f=S;while(f!==null){switch(T.type){case"atom":case"mutable_atom":$=f.atoms.get(T.key);break;case"selector":$=f.selectors.get(T.key);break;case"readonly_selector":$=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":$=f.families.get(T.key);break;case"timeline":$=f.timelines.get(T.key);break;case"transaction":$=f.transactions.get(T.key);break;case"molecule":$=f.molecules.get(e(T.key));break;case"molecule_family":$=f.moleculeFamilies.get(T.key);break}if($)return $;f=f.child}throw new HS(T,S)}function TF(T,S){let $;$=TT(T,S);let{family:f}=T;for(let F of $.joins.values())F.relations.delete($.key),F.molecules.delete($.stringKey);let M=[];for(let F of $.above.values())M.push(kS(F));let J=[];for(let F of $.tokens.values()){let W=F.family;J.push([W.key,S.valueMap.get(F.key)])}if(f){let F=TT(f,S),W={type:"molecule_disposal",subType:"classic",token:T,family:f,context:M,values:J};if(T.family)W.family=T.family;for(let k of $.tokens.values())RS(S,k);for(let k of $.below.values())if(k.dependsOn==="all")TF(k,S);else if(k.above.delete($.stringKey),k.above.size===0)TF(k,S);if($.below.clear(),wT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push(W);else F.subject.next(W);S.molecules.delete($.stringKey)}for(let F of $.above.values())F.below.delete($.stringKey)}function O$(T,S,$){let f=T.families.get(S.key);if(f===void 0)throw new HS(S,T);let M=f($),J=I(T);if(M.family&&J.moleculeInProgress===null){if(cT(J))switch(M.type){case"atom":case"mutable_atom":T.on.atomCreation.next(M);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(M);break}else if(wT(J)&&J.on.transactionApplying.state===null)J.transactionMeta.update.updates.push({type:"state_creation",token:M})}return M}function jT(T,S,$){let f=e($),M=`${S.key}(${f})`,J=I(T),F;switch(S.type){case"atom_family":case"mutable_atom_family":F=J.atoms.get(M);break;case"selector_family":F=J.selectors.get(M);break;case"readonly_selector_family":F=J.readonlySelectors.get(M);break;case"molecule_family":F=J.molecules.get(e($))}if(F)return kS(F);return F}function OT(T,S,$){let f=jT(T,S,$);if(f)return f;let M=T.molecules.get(e($));if(M)return lS(M,S,T);if(T.config.lifespan==="immortal"){let J=xf(S,$);return T.logger.error("\u274C",J.type,J.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),J}return f=O$(T,S,$),f}function RS(T,...S){let $,f;if(S.length===1)$=S[0],f=$.key;else{let J=S[0],F=S[1];$=J.type==="molecule_family"?jT(T,J,F)??xf(J,F):OT(T,J,F)}try{TT($,T)}catch(J){let F=T.disposalTraces.buffer.find((W)=>W?.key===$.key);T.logger.error("\u274C",$.type,$.key,`could not be disposed because it was not found in the store "${T.config.name}".`,F?`\n This state was most recently disposed\n${F.trace}`:"No previous disposal trace was found.");return}switch($.type){case"atom":case"mutable_atom":dW($,T);break;case"selector":case"readonly_selector":iA($,T);break;case"molecule":TF($,T);break}let{stack:M}=new Error;if(M){let J=M?.split("\n")?.slice(3)?.join("\n");T.disposalTraces.add({key:$.key,trace:J})}}var SF=(T,S)=>I(S).atoms.has(T),N4=(T,S)=>I(S).selectors.has(T),C4=(T,S)=>I(S).readonlySelectors.has(T),lA=(T,S)=>SF(T,S)||N4(T,S)||C4(T,S);var $F=(T,S)=>{return I(S).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([f,{source:M}])=>M!==T).map(([f,{source:M}])=>M).filter((f)=>lA(f,S))};var rW=(T,S,$)=>{let f=[],M=$F(T,$);while(M.length>0){let J=M.shift();if(S.has(J))continue;if(S.add(J),!SF(J,$))M.push(...$F(J,$));else if(!f.includes(J))f.push(J)}return f},uA=(T,S)=>{let $=T.key,f=$F($,S),M=new Set;return f.flatMap((J)=>SF(J,S)?J:rW(J,M,S))};var dA=(T,S,$,f)=>{let M=I(f);if(S.type==="atom"||S.type==="mutable_atom")M.selectorAtoms.set({selectorKey:T,atomKey:S.key}),f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${S.key}"`);else{let J=rW(S.key,$,f);f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${J.map((F)=>`"${F}"`).join(", ")} ]`);for(let F of J)M.selectorAtoms=M.selectorAtoms.set({selectorKey:T,atomKey:F})}$.add(S.key)};var fF=(T,S,$)=>({get:(...f)=>{let M=I($),J;if(f.length===2){let[A,k]=f;switch(A.type){case"molecule_family":return KT($,A,k);default:if($.config.lifespan==="ephemeral")J=OT($,A,k);else{let X=jT($,A,k);if(X)J=X;else throw new HS(A,k,$)}}}else[J]=f;if(J.type==="molecule")return KT($,J);let F=TT(J,$),W=m$(F,$);return $.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${J.key}" =`,W,")"),M.selectorGraph.set({upstreamSelectorKey:J.key,downstreamSelectorKey:T},{source:J.key}),dA(T,J,S,$),W},set:(...f)=>{let M,J;if(f.length===2)M=f[0],J=f[1];else{let A=f[0],k=f[1];J=f[2];let X=$.config.lifespan==="ephemeral"?OT($,A,k):jT($,A,k);if(!X)throw new HS(A,k,$);M=X}let F=I($),W=TT(M,F);uJ(W,J,F)},find:(f,M)=>OT($,f,M),seek:(f,M)=>jT($,f,M),json:(f)=>nT($,f)});var CM=(T,S,$)=>{let f=I(T),M=new JT,J=new Set,{get:F,find:W,seek:A,json:k}=fF(S.key,J,f),X=()=>{let z=S.get({get:F,find:W,seek:A,json:k});return ZS(S.key,z,M,I(T)),J.clear(),z},y={...S,subject:M,install:(z)=>CM(z,S,$),get:X,type:"readonly_selector",...$&&{family:$}};f.readonlySelectors.set(S.key,y);let K=X();T.logger.info("\u2728",y.type,y.key,"=",K);let G={key:S.key,type:"readonly_selector"};if($)G.family=$;return G};var mM=(T,S,$)=>{let f=I(T),M=new JT,J=new Set,F=fF(S.key,J,f),{find:W,get:A,seek:k,json:X}=F,y={find:W,get:A,seek:k,json:X},K=(B=S.get,L=I(T))=>{let b=B(y);return ZS(S.key,b,M,L),J.clear(),b},z={...S,subject:M,install:(B)=>mM(B,S,$),get:K,set:(B)=>{let L=I(T),b=K(S.get,L),C=lJ(B)(b);if(T.logger.info("\uD83D\uDCDD","selector",S.key,"set (",b,"->",C,")"),ZS(S.key,C,M,L),bf(L,S.key),cT(L))M.next({newValue:C,oldValue:b});S.set(F,C)},type:"selector",...$&&{family:$}};f.selectors.set(S.key,z);let Q=K();T.logger.info("\u2728",z.type,z.key,"=",Q);let E={key:S.key,type:"selector"};if($)E.family=$;return E};function pS(T,S){if("set"in S){let M=mM(T,S,void 0);return T.on.selectorCreation.next(M),M}let f=CM(T,S,void 0);return T.on.selectorCreation.next(f),f}function iA(T,S){let $=I(S),{key:f}=T,M=TT(T,$);if(!M.family)S.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{let J=$.molecules.get(M.family.subKey);if(J)J.tokens.delete(f);switch(T.type){case"selector":$.selectors.delete(f),TT({key:M.family.key,type:"selector_family"},S).subject.next({type:"state_disposal",token:T});break;case"readonly_selector":$.readonlySelectors.delete(f),TT({key:M.family.key,type:"readonly_selector_family"},S).subject.next({type:"state_disposal",token:T});break}if($.valueMap.delete(f),$.selectorAtoms.delete(f),$.selectorGraph.delete(f),S.logger.info("\uD83D\uDD25",T.type,f,"deleted"),wT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.selectorDisposal.next(T)}}function jM(T,S,$){let f={key:S.key,type:"selector_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","selector_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new JT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},y=`${S.key}(${k})`,K=I(T),G=mM(K,{key:y,get:S.get(A),set:S.set(A)},X);return J.next({type:"state_creation",token:G}),G},f,{internalRoles:$,subject:J,install:(A)=>jM(A,S),default:(A)=>{return S.get(A)({get:(...X)=>KT(T,...X),find:(X,y)=>OT(T,X,y),seek:(X,y)=>jT(T,X,y),json:(X)=>nT(T,X)})}});return T.families.set(S.key,W),f}function rA(T,S,$=XT.STORE){let f=jM($,{key:`${T.key}:JSON`,get:(J)=>({seek:F,get:W})=>{let A=F(T,J);if(A)return S.toJson(W(A));let k=e(J),X=$.molecules.get(k);if(X){let K=lS(X,T,$);return S.toJson(W(K))}if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${k}"`);let y=O$($,T,J);return S.toJson(W(y))},set:(J)=>({seek:F,set:W},A)=>{let k=F(T,J);if(k)W(k,S.fromJson(A));else{let X=e(J),y=$.molecules.get(X);if(y){let K=lS(y,T,$);W(K,S.fromJson(A))}else{if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${X}"`);W(O$($,T,J),S.fromJson(A))}}}},["mutable","json"]);return TT(T,$).subject.subscribe(`store=${$.config.name}::json-selector-family`,(J)=>{if(J.token.family)jT($,f,lT(J.token.family.subKey))}),f}var lT=(T)=>JSON.parse(T),e=(T)=>JSON.stringify(T),uG=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var aA=(T,S)=>{let $=I(S);if($.operation.open)return $.operation.prev.get(T.key);return $.valueMap.get(T.key)};var sW=(T,S)=>{let $=I(S);return uA(T,S).map((M)=>{let J=$.atoms.get(M);if(J===void 0)throw new Error(`Atom "${M}", a dependency of selector "${T.key}", not found in store "${S.config.name}".`);return J.subject.subscribe(`${T.type}:${T.key}`,(F)=>{S.logger.info("\uD83D\uDCE2",T.type,T.key,"root",M,"went",F.oldValue,"->",F.newValue);let W=aA(T,$),A=m$(T,$);S.logger.info("\u2728",T.type,T.key,"went",W,"->",A),T.subject.next({newValue:A,oldValue:W})})})};function XS(T,S,$,f){function M(y){if(f.operation.open){let K=f.on.operationClose.subscribe(`state subscription ${$}`,()=>{K(),S(y)})}else S(y)}let J=TT(T,f);f.logger.info("\uD83D\uDC40",J.type,J.key,`Adding subscription "${$}"`);let F=J.type==="selector"||J.type==="readonly_selector",W=null,A=M;if(F)W=sW(J,f),A=(y)=>{if(W)W.length=0,W.push(...sW(J,f));M(y)};let k=J.subject.subscribe($,A);return()=>{if(f.logger.info("\uD83D\uDE48",J.type,J.key,`Removing subscription "${$}"`),k(),W)for(let y of W)y()}}var aW=(T,S,$,f)=>{let M=TT(T,f);f.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${$}"`);let J=M.subject.subscribe($,S);return()=>{f.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${$}" from timeline`),J()}};var eW=(T,S,$,f)=>{let M=TT(T,f);f.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${$}"`);let J=M.subject.subscribe($,S);return()=>{f.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${$}"`),J()}};class h${Update;initializeState(T,S){let $=`*${T.key}`;S.atoms.delete($),S.valueMap.delete($);let f=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,M=_S(S,{key:$,default:null},f);if(S.parent?.valueMap.has($)){let J=S.parent.valueMap.get($);S.valueMap.set($,J)}return M}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,S,$){let f=`tracker:${$.config.name}:${wT($)?$.transactionMeta.update.key:"main"}:${T.key}`,M=KT($,T);this.unsubscribeFromInnerValue=M.subscribe(f,(J)=>{qT($,S,J)}),this.unsubscribeFromState=XS(T,(J)=>{if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(f,(F)=>{qT($,S,F)})},f,$)}updateCore(T,S,$){let f=`tracker:${$.config.name}:${wT($)?$.transactionMeta.update.key:"main"}:${T.key}`;XS(S,({newValue:M,oldValue:J})=>{let F=$.timelineTopics.getRelatedKey(S.key);if(F){if($.timelines.get(F)?.timeTraveling){let k=aW({key:F,type:"timeline"},(X)=>{k(),qT($,T,(y)=>{if(X==="redo"&&M)y.do(M);else if(X==="undo"&&J)y.undo(J);return y})},f,$);return}}let W=$.on.operationClose.subscribe(f,()=>{W();let A=KT($,T),k=M===null?-1:A.getUpdateNumber(M),X=k-A.cacheUpdateNumber;if(M&&X===1)qT($,T,(y)=>(y.do(M),y));else $.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${A.cacheUpdateNumber+1}, but got ${k}`)})},f,$)}mutableState;latestUpdateState;dispose;constructor(T,S){this.mutableState=T;let $=I(S);this.latestUpdateState=this.initializeState(T,$),this.observeCore(T,this.latestUpdateState,$),this.updateCore(T,this.latestUpdateState,$),$.trackers.set(T.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),$.trackers.delete(T.key)}}}function hM(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let f=I(T),M=f.atoms.get(S.key);if(M&&M.type==="mutable_atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),kS(M);let J=new JT,F={...S,type:"mutable_atom",install:(k)=>{return k.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${k.config.name}"`),hM(k,S,$)},subject:J};if($)F.family=$;let W=S.default();f.atoms.set(F.key,F),MF(S.key,T),ZS(S.key,W,J,f);let A=kS(F);if(S.effects){let k=0,X=[];for(let y of S.effects){let K=y({setSelf:(G)=>{qT(T,A,G)},onSet:(G)=>XS(A,G,`effect[${k}]`,T)});if(K)X.push(K);++k}F.cleanup=()=>{for(let y of X)y()}}if(new h$(A,T),!$)zA(A,S,T);return A}class T0{Update;latestUpdateAtoms;mutableAtoms;constructor(T,S){let $=W$(S,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=TT($,S),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let M=lT(f.token.family.subKey);jT(S,this.latestUpdateAtoms,M),new h$(f.token,S)}}),this.latestUpdateAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let M=lT(f.token.family.subKey),J=jT(S,this.mutableAtoms,M);if(J)new h$(J,S)}})}}function NM(T,S,$){let f={key:S.key,type:"mutable_atom_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","mutable_atom_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new JT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},y=`${S.key}(${k})`,K=I(T),G={key:y,default:()=>S.default(A),toJson:S.toJson,fromJson:S.fromJson,mutable:!0};if(S.effects)G.effects=S.effects(A);let z=hM(K,G,X);return J.next({type:"state_creation",token:z}),z},f,{subject:J,install:(A)=>NM(A,S),toJson:S.toJson,fromJson:S.fromJson,internalRoles:$});return T.families.set(S.key,W),rA(W,S,T),new T0(W,T),f}var S0=(T,S)=>{let $=I(S),f=`${T.key}:JSON`;return $.families.get(f)};var nT=(T,S)=>{if(S.family){let f=I(T),J={key:`${S.family.key}:JSON`,type:"selector_family"},F=TT(J,f),W=JSON.parse(S.family.subKey);return OT(T,F,W)}return{type:"selector",key:`${S.key}:JSON`}};var z$=(T)=>{let $={type:"atom",key:`*${T.key}`};if(T.family)$.family={key:`*${T.family.key}`,subKey:T.family.subKey};return $};function jA(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function qM(T,S,$){let f=S.valueMap.get(T.key),M=$.valueMap.get(T.key);if(f===M){if(f===void 0)return typeof T.default==="function"?T.default():T.default;S.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let J=T.toJson(f),F=T.fromJson(J);return $.valueMap.set(T.key,F),new h$(T,S),F}return M}function ZS(T,S,$,f){let M=f.valueMap.get(T);if(M instanceof LM)M.use(S);if(S instanceof Promise){let J=new LM(S);return f.valueMap.set(T,J),J.then((F)=>{ZS(T,F,$,f),$.next({newValue:F,oldValue:J})}).catch((F)=>{f.logger.error("\uD83D\uDCA5","state",T,"rejected:",F)}),J}return f.valueMap.set(T,S),S}var UA=(T,S)=>{let $=S.valueMap.get(T.key);if(T.type==="mutable_atom"&&wT(S)){let{parent:f}=S;$=qM(T,f,S)}return $},CA=(T,S)=>{let $=S.valueMap.get(T);if($ instanceof LM){let f=$,M=S.selectors.get(T)??S.readonlySelectors.get(T);if(M)f.use(M.get());return}if(S.operation.open)S.operation.prev.set(T,$);S.valueMap.delete(T),S.logger.info("\uD83D\uDDD1","state",T,"evicted")};var bA=(T,S)=>{return I(S).atomsThatAreDefault.has(T)},MF=(T,S)=>{let $=I(S);$.atomsThatAreDefault=new Set($.atomsThatAreDefault).add(T)},qA=(T,S)=>{let $=I(S);$.atomsThatAreDefault=new Set(I(S).atomsThatAreDefault),$.atomsThatAreDefault.delete(T)};function _S(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let f=I(T),M=f.atoms.get(S.key);if(M&&M.type==="atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),kS(M);let J=new JT,F={...S,type:"atom",install:(k)=>{return k.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${k.config.name}"`),_S(k,S,$)},subject:J};if($)F.family=$;let W=S.default;if(S.default instanceof Function)W=S.default();f.atoms.set(F.key,F),MF(S.key,T),ZS(S.key,W,J,f);let A=kS(F);if(S.effects){let k=0,X=[];for(let y of S.effects){let K=y({setSelf:(G)=>{qT(T,A,G)},onSet:(G)=>XS(A,G,`effect[${k}]`,T)});if(K)X.push(K);++k}F.cleanup=()=>{for(let y of X)y()}}return A}function DA(T,S){if("mutable"in S){let M=hM(T,S,void 0);return T.on.atomCreation.next(M),M}let f=_S(T,S,void 0);return T.on.atomCreation.next(f),f}function dW(T,S){let $=I(S),{key:f}=T,M=TT(T,$);if(!M.family)S.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{M.cleanup?.();let J=S.valueMap.get(M.key);TT({key:M.family.key,type:"atom_family"},S).subject.next({type:"state_disposal",token:T,value:J});let W=$.molecules.get(M.family.subKey);if(W)W.tokens.delete(f);if($.atoms.delete(f),$.valueMap.delete(f),$.selectorAtoms.delete(f),$.atomsThatAreDefault.delete(f),S.timelineTopics.delete(f),T.type==="mutable_atom"){let A=z$(T);dW(A,S),S.trackers.delete(f)}if(S.logger.info("\uD83D\uDD25","atom",f,"deleted"),wT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.atomDisposal.next(T)}}class uT extends Set{mode="record";subject=new JT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,S=0){super(T);if(T instanceof uT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(S)this.cacheLimit=S,this.cache=new Array(S),this.subscribe("auto cache",($)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=$})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let S=new uT(T.members,T.cacheLimit);return S.cache=T.cache,S.cacheIdx=T.cacheIdx,S.cacheUpdateNumber=T.cacheUpdateNumber,S}add(T){let S=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${e(T)}`);return S}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let S=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${e(T)}`);return S}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new uT(this);let S=this.child._subscribe("transaction",($)=>{this.transactionUpdates?.push($)});try{if(T(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch($){throw console.error("Failed to apply transaction to SetRTX:",$),$}finally{S(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,S){return this.subject.subscribe(T,S)}subscribe(T,S){return this.subject.subscribe(T,($)=>{S(`${this.cacheUpdateNumber}=${$}`)})}emit(T){this.subject.next(T)}doStep(T){let S=T.indexOf(":"),$=T.substring(0,S),f=T.substring(S+1);switch($){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let M of f.split(";"))this.doStep(M)}}getUpdateNumber(T){let S=T.indexOf("=");return Number(T.substring(0,S))}do(T){let S=T.indexOf("="),$=Number(T.substring(0,S)),f=$-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let J=T.substring(S+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=$,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let J=this.cacheIdx+f;if(this.cache[J]===T)return null;this.mode="playback";let W=!1;while(!W){this.cacheIdx%=this.cacheLimit;let k=this.cache[this.cacheIdx];if(this.cacheIdx--,!k)return"OUT_OF_RANGE";this.undo(k),W=this.cacheIdx===J-1}let A=T.substring(S+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=$,null}return"OUT_OF_RANGE"}undoStep(T){let S=T.indexOf(":"),$=T.substring(0,S),f=T.substring(S+1);switch($){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let M=JSON.parse(f);for(let J of M)this.add(J);break}case"tx":{let M=f.split(";");for(let J=M.length-1;J>=0;J--)this.undoStep(M[J])}}}undo(T){let S=T.indexOf("=");if(Number(T.substring(0,S))===this.cacheUpdateNumber){this.mode="playback";let f=T.substring(S+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function IT(T){return T[0].toUpperCase()+T.slice(1)}class f0{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(T,S){let $=this.toolkit;this.toolkit=T,S(this),this.toolkit=$}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(T){let S=T.config.name,$=this.alternates.get(S);if($)return $;let f=new f0(this.options,this.defaultContent,T);return this.alternates.set(S,f),f.alternates=this.alternates,f}constructor(T,S,$=XT.STORE){this.store=$,this.options=T,this.defaultContent=S,this.alternates=new Map,this.alternates.set($.config.name,this),this.store.miscResources.set(`join:${T.key}`,this),this.retrieve=(D,H)=>{let U=this.toolkit.seek(D,H);if(U)return U;let Z=this.store.molecules.get(e(H));if(Z){let h=TT(D,$);return lS(Z,h,$)}if($.config.lifespan==="immortal")throw new HS(D,H,$);return O$($,D,H)},this.toolkit={get:(...D)=>KT($,...D),set:(...D)=>{qT($,...D)},find:this.retrieve,seek:(...D)=>jT($,...D),json:(D)=>nT($,D),dispose:(...D)=>{RS($,...D)}};let f=T.between[0],M=T.between[1],J=NM($,{key:`${T.key}/relatedKeys`,default:()=>new uT,mutable:!0,fromJson:(D)=>uT.fromJSON(D),toJson:(D)=>D.toJSON()},["join","relations"]);this.core={findRelatedKeysState:J};let F=({get:D},H)=>D(this.retrieve(J,H)),W=(D,H,U)=>{let{set:Z}=D,h=this.retrieve(J,H),O=this.retrieve(J,U);Z(h,(o)=>o.add(U)),Z(O,(o)=>o.add(H))},A=(D,H,U)=>{let{set:Z}=D,h=this.retrieve(J,H),O=this.retrieve(J,U),o,P;Z(h,(a)=>{if(a.delete(U),a.size===0)o=`"${H}"`;return a}),Z(O,(a)=>{if(a.delete(H),a.size===0)P=`"${U}"`;return a})},k=(D,H,U)=>{let{get:Z,set:h}=D,O=this.retrieve(J,H),o=Z(O);for(let P of o){if(U.includes(P))continue;let MT=this.retrieve(J,P);h(MT,(fT)=>{return fT.delete(H),fT})}h(O,(P)=>{return P.transaction((a)=>{a.clear();for(let MT of U){let fT=F(D,MT),UT=fT.has(H);if(this.relations.cardinality==="1:n"){let VS=[];for(let N of fT){if(N===H)continue;let p=F(D,N);if(p.delete(MT),p.size===0)VS.push(N)}if(!UT&&fT.size>0)fT.clear();for(let N of VS){let p=[MT,N].sort(),kT=`"${p[0]}:${p[1]}"`;this.molecules.delete(kT)}}if(!UT)fT.add(H);a.add(MT)}return!0}),P})},X=(D,H,U)=>{let{set:Z}=D,h=this.retrieve(J,H);Z(h,(O)=>{return O.transaction((o)=>{for(let P of U)o.add(P);return!0}),O});for(let O of U){let o=this.retrieve(J,O);Z(o,(P)=>{return P.add(H),P})}return!0},y=(D,H,U)=>{let Z=F(D,H);return U?Z.has(U):Z.size>0},K={getRelatedKeys:(D)=>F(this.toolkit,D),addRelation:(D,H)=>{W(this.toolkit,D,H)},deleteRelation:(D,H)=>{A(this.toolkit,D,H)},replaceRelationsSafely:(D,H)=>{k(this.toolkit,D,H)},replaceRelationsUnsafely:(D,H)=>{X(this.toolkit,D,H)},has:(D,H)=>y(this.toolkit,D,H)},G,z,Q;if(S){z=W$($,{key:`${T.key}/content`,default:S},["join","content"]),Q=ZA($,{key:`${T.key}/content-molecules`,new:class h{o;constructor(O,o){this.key=o}}});let D=({get:h},O)=>h(this.retrieve(z,O)),H=({set:h},O,o)=>{h(this.retrieve(z,O),o)},U=(h,O)=>{let o=$.molecules.get(`"${O}"`);if(o)this.toolkit.dispose(o),this.molecules.delete(`"${O}"`)};G=Object.assign(K,{getContent:(h)=>{return D(this.toolkit,h)},setContent:(h,O)=>{H(this.toolkit,h,O)},deleteContent:(h)=>{U(this.toolkit,h)}})}else G=K;let E=new BS(T,{externalStore:G,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...D)=>{let H=D.sort(),U=`${H[0]}:${H[1]}`,[Z,h]=H.map((O)=>this.molecules.get(e(O)));if($.config.lifespan==="immortal"&&Z&&h){let O=I($),o=G$(O,[Z,h],Q,U);this.molecules.set(`"${U}"`,TT(o,O))}return U}}),B=()=>R$($,{key:`${T.key}/singleRelatedKey`,get:(D)=>({get:H})=>{let U=this.retrieve(J,D),Z=H(U);for(let h of Z)return h;return null}},["join","keys"]),L=()=>{return R$($,{key:`${T.key}/multipleRelatedKeys`,get:(D)=>({get:H})=>{let U=S0(J,$),Z=this.retrieve(U,D);return H(Z).members}},["join","keys"])},b=()=>R$($,{key:`${T.key}/singleRelatedEntry`,get:(D)=>({get:H})=>{let U=this.retrieve(J,D),Z=H(U);for(let h of Z){let O=E.isAType?.(D)?D:void 0,o=O===void 0?D:void 0;O??=h,o??=h;let P=E.makeContentKey(O,o),a=this.retrieve(z,P),MT=H(a);return[h,MT]}return null}},["join","entries"]),C=()=>R$($,{key:`${T.key}/multipleRelatedEntries`,get:(D)=>({get:H})=>{let U=S0(J,$),Z=this.retrieve(U,D);return H(Z).members.map((O)=>{let o=E.isAType?.(D)?D:void 0,P=o===void 0?D:void 0;o??=O,P??=O;let a=E.makeContentKey(o,P),MT=this.retrieve(z,a),fT=H(MT);return[O,fT]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let D=B(),H=`${f}KeyOf${IT(M)}`,U=`${M}KeyOf${IT(f)}`,Z={[H]:D,[U]:D},h;if(S){let O=b(),o=`${f}EntryOf${IT(M)}`,P=`${M}EntryOf${IT(f)}`,a={[o]:O,[P]:O};h=Object.assign(Z,a)}else h=Z;this.relations=E,this.states=h;break}case"1:n":{let D=B(),H=L(),U=`${f}KeyOf${IT(M)}`,Z=`${M}KeysOf${IT(f)}`,h={[U]:D,[Z]:H},O;if(S){let o=b(),P=C(),a=`${f}EntryOf${IT(M)}`,MT=`${M}EntriesOf${IT(f)}`,fT={[a]:o,[MT]:P};O=Object.assign(h,fT)}else O=h;this.relations=E,this.states=O;break}default:{let D=L(),H=`${f}KeysOf${IT(M)}`,U=`${M}KeysOf${IT(f)}`,Z={[H]:D,[U]:D},h;if(S){let O=C(),o=`${f}EntriesOf${IT(M)}`,P=`${M}EntriesOf${IT(f)}`,a={[o]:O,[P]:O};h=Object.assign(Z,a)}else h=Z;this.relations=E,this.states=h}}}}function JF(T,S,$=XT.STORE){return $0($).set(T.key,new f0(T,S,$)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function $0(T){if("joins"in T&&T.joins instanceof Map)return T.joins;let S=new Map;return T.joins=S,S}function ZM(T,S){let $=$0(S),f=$.get(T.key);if(f===void 0){if(f=$0(XT.STORE).get(T.key)?.in(S),f===void 0)throw new Error(`Join "${T.key}" not found in store "${S.config.name}"`);$.set(T.key,f)}return f}function FF(T,S,$){let f=ZM(T,$),M;switch(T.cardinality){case"1:1":{let J=`${T.a}KeyOf${IT(T.b)}`,F=`${T.b}KeyOf${IT(T.a)}`;M={get[J](){let A=f.states[J];return f.retrieve(A,S)},get[F](){let A=f.states[F];return f.retrieve(A,S)}};let W=`${T.a}EntryOf${IT(T.b)}`;if(W in f.states){let A=`${T.b}EntryOf${IT(T.a)}`;Object.assign(M,{get[W](){let k=f.states[W];return f.retrieve(k,S)},get[A](){let k=f.states[A];return f.retrieve(k,S)}})}break}case"1:n":{let J=`${T.a}KeyOf${IT(T.b)}`,F=`${T.b}KeysOf${IT(T.a)}`;M={get[J](){let A=f.states[J];return f.retrieve(A,S)},get[F](){let A=f.states[F];return f.retrieve(A,S)}};let W=`${T.a}EntryOf${IT(T.b)}`;if(W in f.states){let A=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(M,{get[W](){let k=f.states[W];return f.retrieve(k,S)},get[A](){let k=f.states[A];return f.retrieve(k,S)}})}break}case"n:n":{let J=`${T.a}KeysOf${IT(T.b)}`,F=`${T.b}KeysOf${IT(T.a)}`;M={get[J](){let A=f.states[J];return f.retrieve(A,S)},get[F](){let A=f.states[F];return f.retrieve(A,S)}};let W=`${T.a}EntriesOf${IT(T.b)}`;if(W in f.states){let A=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(M,{get[W](){let k=f.states[W];return f.retrieve(k,S)},get[A](){let k=f.states[A];return f.retrieve(k,S)}})}}}return M}function hA(T,S){return FF(T,S,XT.STORE)}function WF(T,S,$){let f=ZM(T,$),M=I($);if(wT(M)){let{toolkit:J}=M.transactionMeta;f.transact(J,({relations:F})=>{S(F)})}else S(f.relations)}function x4(T,S){return ZM(T,S).core.findRelatedKeysState}function eA(T){return x4(T,XT.STORE)}class sA extends Map{set(T,S){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:S}),this;return super.set(T,S)}clear(){throw new Error("Cannot clear an InvariantMap")}}class AF{T;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new sA;static create(T,S){let $=new AF(T),{type:f,globals:M,actions:J,perspectives:F}=S($),W={type:f,key:T,globals:M,actions:J,perspectives:F};return AF.existing.set(T,W),W}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":{let[$,f]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:$,viewAtoms:f})}break}return this}}function p_(T){let{key:S,config:$}=T,f=AF.create(S,$),{actions:M}=f;for(let J of M)oA(S,J.key,XT.STORE);return PA(S,-1,XT.STORE),f}var r_=If({key:"usersInRoomIndex",mutable:!0,default:()=>new uT,toJson:(T)=>T.toJSON(),fromJson:(T)=>uT.fromJSON(T)}),M0=If({key:"roomIndex",default:()=>new uT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>uT.fromJSON(T)}),j4={enteredAtEpoch:0},vM=JF({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},j4),a_=iJ({key:"usersInMyRoomView",get:(T)=>({find:S})=>{let $=eA(vM);return[S($,T)]}});import{spawn as I4}from"child_process";class qf{T;listeners;globalListeners;handleEvent(T,...S){for(let f of this.globalListeners)f(T,...S);let $=this.listeners.get(T);if($)for(let f of $)f(...S)}id="no_id_retrieved";constructor(T){this.emit=T;this.listeners=new Map,this.globalListeners=new Set}on(T,S){let $=this.listeners.get(T);if($)$.add(S);else this.listeners.set(T,new Set([S]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,S){let $=this.listeners.get(T);if($)if(S)$.delete(S);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class J0 extends qf{T;S;$;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(T){if(Array.isArray(T)){let[S,...$]=T;switch(S){case"i":this.logger.info(this.id,this.key,...$);break;case"w":this.logger.warn(this.id,this.key,...$);break;case"e":this.logger.error(this.id,this.key,...$);break}}}constructor(T,S,$=console){super((f,...M)=>{let J=JSON.stringify([f,...M])+"\x03",F=(W)=>{if(W.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",F)};return this.process.stdin.once("error",F),this.process.stdin.write(J),this});this.process=T;this.key=S;this.logger=$;if(this.process=T,this.process.stdout.on("data",(f)=>{let M=f.toString();if(M==="\u2728")return;this.unprocessedEvents.push(...M.split("\x03"));let J=this.unprocessedEvents.shift();this.incompleteData+=J??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let F=lT(this.incompleteData);this.handleEvent(...F);while(this.unprocessedEvents.length>0){let W=this.unprocessedEvents.shift();if(W){if(this.unprocessedEvents.length===0)this.incompleteData=W;F=lT(W),this.handleEvent(...F)}}this.incompleteData=""}catch(F){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(F)}}),this.process.stderr.on("data",(f)=>{let M=f.toString();this.unprocessedLogs.push(...M.split("\x03"));let J=this.unprocessedLogs.shift();this.incompleteLog+=J??"";try{let F=lT(this.incompleteLog);this.handleLog(F);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)F=lT(this.incompleteLog),this.handleLog(F)}catch(F){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(F),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class Tk extends qf{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...S)=>{return this.out.next(S),this});this.id=T,this.in=new JT,this.out=new JT,this.in.subscribe("socket",(S)=>{this.handleEvent(...S)})}dispose(){for(let T of this.disposalFunctions)T()}}class F0 extends qf{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(e(T.map((S)=>S instanceof uT?`{ ${S.toJSON().members.join(" | ")} }`:S))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...S)=>{let $=JSON.stringify([T,...S]);return this.process.stdout.write($+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let S=T.toString();this.unprocessedEvents.push(...S.split("\x03"));let $=this.unprocessedEvents.shift();this.incompleteData+=$??"";try{let f=lT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let M=this.unprocessedEvents.shift();if(M){if(this.unprocessedEvents.length===0)this.incompleteData=M;let J=lT(M);this.handleEvent(...J)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let S=new Tk(`user:${T}`);this.relays.set(T,S),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let $ of this.relayServices){let f=$(S);if(f)S.disposalFunctions.push(f)}this.on(`user:${T}`,(...$)=>{S.in.next($)}),S.out.subscribe("socket",($)=>{this.emit(...$)})}),this.on("user-leaves",(T)=>{let S=this.relays.get(T);if(this.off(`relay:${T}`),S)S.dispose(),this.relays.delete(T)}),process.stdout.write("\u2728")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var W0=e$({key:"roomArguments",default:["echo",["Hello World!"]]}),Sk=iJ({key:"room",get:(T)=>async({get:S,find:$})=>{let f=$(W0,T),M=S(f),[J,F]=M,W=await new Promise((A)=>{let k=I4(J,F,{env:process.env}),X=(y)=>{if(y.toString()==="\u2728")k.stdout.off("data",X),A(k)};k.stdout.on("data",X)});return new J0(W,T)}});var VH=bM({key:"createRoom",do:({get:T,set:S,find:$},f,M,J)=>{let F=J?[M,J]:[M],W=$(W0,f);S(W,F),S(M0,(X)=>X.add(f));let A=$(Sk,f);return T(A)}}),BH=bM({key:"joinRoom",do:(T,S,$,f)=>{let M={enteredAtEpoch:f};return WF(vM,(J)=>{J.set({room:S,user:$},M)},T.env().store),M}}),LH=bM({key:"leaveRoom",do:(T,S,$)=>{WF(vM,(f)=>{f.delete({room:S,user:$})},T.env().store)}}),NH=bM({key:"destroyRoom",do:(T,S)=>{WF(vM,($)=>{$.delete({room:S})},T.env().store),T.set(M0,($)=>($.delete(S),$))}});function A0(T,S){return S.map(($)=>{switch($.type){case"transaction_update":{let f=A0(T,$.updates);return{...$,updates:f}}default:return $}}).filter(($)=>{switch($.type){case"atom_update":case"selector_update":return T.includes($.key);case"state_creation":return T.includes($.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var jH=e$({key:"redactor",default:{occlude:(T)=>T}}),Zf=e$({key:"unacknowledgedUpdates",default:()=>[]});var $k=e$({key:"sockets",default:null}),mH=If({key:"socketsIndex",mutable:!0,default:()=>new uT,toJson:(T)=>T.toJSON(),fromJson:(T)=>uT.fromJSON(T)}),hH=If({key:"usersIndex",mutable:!0,default:()=>new uT,toJson:(T)=>T.toJSON(),fromJson:(T)=>uT.fromJSON(T)}),k0=JF({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function fk(T,S,$,f){let M=S.key;return function J(){let F=[];for(let A of S.globals){let k=A.type==="mutable_atom"?nT(T,A):A,X=KT(T,k);F.push(k,X)}for(let A of S.perspectives){let{viewAtoms:k,resourceAtoms:X}=A,y=OT(T,k,$),K=KT(T,y);T.logger.info("\uD83D\uDC41","atom",X.key,`${$} can see`,{viewAtoms:k,resourceAtoms:X,userView:K});for(let G of K){let z=G.type==="mutable_atom"?nT(T,G):G,Q=KT(T,z);F.push(z,Q)}}let W=cT(T)?T.transactionMeta.epoch.get(M)??null:null;f?.emit(`continuity-init:${M}`,W,F)}}function Mk(T,S,$){let f=S.key;return function M(J){T.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",J);let{key:F,id:W}=J,A=`tx-run:${F}:${W}`,k=`${A}:start`,X=`${A}:end`;performance.mark(k);try{Z$({type:"transaction",key:F},W,T)(...J.params)}catch(K){if(K instanceof Error)T.logger.error("\u274C","continuity",f,`failed to run transaction ${F} from ${$} with update ${W}`,K.message)}performance.mark(X);let y=performance.measure(A,k,X);T?.logger.info("\uD83D\uDE80","transaction",F,W,$,y.duration)}}function Jk(T,S,$,f){let M=S.key;return function J(F){if(T.logger.info("\uD83D\uDC4D","continuity",M,`${$} acknowledged epoch ${F}`),f[0]?.epoch===F)qT(T,Zf,$,(A)=>{return A.shift(),T.logger.info("\uD83D\uDC4D","continuity",M,`${$} unacknowledged update queue now has`,A.length,"items"),A})}}function Fk(T,S,$,f){let M=S.key,J=[];for(let F of S.actions){let W=eW(F,(A)=>{try{let k=S.globals.map((K)=>{if(K.type==="atom")return K.key;return z$(K).key}).concat(S.perspectives.flatMap((K)=>{let{viewAtoms:G}=K,z=OT(T,G,$);return KT(T,z).map((E)=>{return E.type==="mutable_atom"?"*"+E.key:E.key})})),X=A0(k,A.updates),y={...A,updates:X};qT(T,Zf,$,(K)=>{if(y)K.push(y),K.sort((G,z)=>G.epoch-z.epoch),T.logger.info("\uD83D\uDC4D","continuity",M,`${$} unacknowledged update queue now has`,K.length,"items");return K}),f?.emit(`tx-new:${M}`,y)}catch(k){if(k instanceof Error)T.logger.error("\u274C","continuity",M,`${$} failed to send update from transaction ${F.key} to ${$}`,k.message)}},`sync-continuity:${M}:${$}`,T);J.push(W)}return J}function Wk(T,S,$,f){let M=S.key,J=[];for(let F of S.perspectives){let{viewAtoms:W}=F,A=OT(T,W,$),k=XS(A,({oldValue:X,newValue:y})=>{let K=X.map((E)=>E.key),G=y.map((E)=>E.key),z=X.filter((E)=>!G.includes(E.key)),Q=y.filter((E)=>!K.includes(E.key)).flatMap((E)=>{let B=E.type==="mutable_atom"?nT(T,E):E,L=KT(T,B);return[B,L]});if(T.logger.info("\uD83D\uDC41","atom",F.resourceAtoms.key,`${$} has a new perspective`,{oldKeys:K,newKeys:G,revealed:Q,concealed:z}),Q.length>0)f?.emit(`reveal:${M}`,Q);if(z.length>0)f?.emit(`conceal:${M}`,z)},`sync-continuity:${M}:${$}:perspective:${F.resourceAtoms.key}`,T);J.push(k)}return J}function wD({socket:T,store:S=XT.STORE}){return function $(f){let M=T,J=f.key,F=FF(k0,`socket::${M.id}`,S).userKeyOfSocket,W=KT(S,F);if(!W)return S.logger.error("\u274C","continuity",J,`Tried to create a synchronizer for a socket (${M.id}) that is not connected to a user.`),()=>{};let A=FF(k0,W,S).socketKeyOfUser,k=XS(A,({newValue:B})=>{if(S.logger.info("\uD83D\uDC4B","continuity",J,`seeing ${W} on new socket ${B}`),B===null){S.logger.warn("\u274C","continuity",J,`User (${W}) is not connected to a socket, waiting for them to reappear.`);return}let L=OT(S,$k,B);M=KT(S,L);for(let C of X)M?.emit(`tx-new:${J}`,C)},`sync-continuity:${J}:${W}`,S),X=KT(S,Zf,W),y=[],K=Wk(S,f,W,M),G=Fk(S,f,W,M);y.push(...K,...G);let z=fk(S,f,W,T);M.off(`get:${J}`,z),M.on(`get:${J}`,z);let Q=Mk(S,f,W);M.off(`tx-run:${J}`,Q),M.on(`tx-run:${J}`,Q);let E=Jk(S,f,W,X);return M?.on(`ack:${J}`,E),()=>{for(let B of y)B();M?.off(`ack:${J}`,E),M?.off(`get:${J}`,z),M?.off(`tx-run:${J}`,Q)}}}var kk=Symbol("Let zodToJsonSchema decide on which parser to use"),Ak={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Xk=(T)=>typeof T==="string"?{...Ak,name:T}:{...Ak,...T};var yk=(T)=>{let S=Xk(T),$=S.name!==void 0?[...S.basePath,S.definitionPath,S.name]:S.basePath;return{...S,currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(S.definitions).map(([f,M])=>[M._def,{def:M._def,path:[...S.basePath,S.definitionPath,f],jsonSchema:void 0}]))}};function X0(T,S,$,f){if(!f?.errorMessages)return;if($)T.errorMessage={...T.errorMessage,[S]:$}}function YT(T,S,$,f,M){T[S]=$,X0(T,S,f,M)}var GT;(function(T){T.assertEqual=(M)=>M;function S(M){}T.assertIs=S;function $(M){throw new Error}T.assertNever=$,T.arrayToEnum=(M)=>{let J={};for(let F of M)J[F]=F;return J},T.getValidEnumValues=(M)=>{let J=T.objectKeys(M).filter((W)=>typeof M[M[W]]!=="number"),F={};for(let W of J)F[W]=M[W];return T.objectValues(F)},T.objectValues=(M)=>{return T.objectKeys(M).map(function(J){return M[J]})},T.objectKeys=typeof Object.keys==="function"?(M)=>Object.keys(M):(M)=>{let J=[];for(let F in M)if(Object.prototype.hasOwnProperty.call(M,F))J.push(F);return J},T.find=(M,J)=>{for(let F of M)if(J(F))return F;return},T.isInteger=typeof Number.isInteger==="function"?(M)=>Number.isInteger(M):(M)=>typeof M==="number"&&isFinite(M)&&Math.floor(M)===M;function f(M,J=" | "){return M.map((F)=>typeof F==="string"?`'${F}'`:F).join(J)}T.joinValues=f,T.jsonStringifyReplacer=(M,J)=>{if(typeof J==="bigint")return J.toString();return J}})(GT||(GT={}));var K0;(function(T){T.mergeShapes=(S,$)=>{return{...S,...$}}})(K0||(K0={}));var n=GT.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),v$=(T)=>{switch(typeof T){case"undefined":return n.undefined;case"string":return n.string;case"number":return isNaN(T)?n.nan:n.number;case"boolean":return n.boolean;case"function":return n.function;case"bigint":return n.bigint;case"symbol":return n.symbol;case"object":if(Array.isArray(T))return n.array;if(T===null)return n.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return n.promise;if(typeof Map!=="undefined"&&T instanceof Map)return n.map;if(typeof Set!=="undefined"&&T instanceof Set)return n.set;if(typeof Date!=="undefined"&&T instanceof Date)return n.date;return n.object;default:return n.unknown}},j=GT.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"]),b4=(T)=>{return JSON.stringify(T,null,2).replace(/"([^"]+)":/g,"$1:")};class LS extends Error{constructor(T){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let S=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,S);else this.__proto__=S;this.name="ZodError",this.issues=T}get errors(){return this.issues}format(T){let S=T||function(M){return M.message},$={_errors:[]},f=(M)=>{for(let J of M.issues)if(J.code==="invalid_union")J.unionErrors.map(f);else if(J.code==="invalid_return_type")f(J.returnTypeError);else if(J.code==="invalid_arguments")f(J.argumentsError);else if(J.path.length===0)$._errors.push(S(J));else{let F=$,W=0;while(W<J.path.length){let A=J.path[W];if(W!==J.path.length-1)F[A]=F[A]||{_errors:[]};else F[A]=F[A]||{_errors:[]},F[A]._errors.push(S(J));F=F[A],W++}}};return f(this),$}static assert(T){if(!(T instanceof LS))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,GT.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=(S)=>S.message){let S={},$=[];for(let f of this.issues)if(f.path.length>0)S[f.path[0]]=S[f.path[0]]||[],S[f.path[0]].push(T(f));else $.push(T(f));return{formErrors:$,fieldErrors:S}}get formErrors(){return this.flatten()}}LS.create=(T)=>{return new LS(T)};var Pf=(T,S)=>{let $;switch(T.code){case j.invalid_type:if(T.received===n.undefined)$="Required";else $=`Expected ${T.expected}, received ${T.received}`;break;case j.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(T.expected,GT.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:$=`Unrecognized key(s) in object: ${GT.joinValues(T.keys,", ")}`;break;case j.invalid_union:$="Invalid input";break;case j.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${GT.joinValues(T.options)}`;break;case j.invalid_enum_value:$=`Invalid enum value. Expected ${GT.joinValues(T.options)}, received '${T.received}'`;break;case j.invalid_arguments:$="Invalid function arguments";break;case j.invalid_return_type:$="Invalid function return type";break;case j.invalid_date:$="Invalid date";break;case j.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if($=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)$=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)$=`Invalid input: must end with "${T.validation.endsWith}"`;else GT.assertNever(T.validation);else if(T.validation!=="regex")$=`Invalid ${T.validation}`;else $="Invalid";break;case j.too_small:if(T.type==="array")$=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")$=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")$=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")$=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else $="Invalid input";break;case j.too_big:if(T.type==="array")$=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")$=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")$=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")$=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")$=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else $="Invalid input";break;case j.custom:$="Invalid input";break;case j.invalid_intersection_types:$="Intersection results could not be merged";break;case j.not_multiple_of:$=`Number must be a multiple of ${T.multipleOf}`;break;case j.not_finite:$="Number must be finite";break;default:$=S.defaultError,GT.assertNever(T)}return{message:$}},Yk=Pf;function q4(T){Yk=T}function kF(){return Yk}var XF=(T)=>{let{data:S,path:$,errorMaps:f,issueData:M}=T,J=[...$,...M.path||[]],F={...M,path:J};if(M.message!==void 0)return{...M,path:J,message:M.message};let W="",A=f.filter((k)=>!!k).slice().reverse();for(let k of A)W=k(F,{data:S,defaultError:W}).message;return{...M,path:J,message:W}},Z4=[];function v(T,S){let $=kF(),f=XF({issueData:S,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$,$===Pf?void 0:Pf].filter((M)=>!!M)});T.common.issues.push(f)}class yS{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,S){let $=[];for(let f of S){if(f.status==="aborted")return ST;if(f.status==="dirty")T.dirty();$.push(f.value)}return{status:T.value,value:$}}static async mergeObjectAsync(T,S){let $=[];for(let f of S){let M=await f.key,J=await f.value;$.push({key:M,value:J})}return yS.mergeObjectSync(T,$)}static mergeObjectSync(T,S){let $={};for(let f of S){let{key:M,value:J}=f;if(M.status==="aborted")return ST;if(J.status==="aborted")return ST;if(M.status==="dirty")T.dirty();if(J.status==="dirty")T.dirty();if(M.value!=="__proto__"&&(typeof J.value!=="undefined"||f.alwaysSet))$[M.value]=J.value}return{status:T.value,value:$}}}var ST=Object.freeze({status:"aborted"}),hf=(T)=>({status:"dirty",value:T}),OS=(T)=>({status:"valid",value:T}),w0=(T)=>T.status==="aborted",Y0=(T)=>T.status==="dirty",cM=(T)=>T.status==="valid",oM=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function yF(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)}function Rk(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$}var l;(function(T){T.errToObj=(S)=>typeof S==="string"?{message:S}:S||{},T.toString=(S)=>typeof S==="string"?S:S===null||S===void 0?void 0:S.message})(l||(l={}));var PM,nM;class aS{constructor(T,S,$,f){this._cachedPath=[],this.parent=T,this.data=S,this._path=$,this._key=f}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Kk=(T,S)=>{if(cM(S))return{success:!0,data:S.value};else{if(!T.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new LS(T.common.issues);return this._error=$,this._error}}}};function FT(T){if(!T)return{};let{errorMap:S,invalid_type_error:$,required_error:f,description:M}=T;if(S&&($||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(S)return{errorMap:S,description:M};return{errorMap:(F,W)=>{var A,k;let{message:X}=T;if(F.code==="invalid_enum_value")return{message:X!==null&&X!==void 0?X:W.defaultError};if(typeof W.data==="undefined")return{message:(A=X!==null&&X!==void 0?X:f)!==null&&A!==void 0?A:W.defaultError};if(F.code!=="invalid_type")return{message:W.defaultError};return{message:(k=X!==null&&X!==void 0?X:$)!==null&&k!==void 0?k:W.defaultError}},description:M}}class WT{constructor(T){this.spa=this.safeParseAsync,this._def=T,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)}get description(){return this._def.description}_getType(T){return v$(T.data)}_getOrReturnCtx(T,S){return S||{common:T.parent.common,data:T.data,parsedType:v$(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new yS,ctx:{common:T.parent.common,data:T.data,parsedType:v$(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){let S=this._parse(T);if(oM(S))throw new Error("Synchronous parse encountered promise.");return S}_parseAsync(T){let S=this._parse(T);return Promise.resolve(S)}parse(T,S){let $=this.safeParse(T,S);if($.success)return $.data;throw $.error}safeParse(T,S){var $;let f={common:{issues:[],async:($=S===null||S===void 0?void 0:S.async)!==null&&$!==void 0?$:!1,contextualErrorMap:S===null||S===void 0?void 0:S.errorMap},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:v$(T)},M=this._parseSync({data:T,path:f.path,parent:f});return Kk(f,M)}async parseAsync(T,S){let $=await this.safeParseAsync(T,S);if($.success)return $.data;throw $.error}async safeParseAsync(T,S){let $={common:{issues:[],contextualErrorMap:S===null||S===void 0?void 0:S.errorMap,async:!0},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:v$(T)},f=this._parse({data:T,path:$.path,parent:$}),M=await(oM(f)?f:Promise.resolve(f));return Kk($,M)}refine(T,S){let $=(f)=>{if(typeof S==="string"||typeof S==="undefined")return{message:S};else if(typeof S==="function")return S(f);else return S};return this._refinement((f,M)=>{let J=T(f),F=()=>M.addIssue({code:j.custom,...$(f)});if(typeof Promise!=="undefined"&&J instanceof Promise)return J.then((W)=>{if(!W)return F(),!1;else return!0});if(!J)return F(),!1;else return!0})}refinement(T,S){return this._refinement(($,f)=>{if(!T($))return f.addIssue(typeof S==="function"?S($,f):S),!1;else return!0})}_refinement(T){return new hS({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}optional(){return rS.create(this,this._def)}nullable(){return H$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dS.create(this,this._def)}promise(){return $f.create(this,this._def)}or(T){return gf.create([this,T],this._def)}and(T){return tf.create(this,T,this._def)}transform(T){return new hS({...FT(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:T}})}default(T){let S=typeof T==="function"?T:()=>T;return new df({...FT(this._def),innerType:this,defaultValue:S,typeName:x.ZodDefault})}brand(){return new wF({typeName:x.ZodBranded,type:this,...FT(this._def)})}catch(T){let S=typeof T==="function"?T:()=>T;return new rf({...FT(this._def),innerType:this,catchValue:S,typeName:x.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return uM.create(this,T)}readonly(){return af.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var m4=/^c[^\s-]{8,}$/i,h4=/^[0-9a-z]+$/,v4=/^[0-9A-HJKMNP-TV-Z]{26}$/,P4=/^[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,n4=/^[a-z0-9_-]{21}$/i,c4=/^[-+]?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)?)??$/,o4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,g4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y0,t4=/^(?:(?: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])$/,p4=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,i4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ok="((\\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])))",l4=new RegExp(`^${Ok}\$`);function Gk(T){let S="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)S=`${S}\\.\\d{${T.precision}}`;else if(T.precision==null)S=`${S}(\\.\\d+)?`;return S}function u4(T){return new RegExp(`^${Gk(T)}\$`)}function zk(T){let S=`${Ok}T${Gk(T)}`,$=[];if($.push(T.local?"Z?":"Z"),T.offset)$.push("([+-]\\d{2}:?\\d{2})");return S=`${S}(${$.join("|")})`,new RegExp(`^${S}\$`)}function d4(T,S){if((S==="v4"||!S)&&t4.test(T))return!0;if((S==="v6"||!S)&&p4.test(T))return!0;return!1}class uS extends WT{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==n.string){let M=this._getOrReturnCtx(T);return v(M,{code:j.invalid_type,expected:n.string,received:M.parsedType}),ST}let $=new yS,f=void 0;for(let M of this._def.checks)if(M.kind==="min"){if(T.data.length<M.value)f=this._getOrReturnCtx(T,f),v(f,{code:j.too_small,minimum:M.value,type:"string",inclusive:!0,exact:!1,message:M.message}),$.dirty()}else if(M.kind==="max"){if(T.data.length>M.value)f=this._getOrReturnCtx(T,f),v(f,{code:j.too_big,maximum:M.value,type:"string",inclusive:!0,exact:!1,message:M.message}),$.dirty()}else if(M.kind==="length"){let J=T.data.length>M.value,F=T.data.length<M.value;if(J||F){if(f=this._getOrReturnCtx(T,f),J)v(f,{code:j.too_big,maximum:M.value,type:"string",inclusive:!0,exact:!0,message:M.message});else if(F)v(f,{code:j.too_small,minimum:M.value,type:"string",inclusive:!0,exact:!0,message:M.message});$.dirty()}}else if(M.kind==="email"){if(!o4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"email",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="emoji"){if(!y0)y0=new RegExp(g4,"u");if(!y0.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"emoji",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="uuid"){if(!P4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"uuid",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="nanoid"){if(!n4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"nanoid",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="cuid"){if(!m4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"cuid",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="cuid2"){if(!h4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"cuid2",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="ulid"){if(!v4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"ulid",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="url")try{new URL(T.data)}catch(J){f=this._getOrReturnCtx(T,f),v(f,{validation:"url",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="regex"){if(M.regex.lastIndex=0,!M.regex.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"regex",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="trim")T.data=T.data.trim();else if(M.kind==="includes"){if(!T.data.includes(M.value,M.position))f=this._getOrReturnCtx(T,f),v(f,{code:j.invalid_string,validation:{includes:M.value,position:M.position},message:M.message}),$.dirty()}else if(M.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(M.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(M.kind==="startsWith"){if(!T.data.startsWith(M.value))f=this._getOrReturnCtx(T,f),v(f,{code:j.invalid_string,validation:{startsWith:M.value},message:M.message}),$.dirty()}else if(M.kind==="endsWith"){if(!T.data.endsWith(M.value))f=this._getOrReturnCtx(T,f),v(f,{code:j.invalid_string,validation:{endsWith:M.value},message:M.message}),$.dirty()}else if(M.kind==="datetime"){if(!zk(M).test(T.data))f=this._getOrReturnCtx(T,f),v(f,{code:j.invalid_string,validation:"datetime",message:M.message}),$.dirty()}else if(M.kind==="date"){if(!l4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{code:j.invalid_string,validation:"date",message:M.message}),$.dirty()}else if(M.kind==="time"){if(!u4(M).test(T.data))f=this._getOrReturnCtx(T,f),v(f,{code:j.invalid_string,validation:"time",message:M.message}),$.dirty()}else if(M.kind==="duration"){if(!c4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"duration",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="ip"){if(!d4(T.data,M.version))f=this._getOrReturnCtx(T,f),v(f,{validation:"ip",code:j.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="base64"){if(!i4.test(T.data))f=this._getOrReturnCtx(T,f),v(f,{validation:"base64",code:j.invalid_string,message:M.message}),$.dirty()}else GT.assertNever(M);return{status:$.value,value:T.data}}_regex(T,S,$){return this.refinement((f)=>T.test(f),{validation:S,code:j.invalid_string,...l.errToObj($)})}_addCheck(T){return new uS({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...l.errToObj(T)})}url(T){return this._addCheck({kind:"url",...l.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...l.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...l.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...l.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...l.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...l.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...l.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...l.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...l.errToObj(T)})}datetime(T){var S,$;if(typeof T==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:T});return this._addCheck({kind:"datetime",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,offset:(S=T===null||T===void 0?void 0:T.offset)!==null&&S!==void 0?S:!1,local:($=T===null||T===void 0?void 0:T.local)!==null&&$!==void 0?$:!1,...l.errToObj(T===null||T===void 0?void 0:T.message)})}date(T){return this._addCheck({kind:"date",message:T})}time(T){if(typeof T==="string")return this._addCheck({kind:"time",precision:null,message:T});return this._addCheck({kind:"time",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,...l.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...l.errToObj(T)})}regex(T,S){return this._addCheck({kind:"regex",regex:T,...l.errToObj(S)})}includes(T,S){return this._addCheck({kind:"includes",value:T,position:S===null||S===void 0?void 0:S.position,...l.errToObj(S===null||S===void 0?void 0:S.message)})}startsWith(T,S){return this._addCheck({kind:"startsWith",value:T,...l.errToObj(S)})}endsWith(T,S){return this._addCheck({kind:"endsWith",value:T,...l.errToObj(S)})}min(T,S){return this._addCheck({kind:"min",value:T,...l.errToObj(S)})}max(T,S){return this._addCheck({kind:"max",value:T,...l.errToObj(S)})}length(T,S){return this._addCheck({kind:"length",value:T,...l.errToObj(S)})}nonempty(T){return this.min(1,l.errToObj(T))}trim(){return new uS({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new uS({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new uS({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((T)=>T.kind==="datetime")}get isDate(){return!!this._def.checks.find((T)=>T.kind==="date")}get isTime(){return!!this._def.checks.find((T)=>T.kind==="time")}get isDuration(){return!!this._def.checks.find((T)=>T.kind==="duration")}get isEmail(){return!!this._def.checks.find((T)=>T.kind==="email")}get isURL(){return!!this._def.checks.find((T)=>T.kind==="url")}get isEmoji(){return!!this._def.checks.find((T)=>T.kind==="emoji")}get isUUID(){return!!this._def.checks.find((T)=>T.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((T)=>T.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((T)=>T.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((T)=>T.kind==="cuid2")}get isULID(){return!!this._def.checks.find((T)=>T.kind==="ulid")}get isIP(){return!!this._def.checks.find((T)=>T.kind==="ip")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get minLength(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxLength(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}uS.create=(T)=>{var S;return new uS({checks:[],typeName:x.ZodString,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...FT(T)})};function r4(T,S){let $=(T.toString().split(".")[1]||"").length,f=(S.toString().split(".")[1]||"").length,M=$>f?$:f,J=parseInt(T.toFixed(M).replace(".","")),F=parseInt(S.toFixed(M).replace(".",""));return J%F/Math.pow(10,M)}class n$ extends WT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(T){if(this._def.coerce)T.data=Number(T.data);if(this._getType(T)!==n.number){let M=this._getOrReturnCtx(T);return v(M,{code:j.invalid_type,expected:n.number,received:M.parsedType}),ST}let $=void 0,f=new yS;for(let M of this._def.checks)if(M.kind==="int"){if(!GT.isInteger(T.data))$=this._getOrReturnCtx(T,$),v($,{code:j.invalid_type,expected:"integer",received:"float",message:M.message}),f.dirty()}else if(M.kind==="min"){if(M.inclusive?T.data<M.value:T.data<=M.value)$=this._getOrReturnCtx(T,$),v($,{code:j.too_small,minimum:M.value,type:"number",inclusive:M.inclusive,exact:!1,message:M.message}),f.dirty()}else if(M.kind==="max"){if(M.inclusive?T.data>M.value:T.data>=M.value)$=this._getOrReturnCtx(T,$),v($,{code:j.too_big,maximum:M.value,type:"number",inclusive:M.inclusive,exact:!1,message:M.message}),f.dirty()}else if(M.kind==="multipleOf"){if(r4(T.data,M.value)!==0)$=this._getOrReturnCtx(T,$),v($,{code:j.not_multiple_of,multipleOf:M.value,message:M.message}),f.dirty()}else if(M.kind==="finite"){if(!Number.isFinite(T.data))$=this._getOrReturnCtx(T,$),v($,{code:j.not_finite,message:M.message}),f.dirty()}else GT.assertNever(M);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,l.toString(S))}gt(T,S){return this.setLimit("min",T,!1,l.toString(S))}lte(T,S){return this.setLimit("max",T,!0,l.toString(S))}lt(T,S){return this.setLimit("max",T,!1,l.toString(S))}setLimit(T,S,$,f){return new n$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:l.toString(f)}]})}_addCheck(T){return new n$({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:l.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:l.toString(S)})}finite(T){return this._addCheck({kind:"finite",message:l.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(T)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&GT.isInteger(T.value))}get isFinite(){let T=null,S=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(S===null||$.value>S)S=$.value}else if($.kind==="max"){if(T===null||$.value<T)T=$.value}return Number.isFinite(S)&&Number.isFinite(T)}}n$.create=(T)=>{return new n$({checks:[],typeName:x.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...FT(T)})};class c$ extends WT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)T.data=BigInt(T.data);if(this._getType(T)!==n.bigint){let M=this._getOrReturnCtx(T);return v(M,{code:j.invalid_type,expected:n.bigint,received:M.parsedType}),ST}let $=void 0,f=new yS;for(let M of this._def.checks)if(M.kind==="min"){if(M.inclusive?T.data<M.value:T.data<=M.value)$=this._getOrReturnCtx(T,$),v($,{code:j.too_small,type:"bigint",minimum:M.value,inclusive:M.inclusive,message:M.message}),f.dirty()}else if(M.kind==="max"){if(M.inclusive?T.data>M.value:T.data>=M.value)$=this._getOrReturnCtx(T,$),v($,{code:j.too_big,type:"bigint",maximum:M.value,inclusive:M.inclusive,message:M.message}),f.dirty()}else if(M.kind==="multipleOf"){if(T.data%M.value!==BigInt(0))$=this._getOrReturnCtx(T,$),v($,{code:j.not_multiple_of,multipleOf:M.value,message:M.message}),f.dirty()}else GT.assertNever(M);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,l.toString(S))}gt(T,S){return this.setLimit("min",T,!1,l.toString(S))}lte(T,S){return this.setLimit("max",T,!0,l.toString(S))}lt(T,S){return this.setLimit("max",T,!1,l.toString(S))}setLimit(T,S,$,f){return new c$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:l.toString(f)}]})}_addCheck(T){return new c$({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:l.toString(S)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}c$.create=(T)=>{var S;return new c$({checks:[],typeName:x.ZodBigInt,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...FT(T)})};class nf extends WT{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==n.boolean){let $=this._getOrReturnCtx(T);return v($,{code:j.invalid_type,expected:n.boolean,received:$.parsedType}),ST}return OS(T.data)}}nf.create=(T)=>{return new nf({typeName:x.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...FT(T)})};class s$ extends WT{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==n.date){let M=this._getOrReturnCtx(T);return v(M,{code:j.invalid_type,expected:n.date,received:M.parsedType}),ST}if(isNaN(T.data.getTime())){let M=this._getOrReturnCtx(T);return v(M,{code:j.invalid_date}),ST}let $=new yS,f=void 0;for(let M of this._def.checks)if(M.kind==="min"){if(T.data.getTime()<M.value)f=this._getOrReturnCtx(T,f),v(f,{code:j.too_small,message:M.message,inclusive:!0,exact:!1,minimum:M.value,type:"date"}),$.dirty()}else if(M.kind==="max"){if(T.data.getTime()>M.value)f=this._getOrReturnCtx(T,f),v(f,{code:j.too_big,message:M.message,inclusive:!0,exact:!1,maximum:M.value,type:"date"}),$.dirty()}else GT.assertNever(M);return{status:$.value,value:new Date(T.data.getTime())}}_addCheck(T){return new s$({...this._def,checks:[...this._def.checks,T]})}min(T,S){return this._addCheck({kind:"min",value:T.getTime(),message:l.toString(S)})}max(T,S){return this._addCheck({kind:"max",value:T.getTime(),message:l.toString(S)})}get minDate(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T!=null?new Date(T):null}}s$.create=(T)=>{return new s$({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:x.ZodDate,...FT(T)})};class gM extends WT{_parse(T){if(this._getType(T)!==n.symbol){let $=this._getOrReturnCtx(T);return v($,{code:j.invalid_type,expected:n.symbol,received:$.parsedType}),ST}return OS(T.data)}}gM.create=(T)=>{return new gM({typeName:x.ZodSymbol,...FT(T)})};class cf extends WT{_parse(T){if(this._getType(T)!==n.undefined){let $=this._getOrReturnCtx(T);return v($,{code:j.invalid_type,expected:n.undefined,received:$.parsedType}),ST}return OS(T.data)}}cf.create=(T)=>{return new cf({typeName:x.ZodUndefined,...FT(T)})};class of extends WT{_parse(T){if(this._getType(T)!==n.null){let $=this._getOrReturnCtx(T);return v($,{code:j.invalid_type,expected:n.null,received:$.parsedType}),ST}return OS(T.data)}}of.create=(T)=>{return new of({typeName:x.ZodNull,...FT(T)})};class Tf extends WT{constructor(){super(...arguments);this._any=!0}_parse(T){return OS(T.data)}}Tf.create=(T)=>{return new Tf({typeName:x.ZodAny,...FT(T)})};class P$ extends WT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return OS(T.data)}}P$.create=(T)=>{return new P$({typeName:x.ZodUnknown,...FT(T)})};class A$ extends WT{_parse(T){let S=this._getOrReturnCtx(T);return v(S,{code:j.invalid_type,expected:n.never,received:S.parsedType}),ST}}A$.create=(T)=>{return new A$({typeName:x.ZodNever,...FT(T)})};class tM extends WT{_parse(T){if(this._getType(T)!==n.undefined){let $=this._getOrReturnCtx(T);return v($,{code:j.invalid_type,expected:n.void,received:$.parsedType}),ST}return OS(T.data)}}tM.create=(T)=>{return new tM({typeName:x.ZodVoid,...FT(T)})};class dS extends WT{_parse(T){let{ctx:S,status:$}=this._processInputParams(T),f=this._def;if(S.parsedType!==n.array)return v(S,{code:j.invalid_type,expected:n.array,received:S.parsedType}),ST;if(f.exactLength!==null){let J=S.data.length>f.exactLength.value,F=S.data.length<f.exactLength.value;if(J||F)v(S,{code:J?j.too_big:j.too_small,minimum:F?f.exactLength.value:void 0,maximum:J?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),$.dirty()}if(f.minLength!==null){if(S.data.length<f.minLength.value)v(S,{code:j.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),$.dirty()}if(f.maxLength!==null){if(S.data.length>f.maxLength.value)v(S,{code:j.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),$.dirty()}if(S.common.async)return Promise.all([...S.data].map((J,F)=>{return f.type._parseAsync(new aS(S,J,S.path,F))})).then((J)=>{return yS.mergeArray($,J)});let M=[...S.data].map((J,F)=>{return f.type._parseSync(new aS(S,J,S.path,F))});return yS.mergeArray($,M)}get element(){return this._def.type}min(T,S){return new dS({...this._def,minLength:{value:T,message:l.toString(S)}})}max(T,S){return new dS({...this._def,maxLength:{value:T,message:l.toString(S)}})}length(T,S){return new dS({...this._def,exactLength:{value:T,message:l.toString(S)}})}nonempty(T){return this.min(1,T)}}dS.create=(T,S)=>{return new dS({type:T,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...FT(S)})};function mf(T){if(T instanceof ZT){let S={};for(let $ in T.shape){let f=T.shape[$];S[$]=rS.create(mf(f))}return new ZT({...T._def,shape:()=>S})}else if(T instanceof dS)return new dS({...T._def,type:mf(T.element)});else if(T instanceof rS)return rS.create(mf(T.unwrap()));else if(T instanceof H$)return H$.create(mf(T.unwrap()));else if(T instanceof k$)return k$.create(T.items.map((S)=>mf(S)));else return T}class ZT extends WT{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let T=this._def.shape(),S=GT.objectKeys(T);return this._cached={shape:T,keys:S}}_parse(T){if(this._getType(T)!==n.object){let A=this._getOrReturnCtx(T);return v(A,{code:j.invalid_type,expected:n.object,received:A.parsedType}),ST}let{status:$,ctx:f}=this._processInputParams(T),{shape:M,keys:J}=this._getCached(),F=[];if(!(this._def.catchall instanceof A$&&this._def.unknownKeys==="strip")){for(let A in f.data)if(!J.includes(A))F.push(A)}let W=[];for(let A of J){let k=M[A],X=f.data[A];W.push({key:{status:"valid",value:A},value:k._parse(new aS(f,X,f.path,A)),alwaysSet:A in f.data})}if(this._def.catchall instanceof A$){let A=this._def.unknownKeys;if(A==="passthrough")for(let k of F)W.push({key:{status:"valid",value:k},value:{status:"valid",value:f.data[k]}});else if(A==="strict"){if(F.length>0)v(f,{code:j.unrecognized_keys,keys:F}),$.dirty()}else if(A==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let A=this._def.catchall;for(let k of F){let X=f.data[k];W.push({key:{status:"valid",value:k},value:A._parse(new aS(f,X,f.path,k)),alwaysSet:k in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let A=[];for(let k of W){let X=await k.key,y=await k.value;A.push({key:X,value:y,alwaysSet:k.alwaysSet})}return A}).then((A)=>{return yS.mergeObjectSync($,A)});else return yS.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(T){return l.errToObj,new ZT({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:(S,$)=>{var f,M,J,F;let W=(J=(M=(f=this._def).errorMap)===null||M===void 0?void 0:M.call(f,S,$).message)!==null&&J!==void 0?J:$.defaultError;if(S.code==="unrecognized_keys")return{message:(F=l.errToObj(T).message)!==null&&F!==void 0?F:W};return{message:W}}}:{}})}strip(){return new ZT({...this._def,unknownKeys:"strip"})}passthrough(){return new ZT({...this._def,unknownKeys:"passthrough"})}extend(T){return new ZT({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new ZT({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:x.ZodObject})}setKey(T,S){return this.augment({[T]:S})}catchall(T){return new ZT({...this._def,catchall:T})}pick(T){let S={};return GT.objectKeys(T).forEach(($)=>{if(T[$]&&this.shape[$])S[$]=this.shape[$]}),new ZT({...this._def,shape:()=>S})}omit(T){let S={};return GT.objectKeys(this.shape).forEach(($)=>{if(!T[$])S[$]=this.shape[$]}),new ZT({...this._def,shape:()=>S})}deepPartial(){return mf(this)}partial(T){let S={};return GT.objectKeys(this.shape).forEach(($)=>{let f=this.shape[$];if(T&&!T[$])S[$]=f;else S[$]=f.optional()}),new ZT({...this._def,shape:()=>S})}required(T){let S={};return GT.objectKeys(this.shape).forEach(($)=>{if(T&&!T[$])S[$]=this.shape[$];else{let M=this.shape[$];while(M instanceof rS)M=M._def.innerType;S[$]=M}}),new ZT({...this._def,shape:()=>S})}keyof(){return _k(GT.objectKeys(this.shape))}}ZT.create=(T,S)=>{return new ZT({shape:()=>T,unknownKeys:"strip",catchall:A$.create(),typeName:x.ZodObject,...FT(S)})};ZT.strictCreate=(T,S)=>{return new ZT({shape:()=>T,unknownKeys:"strict",catchall:A$.create(),typeName:x.ZodObject,...FT(S)})};ZT.lazycreate=(T,S)=>{return new ZT({shape:T,unknownKeys:"strip",catchall:A$.create(),typeName:x.ZodObject,...FT(S)})};class gf extends WT{_parse(T){let{ctx:S}=this._processInputParams(T),$=this._def.options;function f(M){for(let F of M)if(F.result.status==="valid")return F.result;for(let F of M)if(F.result.status==="dirty")return S.common.issues.push(...F.ctx.common.issues),F.result;let J=M.map((F)=>new LS(F.ctx.common.issues));return v(S,{code:j.invalid_union,unionErrors:J}),ST}if(S.common.async)return Promise.all($.map(async(M)=>{let J={...S,common:{...S.common,issues:[]},parent:null};return{result:await M._parseAsync({data:S.data,path:S.path,parent:J}),ctx:J}})).then(f);else{let M=void 0,J=[];for(let W of $){let A={...S,common:{...S.common,issues:[]},parent:null},k=W._parseSync({data:S.data,path:S.path,parent:A});if(k.status==="valid")return k;else if(k.status==="dirty"&&!M)M={result:k,ctx:A};if(A.common.issues.length)J.push(A.common.issues)}if(M)return S.common.issues.push(...M.ctx.common.issues),M.result;let F=J.map((W)=>new LS(W));return v(S,{code:j.invalid_union,unionErrors:F}),ST}}get options(){return this._def.options}}gf.create=(T,S)=>{return new gf({options:T,typeName:x.ZodUnion,...FT(S)})};var _$=(T)=>{if(T instanceof pf)return _$(T.schema);else if(T instanceof hS)return _$(T.innerType());else if(T instanceof lf)return[T.value];else if(T instanceof o$)return T.options;else if(T instanceof uf)return GT.objectValues(T.enum);else if(T instanceof df)return _$(T._def.innerType);else if(T instanceof cf)return[void 0];else if(T instanceof of)return[null];else if(T instanceof rS)return[void 0,..._$(T.unwrap())];else if(T instanceof H$)return[null,..._$(T.unwrap())];else if(T instanceof wF)return _$(T.unwrap());else if(T instanceof af)return _$(T.unwrap());else if(T instanceof rf)return _$(T._def.innerType);else return[]};class KF extends WT{_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==n.object)return v(S,{code:j.invalid_type,expected:n.object,received:S.parsedType}),ST;let $=this.discriminator,f=S.data[$],M=this.optionsMap.get(f);if(!M)return v(S,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),ST;if(S.common.async)return M._parseAsync({data:S.data,path:S.path,parent:S});else return M._parseSync({data:S.data,path:S.path,parent:S})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,S,$){let f=new Map;for(let M of S){let J=_$(M.shape[T]);if(!J.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let F of J){if(f.has(F))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String(F)}`);f.set(F,M)}}return new KF({typeName:x.ZodDiscriminatedUnion,discriminator:T,options:S,optionsMap:f,...FT($)})}}function R0(T,S){let $=v$(T),f=v$(S);if(T===S)return{valid:!0,data:T};else if($===n.object&&f===n.object){let M=GT.objectKeys(S),J=GT.objectKeys(T).filter((W)=>M.indexOf(W)!==-1),F={...T,...S};for(let W of J){let A=R0(T[W],S[W]);if(!A.valid)return{valid:!1};F[W]=A.data}return{valid:!0,data:F}}else if($===n.array&&f===n.array){if(T.length!==S.length)return{valid:!1};let M=[];for(let J=0;J<T.length;J++){let F=T[J],W=S[J],A=R0(F,W);if(!A.valid)return{valid:!1};M.push(A.data)}return{valid:!0,data:M}}else if($===n.date&&f===n.date&&+T===+S)return{valid:!0,data:T};else return{valid:!1}}class tf extends WT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T),f=(M,J)=>{if(w0(M)||w0(J))return ST;let F=R0(M.value,J.value);if(!F.valid)return v($,{code:j.invalid_intersection_types}),ST;if(Y0(M)||Y0(J))S.dirty();return{status:S.value,value:F.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([M,J])=>f(M,J));else return f(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}tf.create=(T,S,$)=>{return new tf({left:T,right:S,typeName:x.ZodIntersection,...FT($)})};class k$ extends WT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==n.array)return v($,{code:j.invalid_type,expected:n.array,received:$.parsedType}),ST;if($.data.length<this._def.items.length)return v($,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ST;if(!this._def.rest&&$.data.length>this._def.items.length)v($,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.dirty();let M=[...$.data].map((J,F)=>{let W=this._def.items[F]||this._def.rest;if(!W)return null;return W._parse(new aS($,J,$.path,F))}).filter((J)=>!!J);if($.common.async)return Promise.all(M).then((J)=>{return yS.mergeArray(S,J)});else return yS.mergeArray(S,M)}get items(){return this._def.items}rest(T){return new k$({...this._def,rest:T})}}k$.create=(T,S)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new k$({items:T,typeName:x.ZodTuple,rest:null,...FT(S)})};class pM extends WT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==n.object)return v($,{code:j.invalid_type,expected:n.object,received:$.parsedType}),ST;let f=[],M=this._def.keyType,J=this._def.valueType;for(let F in $.data)f.push({key:M._parse(new aS($,F,$.path,F)),value:J._parse(new aS($,$.data[F],$.path,F)),alwaysSet:F in $.data});if($.common.async)return yS.mergeObjectAsync(S,f);else return yS.mergeObjectSync(S,f)}get element(){return this._def.valueType}static create(T,S,$){if(S instanceof WT)return new pM({keyType:T,valueType:S,typeName:x.ZodRecord,...FT($)});return new pM({keyType:uS.create(),valueType:T,typeName:x.ZodRecord,...FT(S)})}}class iM extends WT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==n.map)return v($,{code:j.invalid_type,expected:n.map,received:$.parsedType}),ST;let f=this._def.keyType,M=this._def.valueType,J=[...$.data.entries()].map(([F,W],A)=>{return{key:f._parse(new aS($,F,$.path,[A,"key"])),value:M._parse(new aS($,W,$.path,[A,"value"]))}});if($.common.async){let F=new Map;return Promise.resolve().then(async()=>{for(let W of J){let A=await W.key,k=await W.value;if(A.status==="aborted"||k.status==="aborted")return ST;if(A.status==="dirty"||k.status==="dirty")S.dirty();F.set(A.value,k.value)}return{status:S.value,value:F}})}else{let F=new Map;for(let W of J){let{key:A,value:k}=W;if(A.status==="aborted"||k.status==="aborted")return ST;if(A.status==="dirty"||k.status==="dirty")S.dirty();F.set(A.value,k.value)}return{status:S.value,value:F}}}}iM.create=(T,S,$)=>{return new iM({valueType:S,keyType:T,typeName:x.ZodMap,...FT($)})};class Sf extends WT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==n.set)return v($,{code:j.invalid_type,expected:n.set,received:$.parsedType}),ST;let f=this._def;if(f.minSize!==null){if($.data.size<f.minSize.value)v($,{code:j.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),S.dirty()}if(f.maxSize!==null){if($.data.size>f.maxSize.value)v($,{code:j.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),S.dirty()}let M=this._def.valueType;function J(W){let A=new Set;for(let k of W){if(k.status==="aborted")return ST;if(k.status==="dirty")S.dirty();A.add(k.value)}return{status:S.value,value:A}}let F=[...$.data.values()].map((W,A)=>M._parse(new aS($,W,$.path,A)));if($.common.async)return Promise.all(F).then((W)=>J(W));else return J(F)}min(T,S){return new Sf({...this._def,minSize:{value:T,message:l.toString(S)}})}max(T,S){return new Sf({...this._def,maxSize:{value:T,message:l.toString(S)}})}size(T,S){return this.min(T,S).max(T,S)}nonempty(T){return this.min(1,T)}}Sf.create=(T,S)=>{return new Sf({valueType:T,minSize:null,maxSize:null,typeName:x.ZodSet,...FT(S)})};class vf extends WT{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==n.function)return v(S,{code:j.invalid_type,expected:n.function,received:S.parsedType}),ST;function $(F,W){return XF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,kF(),Pf].filter((A)=>!!A),issueData:{code:j.invalid_arguments,argumentsError:W}})}function f(F,W){return XF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,kF(),Pf].filter((A)=>!!A),issueData:{code:j.invalid_return_type,returnTypeError:W}})}let M={errorMap:S.common.contextualErrorMap},J=S.data;if(this._def.returns instanceof $f){let F=this;return OS(async function(...W){let A=new LS([]),k=await F._def.args.parseAsync(W,M).catch((K)=>{throw A.addIssue($(W,K)),A}),X=await Reflect.apply(J,this,k);return await F._def.returns._def.type.parseAsync(X,M).catch((K)=>{throw A.addIssue(f(X,K)),A})})}else{let F=this;return OS(function(...W){let A=F._def.args.safeParse(W,M);if(!A.success)throw new LS([$(W,A.error)]);let k=Reflect.apply(J,this,A.data),X=F._def.returns.safeParse(k,M);if(!X.success)throw new LS([f(k,X.error)]);return X.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new vf({...this._def,args:k$.create(T).rest(P$.create())})}returns(T){return new vf({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,S,$){return new vf({args:T?T:k$.create([]).rest(P$.create()),returns:S||P$.create(),typeName:x.ZodFunction,...FT($)})}}class pf extends WT{get schema(){return this._def.getter()}_parse(T){let{ctx:S}=this._processInputParams(T);return this._def.getter()._parse({data:S.data,path:S.path,parent:S})}}pf.create=(T,S)=>{return new pf({getter:T,typeName:x.ZodLazy,...FT(S)})};class lf extends WT{_parse(T){if(T.data!==this._def.value){let S=this._getOrReturnCtx(T);return v(S,{received:S.data,code:j.invalid_literal,expected:this._def.value}),ST}return{status:"valid",value:T.data}}get value(){return this._def.value}}lf.create=(T,S)=>{return new lf({value:T,typeName:x.ZodLiteral,...FT(S)})};function _k(T,S){return new o$({values:T,typeName:x.ZodEnum,...FT(S)})}class o$ extends WT{constructor(){super(...arguments);PM.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){let S=this._getOrReturnCtx(T),$=this._def.values;return v(S,{expected:GT.joinValues($),received:S.parsedType,code:j.invalid_type}),ST}if(!yF(this,PM,"f"))Rk(this,PM,new Set(this._def.values),"f");if(!yF(this,PM,"f").has(T.data)){let S=this._getOrReturnCtx(T),$=this._def.values;return v(S,{received:S.data,code:j.invalid_enum_value,options:$}),ST}return OS(T.data)}get options(){return this._def.values}get enum(){let T={};for(let S of this._def.values)T[S]=S;return T}get Values(){let T={};for(let S of this._def.values)T[S]=S;return T}get Enum(){let T={};for(let S of this._def.values)T[S]=S;return T}extract(T,S=this._def){return o$.create(T,{...this._def,...S})}exclude(T,S=this._def){return o$.create(this.options.filter(($)=>!T.includes($)),{...this._def,...S})}}PM=new WeakMap;o$.create=_k;class uf extends WT{constructor(){super(...arguments);nM.set(this,void 0)}_parse(T){let S=GT.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(T);if($.parsedType!==n.string&&$.parsedType!==n.number){let f=GT.objectValues(S);return v($,{expected:GT.joinValues(f),received:$.parsedType,code:j.invalid_type}),ST}if(!yF(this,nM,"f"))Rk(this,nM,new Set(GT.getValidEnumValues(this._def.values)),"f");if(!yF(this,nM,"f").has(T.data)){let f=GT.objectValues(S);return v($,{received:$.data,code:j.invalid_enum_value,options:f}),ST}return OS(T.data)}get enum(){return this._def.values}}nM=new WeakMap;uf.create=(T,S)=>{return new uf({values:T,typeName:x.ZodNativeEnum,...FT(S)})};class $f extends WT{unwrap(){return this._def.type}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==n.promise&&S.common.async===!1)return v(S,{code:j.invalid_type,expected:n.promise,received:S.parsedType}),ST;let $=S.parsedType===n.promise?S.data:Promise.resolve(S.data);return OS($.then((f)=>{return this._def.type.parseAsync(f,{path:S.path,errorMap:S.common.contextualErrorMap})}))}}$f.create=(T,S)=>{return new $f({type:T,typeName:x.ZodPromise,...FT(S)})};class hS extends WT{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){let{status:S,ctx:$}=this._processInputParams(T),f=this._def.effect||null,M={addIssue:(J)=>{if(v($,J),J.fatal)S.abort();else S.dirty()},get path(){return $.path}};if(M.addIssue=M.addIssue.bind(M),f.type==="preprocess"){let J=f.transform($.data,M);if($.common.async)return Promise.resolve(J).then(async(F)=>{if(S.value==="aborted")return ST;let W=await this._def.schema._parseAsync({data:F,path:$.path,parent:$});if(W.status==="aborted")return ST;if(W.status==="dirty")return hf(W.value);if(S.value==="dirty")return hf(W.value);return W});else{if(S.value==="aborted")return ST;let F=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(F.status==="aborted")return ST;if(F.status==="dirty")return hf(F.value);if(S.value==="dirty")return hf(F.value);return F}}if(f.type==="refinement"){let J=(F)=>{let W=f.refinement(F,M);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return F};if($.common.async===!1){let F=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(F.status==="aborted")return ST;if(F.status==="dirty")S.dirty();return J(F.value),{status:S.value,value:F.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((F)=>{if(F.status==="aborted")return ST;if(F.status==="dirty")S.dirty();return J(F.value).then(()=>{return{status:S.value,value:F.value}})})}if(f.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!cM(J))return J;let F=f.transform(J.value,M);if(F instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:S.value,value:F}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!cM(J))return J;return Promise.resolve(f.transform(J.value,M)).then((F)=>({status:S.value,value:F}))});GT.assertNever(f)}}hS.create=(T,S,$)=>{return new hS({schema:T,typeName:x.ZodEffects,effect:S,...FT($)})};hS.createWithPreprocess=(T,S,$)=>{return new hS({schema:S,effect:{type:"preprocess",transform:T},typeName:x.ZodEffects,...FT($)})};class rS extends WT{_parse(T){if(this._getType(T)===n.undefined)return OS(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}rS.create=(T,S)=>{return new rS({innerType:T,typeName:x.ZodOptional,...FT(S)})};class H$ extends WT{_parse(T){if(this._getType(T)===n.null)return OS(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}H$.create=(T,S)=>{return new H$({innerType:T,typeName:x.ZodNullable,...FT(S)})};class df extends WT{_parse(T){let{ctx:S}=this._processInputParams(T),$=S.data;if(S.parsedType===n.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:S.path,parent:S})}removeDefault(){return this._def.innerType}}df.create=(T,S)=>{return new df({innerType:T,typeName:x.ZodDefault,defaultValue:typeof S.default==="function"?S.default:()=>S.default,...FT(S)})};class rf extends WT{_parse(T){let{ctx:S}=this._processInputParams(T),$={...S,common:{...S.common,issues:[]}},f=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(oM(f))return f.then((M)=>{return{status:"valid",value:M.status==="valid"?M.value:this._def.catchValue({get error(){return new LS($.common.issues)},input:$.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new LS($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}rf.create=(T,S)=>{return new rf({innerType:T,typeName:x.ZodCatch,catchValue:typeof S.catch==="function"?S.catch:()=>S.catch,...FT(S)})};class lM extends WT{_parse(T){if(this._getType(T)!==n.nan){let $=this._getOrReturnCtx(T);return v($,{code:j.invalid_type,expected:n.nan,received:$.parsedType}),ST}return{status:"valid",value:T.data}}}lM.create=(T)=>{return new lM({typeName:x.ZodNaN,...FT(T)})};var a4=Symbol("zod_brand");class wF extends WT{_parse(T){let{ctx:S}=this._processInputParams(T),$=S.data;return this._def.type._parse({data:$,path:S.path,parent:S})}unwrap(){return this._def.type}}class uM extends WT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.common.async)return(async()=>{let M=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(M.status==="aborted")return ST;if(M.status==="dirty")return S.dirty(),hf(M.value);else return this._def.out._parseAsync({data:M.value,path:$.path,parent:$})})();else{let f=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(f.status==="aborted")return ST;if(f.status==="dirty")return S.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:$.path,parent:$})}}static create(T,S){return new uM({in:T,out:S,typeName:x.ZodPipeline})}}class af extends WT{_parse(T){let S=this._def.innerType._parse(T),$=(f)=>{if(cM(f))f.value=Object.freeze(f.value);return f};return oM(S)?S.then((f)=>$(f)):$(S)}unwrap(){return this._def.innerType}}af.create=(T,S)=>{return new af({innerType:T,typeName:x.ZodReadonly,...FT(S)})};function Hk(T,S={},$){if(T)return Tf.create().superRefine((f,M)=>{var J,F;if(!T(f)){let W=typeof S==="function"?S(f):typeof S==="string"?{message:S}:S,A=(F=(J=W.fatal)!==null&&J!==void 0?J:$)!==null&&F!==void 0?F:!0,k=typeof W==="string"?{message:W}:W;M.addIssue({code:"custom",...k,fatal:A})}});return Tf.create()}var e4={object:ZT.lazycreate},x;(function(T){T.ZodString="ZodString",T.ZodNumber="ZodNumber",T.ZodNaN="ZodNaN",T.ZodBigInt="ZodBigInt",T.ZodBoolean="ZodBoolean",T.ZodDate="ZodDate",T.ZodSymbol="ZodSymbol",T.ZodUndefined="ZodUndefined",T.ZodNull="ZodNull",T.ZodAny="ZodAny",T.ZodUnknown="ZodUnknown",T.ZodNever="ZodNever",T.ZodVoid="ZodVoid",T.ZodArray="ZodArray",T.ZodObject="ZodObject",T.ZodUnion="ZodUnion",T.ZodDiscriminatedUnion="ZodDiscriminatedUnion",T.ZodIntersection="ZodIntersection",T.ZodTuple="ZodTuple",T.ZodRecord="ZodRecord",T.ZodMap="ZodMap",T.ZodSet="ZodSet",T.ZodFunction="ZodFunction",T.ZodLazy="ZodLazy",T.ZodLiteral="ZodLiteral",T.ZodEnum="ZodEnum",T.ZodEffects="ZodEffects",T.ZodNativeEnum="ZodNativeEnum",T.ZodOptional="ZodOptional",T.ZodNullable="ZodNullable",T.ZodDefault="ZodDefault",T.ZodCatch="ZodCatch",T.ZodPromise="ZodPromise",T.ZodBranded="ZodBranded",T.ZodPipeline="ZodPipeline",T.ZodReadonly="ZodReadonly"})(x||(x={}));var s4=(T,S={message:`Input not instance of ${T.name}`})=>Hk(($)=>$ instanceof T,S),Dk=uS.create,Ek=n$.create,Tw=lM.create,Sw=c$.create,Qk=nf.create,$w=s$.create,fw=gM.create,Mw=cf.create,Jw=of.create,Fw=Tf.create,Ww=P$.create,Aw=A$.create,kw=tM.create,Xw=dS.create,dM=ZT.create,yw=ZT.strictCreate,Kw=gf.create,ww=KF.create,Yw=tf.create,Rw=k$.create,Ow=pM.create,Gw=iM.create,zw=Sf.create,_w=vf.create,Hw=pf.create,Dw=lf.create,Ew=o$.create,Qw=uf.create,Uw=$f.create,wk=hS.create,Vw=rS.create,Bw=H$.create,Lw=hS.createWithPreprocess,Nw=uM.create,Cw=()=>Dk().optional(),xw=()=>Ek().optional(),jw=()=>Qk().optional(),Iw={string:(T)=>uS.create({...T,coerce:!0}),number:(T)=>n$.create({...T,coerce:!0}),boolean:(T)=>nf.create({...T,coerce:!0}),bigint:(T)=>c$.create({...T,coerce:!0}),date:(T)=>s$.create({...T,coerce:!0})},bw=ST,HT=Object.freeze({__proto__:null,defaultErrorMap:Pf,setErrorMap:q4,getErrorMap:kF,makeIssue:XF,EMPTY_PATH:Z4,addIssueToContext:v,ParseStatus:yS,INVALID:ST,DIRTY:hf,OK:OS,isAborted:w0,isDirty:Y0,isValid:cM,isAsync:oM,get util(){return GT},get objectUtil(){return K0},ZodParsedType:n,getParsedType:v$,ZodType:WT,datetimeRegex:zk,ZodString:uS,ZodNumber:n$,ZodBigInt:c$,ZodBoolean:nf,ZodDate:s$,ZodSymbol:gM,ZodUndefined:cf,ZodNull:of,ZodAny:Tf,ZodUnknown:P$,ZodNever:A$,ZodVoid:tM,ZodArray:dS,ZodObject:ZT,ZodUnion:gf,ZodDiscriminatedUnion:KF,ZodIntersection:tf,ZodTuple:k$,ZodRecord:pM,ZodMap:iM,ZodSet:Sf,ZodFunction:vf,ZodLazy:pf,ZodLiteral:lf,ZodEnum:o$,ZodNativeEnum:uf,ZodPromise:$f,ZodEffects:hS,ZodTransformer:hS,ZodOptional:rS,ZodNullable:H$,ZodDefault:df,ZodCatch:rf,ZodNaN:lM,BRAND:a4,ZodBranded:wF,ZodPipeline:uM,ZodReadonly:af,custom:Hk,Schema:WT,ZodSchema:WT,late:e4,get ZodFirstPartyTypeKind(){return x},coerce:Iw,any:Fw,array:Xw,bigint:Sw,boolean:Qk,date:$w,discriminatedUnion:ww,effect:wk,enum:Ew,function:_w,instanceof:s4,intersection:Yw,lazy:Hw,literal:Dw,map:Gw,nan:Tw,nativeEnum:Qw,never:Aw,null:Jw,nullable:Bw,number:Ek,object:dM,oboolean:jw,onumber:xw,optional:Vw,ostring:Cw,pipeline:Nw,preprocess:Lw,promise:Uw,record:Ow,set:zw,strictObject:yw,string:Dk,symbol:fw,transformer:wk,tuple:Rw,undefined:Mw,union:Kw,unknown:Ww,void:kw,NEVER:bw,ZodIssueCode:j,quotelessJson:b4,ZodError:LS});function Uk(){return{}}function Vk(T,S){let $={type:"array"};if(T.type?._def&&T.type?._def?.typeName!==x.ZodAny)$.items=s(T.type._def,{...S,currentPath:[...S.currentPath,"items"]});if(T.minLength)YT($,"minItems",T.minLength.value,T.minLength.message,S);if(T.maxLength)YT($,"maxItems",T.maxLength.value,T.maxLength.message,S);if(T.exactLength)YT($,"minItems",T.exactLength.value,T.exactLength.message,S),YT($,"maxItems",T.exactLength.value,T.exactLength.message,S);return $}function Bk(T,S){let $={type:"integer",format:"int64"};if(!T.checks)return $;for(let f of T.checks)switch(f.kind){case"min":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"minimum",f.value,f.message,S);else YT($,"exclusiveMinimum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMinimum=!0;YT($,"minimum",f.value,f.message,S)}break;case"max":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"maximum",f.value,f.message,S);else YT($,"exclusiveMaximum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMaximum=!0;YT($,"maximum",f.value,f.message,S)}break;case"multipleOf":YT($,"multipleOf",f.value,f.message,S);break}return $}function Lk(){return{type:"boolean"}}function YF(T,S){return s(T.type._def,S)}var Nk=(T,S)=>{return s(T.innerType._def,S)};function O0(T,S,$){let f=$??S.dateStrategy;if(Array.isArray(f))return{anyOf:f.map((M,J)=>O0(T,S,M))};switch(f){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return qw(T,S)}}var qw=(T,S)=>{let $={type:"integer",format:"unix-time"};if(S.target==="openApi3")return $;for(let f of T.checks)switch(f.kind){case"min":YT($,"minimum",f.value,f.message,S);break;case"max":YT($,"maximum",f.value,f.message,S);break}return $};function Ck(T,S){return{...s(T.innerType._def,S),default:T.defaultValue()}}function xk(T,S){return S.effectStrategy==="input"?s(T.schema._def,S):{}}function jk(T){return{type:"string",enum:T.values}}var Zw=(T)=>{if("type"in T&&T.type==="string")return!1;return"allOf"in T};function Ik(T,S){let $=[s(T.left._def,{...S,currentPath:[...S.currentPath,"allOf","0"]}),s(T.right._def,{...S,currentPath:[...S.currentPath,"allOf","1"]})].filter((J)=>!!J),f=S.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,M=[];return $.forEach((J)=>{if(Zw(J)){if(M.push(...J.allOf),J.unevaluatedProperties===void 0)f=void 0}else{let F=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...A}=J;F=A}else f=void 0;M.push(F)}}),M.length?{allOf:M,...f}:void 0}function bk(T,S){let $=typeof T.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(T.value)?"array":"object"};if(S.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[T.value]};return{type:$==="bigint"?"integer":$,const:T.value}}var G0,ff={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(G0===void 0)G0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return G0},uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function RF(T,S){let $={type:"string"};function f(M){return S.patternStrategy==="escape"?mw(M):M}if(T.checks)for(let M of T.checks)switch(M.kind){case"min":YT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,M.value):M.value,M.message,S);break;case"max":YT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,M.value):M.value,M.message,S);break;case"email":switch(S.emailStrategy){case"format:email":eS($,"email",M.message,S);break;case"format:idn-email":eS($,"idn-email",M.message,S);break;case"pattern:zod":sS($,ff.email,M.message,S);break}break;case"url":eS($,"uri",M.message,S);break;case"uuid":eS($,"uuid",M.message,S);break;case"regex":sS($,M.regex,M.message,S);break;case"cuid":sS($,ff.cuid,M.message,S);break;case"cuid2":sS($,ff.cuid2,M.message,S);break;case"startsWith":sS($,RegExp(`^${f(M.value)}`),M.message,S);break;case"endsWith":sS($,RegExp(`${f(M.value)}\$`),M.message,S);break;case"datetime":eS($,"date-time",M.message,S);break;case"date":eS($,"date",M.message,S);break;case"time":eS($,"time",M.message,S);break;case"duration":eS($,"duration",M.message,S);break;case"length":YT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,M.value):M.value,M.message,S),YT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,M.value):M.value,M.message,S);break;case"includes":{sS($,RegExp(f(M.value)),M.message,S);break}case"ip":{if(M.version!=="v6")eS($,"ipv4",M.message,S);if(M.version!=="v4")eS($,"ipv6",M.message,S);break}case"emoji":sS($,ff.emoji,M.message,S);break;case"ulid":{sS($,ff.ulid,M.message,S);break}case"base64":{switch(S.base64Strategy){case"format:binary":{eS($,"binary",M.message,S);break}case"contentEncoding:base64":{YT($,"contentEncoding","base64",M.message,S);break}case"pattern:zod":{sS($,ff.base64,M.message,S);break}}break}case"nanoid":sS($,ff.nanoid,M.message,S);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(M)}return $}var mw=(T)=>Array.from(T).map((S)=>/[a-zA-Z0-9]/.test(S)?S:`\\${S}`).join(""),eS=(T,S,$,f)=>{if(T.format||T.anyOf?.some((M)=>M.format)){if(!T.anyOf)T.anyOf=[];if(T.format){if(T.anyOf.push({format:T.format,...T.errorMessage&&f.errorMessages&&{errorMessage:{format:T.errorMessage.format}}}),delete T.format,T.errorMessage){if(delete T.errorMessage.format,Object.keys(T.errorMessage).length===0)delete T.errorMessage}}T.anyOf.push({format:S,...$&&f.errorMessages&&{errorMessage:{format:$}}})}else YT(T,"format",S,$,f)},sS=(T,S,$,f)=>{if(T.pattern||T.allOf?.some((M)=>M.pattern)){if(!T.allOf)T.allOf=[];if(T.pattern){if(T.allOf.push({pattern:T.pattern,...T.errorMessage&&f.errorMessages&&{errorMessage:{pattern:T.errorMessage.pattern}}}),delete T.pattern,T.errorMessage){if(delete T.errorMessage.pattern,Object.keys(T.errorMessage).length===0)delete T.errorMessage}}T.allOf.push({pattern:qk(S,f),...$&&f.errorMessages&&{errorMessage:{pattern:$}}})}else YT(T,"pattern",qk(S,f),$,f)},qk=(T,S)=>{let $=typeof T==="function"?T():T;if(!S.applyRegexFlags||!$.flags)return $.source;let f={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},M=f.i?$.source.toLowerCase():$.source,J="",F=!1,W=!1,A=!1;for(let k=0;k<M.length;k++){if(F){J+=M[k],F=!1;continue}if(f.i){if(W){if(M[k].match(/[a-z]/)){if(A)J+=M[k],J+=`${M[k-2]}-${M[k]}`.toUpperCase(),A=!1;else if(M[k+1]==="-"&&M[k+2]?.match(/[a-z]/))J+=M[k],A=!0;else J+=`${M[k]}${M[k].toUpperCase()}`;continue}}else if(M[k].match(/[a-z]/)){J+=`[${M[k]}${M[k].toUpperCase()}]`;continue}}if(f.m){if(M[k]==="^"){J+="(^|(?<=[\r\n]))";continue}else if(M[k]==="$"){J+="($|(?=[\r\n]))";continue}}if(f.s&&M[k]==="."){J+=W?`${M[k]}\r\n`:`[${M[k]}\r\n]`;continue}if(J+=M[k],M[k]==="\\")F=!0;else if(W&&M[k]==="]")W=!1;else if(!W&&M[k]==="[")W=!0}try{let k=new RegExp(J)}catch{return console.warn(`Could not convert regex pattern at ${S.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return J};function OF(T,S){if(S.target==="openApi3"&&T.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:T.keyType._def.values,properties:T.keyType._def.values.reduce((f,M)=>({...f,[M]:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"properties",M]})??{}}),{}),additionalProperties:!1};let $={type:"object",additionalProperties:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??{}};if(S.target==="openApi3")return $;if(T.keyType?._def.typeName===x.ZodString&&T.keyType._def.checks?.length){let{type:f,...M}=RF(T.keyType._def,S);return{...$,propertyNames:M}}else if(T.keyType?._def.typeName===x.ZodEnum)return{...$,propertyNames:{enum:T.keyType._def.values}};else if(T.keyType?._def.typeName===x.ZodBranded&&T.keyType._def.type._def.typeName===x.ZodString&&T.keyType._def.type._def.checks?.length){let{type:f,...M}=YF(T.keyType._def,S);return{...$,propertyNames:M}}return $}function Zk(T,S){if(S.mapStrategy==="record")return OF(T,S);let $=s(T.keyType._def,{...S,currentPath:[...S.currentPath,"items","items","0"]})||{},f=s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[$,f],minItems:2,maxItems:2}}}function mk(T){let S=T.values,f=Object.keys(T.values).filter((J)=>{return typeof S[S[J]]!=="number"}).map((J)=>S[J]),M=Array.from(new Set(f.map((J)=>typeof J)));return{type:M.length===1?M[0]==="string"?"string":"number":["string","number"],enum:f}}function hk(){return{not:{}}}function vk(T){return T.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var rM={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nk(T,S){if(S.target==="openApi3")return Pk(T,S);let $=T.options instanceof Map?Array.from(T.options.values()):T.options;if($.every((f)=>(f._def.typeName in rM)&&(!f._def.checks||!f._def.checks.length))){let f=$.reduce((M,J)=>{let F=rM[J._def.typeName];return F&&!M.includes(F)?[...M,F]:M},[]);return{type:f.length>1?f:f[0]}}else if($.every((f)=>f._def.typeName==="ZodLiteral"&&!f.description)){let f=$.reduce((M,J)=>{let F=typeof J._def.value;switch(F){case"string":case"number":case"boolean":return[...M,F];case"bigint":return[...M,"integer"];case"object":if(J._def.value===null)return[...M,"null"];case"symbol":case"undefined":case"function":default:return M}},[]);if(f.length===$.length){let M=f.filter((J,F,W)=>W.indexOf(J)===F);return{type:M.length>1?M:M[0],enum:$.reduce((J,F)=>{return J.includes(F._def.value)?J:[...J,F._def.value]},[])}}}else if($.every((f)=>f._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((f,M)=>[...f,...M._def.values.filter((J)=>!f.includes(J))],[])};return Pk(T,S)}var Pk=(T,S)=>{let $=(T.options instanceof Map?Array.from(T.options.values()):T.options).map((f,M)=>s(f._def,{...S,currentPath:[...S.currentPath,"anyOf",`${M}`]})).filter((f)=>!!f&&(!S.strictUnions||typeof f==="object"&&Object.keys(f).length>0));return $.length?{anyOf:$}:void 0};function ck(T,S){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(T.innerType._def.typeName)&&(!T.innerType._def.checks||!T.innerType._def.checks.length)){if(S.target==="openApi3")return{type:rM[T.innerType._def.typeName],nullable:!0};return{type:[rM[T.innerType._def.typeName],"null"]}}if(S.target==="openApi3"){let f=s(T.innerType._def,{...S,currentPath:[...S.currentPath]});if(f&&"$ref"in f)return{allOf:[f],nullable:!0};return f&&{...f,nullable:!0}}let $=s(T.innerType._def,{...S,currentPath:[...S.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function ok(T,S){let $={type:"number"};if(!T.checks)return $;for(let f of T.checks)switch(f.kind){case"int":$.type="integer",X0($,"type",f.message,S);break;case"min":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"minimum",f.value,f.message,S);else YT($,"exclusiveMinimum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMinimum=!0;YT($,"minimum",f.value,f.message,S)}break;case"max":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"maximum",f.value,f.message,S);else YT($,"exclusiveMaximum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMaximum=!0;YT($,"maximum",f.value,f.message,S)}break;case"multipleOf":YT($,"multipleOf",f.value,f.message,S);break}return $}function hw(T,S){if(S.removeAdditionalStrategy==="strict")return T.catchall._def.typeName==="ZodNever"?T.unknownKeys!=="strict":s(T.catchall._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??!0;else return T.catchall._def.typeName==="ZodNever"?T.unknownKeys==="passthrough":s(T.catchall._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??!0}function gk(T,S){let $={type:"object",...Object.entries(T.shape()).reduce((f,[M,J])=>{if(J===void 0||J._def===void 0)return f;let F=s(J._def,{...S,currentPath:[...S.currentPath,"properties",M],propertyPath:[...S.currentPath,"properties",M]});if(F===void 0)return f;return{properties:{...f.properties,[M]:F},required:J.isOptional()?f.required:[...f.required,M]}},{properties:{},required:[]}),additionalProperties:hw(T,S)};if(!$.required.length)delete $.required;return $}var tk=(T,S)=>{if(S.currentPath.toString()===S.propertyPath?.toString())return s(T.innerType._def,S);let $=s(T.innerType._def,{...S,currentPath:[...S.currentPath,"anyOf","1"]});return $?{anyOf:[{not:{}},$]}:{}};var pk=(T,S)=>{if(S.pipeStrategy==="input")return s(T.in._def,S);else if(S.pipeStrategy==="output")return s(T.out._def,S);let $=s(T.in._def,{...S,currentPath:[...S.currentPath,"allOf","0"]}),f=s(T.out._def,{...S,currentPath:[...S.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,f].filter((M)=>M!==void 0)}};function ik(T,S){return s(T.type._def,S)}function lk(T,S){let f={type:"array",uniqueItems:!0,items:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items"]})};if(T.minSize)YT(f,"minItems",T.minSize.value,T.minSize.message,S);if(T.maxSize)YT(f,"maxItems",T.maxSize.value,T.maxSize.message,S);return f}function uk(T,S){if(T.rest)return{type:"array",minItems:T.items.length,items:T.items.map(($,f)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${f}`]})).reduce(($,f)=>f===void 0?$:[...$,f],[]),additionalItems:s(T.rest._def,{...S,currentPath:[...S.currentPath,"additionalItems"]})};else return{type:"array",minItems:T.items.length,maxItems:T.items.length,items:T.items.map(($,f)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${f}`]})).reduce(($,f)=>f===void 0?$:[...$,f],[])}}function dk(){return{not:{}}}function rk(){return{}}var ak=(T,S)=>{return s(T.innerType._def,S)};function s(T,S,$=!1){let f=S.seen.get(T);if(S.override){let F=S.override?.(T,S,f,$);if(F!==kk)return F}if(f&&!$){let F=vw(f,S);if(F!==void 0)return F}let M={def:T,path:S.currentPath,jsonSchema:void 0};S.seen.set(T,M);let J=nw(T,T.typeName,S);if(J)cw(T,S,J);return M.jsonSchema=J,J}var vw=(T,S)=>{switch(S.$refStrategy){case"root":return{$ref:T.path.join("/")};case"relative":return{$ref:Pw(S.currentPath,T.path)};case"none":case"seen":{if(T.path.length<S.currentPath.length&&T.path.every(($,f)=>S.currentPath[f]===$))return console.warn(`Recursive reference detected at ${S.currentPath.join("/")}! Defaulting to any`),{};return S.$refStrategy==="seen"?{}:void 0}}},Pw=(T,S)=>{let $=0;for(;$<T.length&&$<S.length;$++)if(T[$]!==S[$])break;return[(T.length-$).toString(),...S.slice($)].join("/")},nw=(T,S,$)=>{switch(S){case x.ZodString:return RF(T,$);case x.ZodNumber:return ok(T,$);case x.ZodObject:return gk(T,$);case x.ZodBigInt:return Bk(T,$);case x.ZodBoolean:return Lk();case x.ZodDate:return O0(T,$);case x.ZodUndefined:return dk();case x.ZodNull:return vk($);case x.ZodArray:return Vk(T,$);case x.ZodUnion:case x.ZodDiscriminatedUnion:return nk(T,$);case x.ZodIntersection:return Ik(T,$);case x.ZodTuple:return uk(T,$);case x.ZodRecord:return OF(T,$);case x.ZodLiteral:return bk(T,$);case x.ZodEnum:return jk(T);case x.ZodNativeEnum:return mk(T);case x.ZodNullable:return ck(T,$);case x.ZodOptional:return tk(T,$);case x.ZodMap:return Zk(T,$);case x.ZodSet:return lk(T,$);case x.ZodLazy:return s(T.getter()._def,$);case x.ZodPromise:return ik(T,$);case x.ZodNaN:case x.ZodNever:return hk();case x.ZodEffects:return xk(T,$);case x.ZodAny:return Uk();case x.ZodUnknown:return rk();case x.ZodDefault:return Ck(T,$);case x.ZodBranded:return YF(T,$);case x.ZodReadonly:return ak(T,$);case x.ZodCatch:return Nk(T,$);case x.ZodPipeline:return pk(T,$);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return((f)=>{return})(S)}},cw=(T,S,$)=>{if(T.description){if($.description=T.description,S.markdownDescription)$.markdownDescription=T.description}return $};var ek=(T,S)=>{let $=yk(S),f=typeof S==="object"&&S.definitions?Object.entries(S.definitions).reduce((A,[k,X])=>({...A,[k]:s(X._def,{...$,currentPath:[...$.basePath,$.definitionPath,k]},!0)??{}}),{}):void 0,M=typeof S==="string"?S:S?.nameStrategy==="title"?void 0:S?.name,J=s(T._def,M===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,M]},!1)??{},F=typeof S==="object"&&S.name!==void 0&&S.nameStrategy==="title"?S.name:void 0;if(F!==void 0)J.title=F;let W=M===void 0?f?{...J,[$.definitionPath]:f}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,M].join("/"),[$.definitionPath]:{...f,[M]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09")W.$schema="https://json-schema.org/draft/2019-09/schema#";return W};var sk=ek;function TX(T,S){return function $({schema:f,fallback:M}){let J=sk(f);return async function F(W,A=3){let k,X=[];while(X.length<A){k=await T(W,J,M,X);let y=f.safeParse(k);if(y.success)return y.data;S?.warn(`safegen failed to generate well-formed data.
3
+ var z4=Object.create;var{getPrototypeOf:_4,defineProperty:gW,getOwnPropertyNames:H4}=Object;var E4=Object.prototype.hasOwnProperty;var Oy=(T,S,$)=>{$=T!=null?z4(_4(T)):{};let f=S||!T||!T.__esModule?gW($,"default",{value:T,enumerable:!0}):$;for(let M of H4(T))if(!E4.call(f,M))gW(f,M,{get:()=>T[M],enumerable:!0});return f};var Ry=(T,S)=>()=>(S||T((S={exports:{}}).exports,S),S.exports);var D4=(T,S)=>{for(var $ in S)gW(T,$,{get:S[$],enumerable:!0,configurable:!0,set:(f)=>S[$]=()=>f})};function xf(T=Math.random){return T().toString(36).slice(2)}class NM extends Promise{fate;resolve;reject;done=!1;constructor(T){let S,$;super((f,M)=>{S=f,$=M});this.resolve=S,this.reject=$,this.use(T instanceof Promise?T:new Promise(T))}pass(T,S){if(T===this.fate)this.resolve(S),this.done=!0}fail(T,S){if(T===this.fate)this.reject(S),this.done=!0}use(T){if(T instanceof Promise){let S=T;this.fate=S,S.then(($)=>{this.pass(S,$)},($)=>{this.fail(S,$)})}else this.resolve(T),this.fate=void 0}}function Hy(T){return Object.entries(T)}var EA=(T,S,$=WT.STORE)=>{return tS($,{key:`${T.key}:JSON`,get:({get:f})=>S.toJson(f(T)),set:({set:f},M)=>{f(T,S.fromJson(M))}})};function I(T){while(T.child!==null)T=T.child;return T}function DA(T){while(T.parent!==null)T=T.parent;return T}class fT{Subscriber;subscribers=new Map;subscribe(T,S){return this.subscribers.set(T,S),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let S=this.subscribers.values();for(let $ of S)$(T)}}class oW extends fT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function F$(T,S,$){let f={key:S.key,type:"atom_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","atom_family",S.key,`Overwriting an existing ${pS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new fT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},w=`${S.key}(${k})`,K=I(T),G=S.default,z={key:w,default:G instanceof Function?G(A):G};if(S.effects)z.effects=S.effects(A);let U=ES(K,z,X);return J.next({type:"state_creation",token:U}),U},f,{subject:J,install:(A)=>F$(A,S),internalRoles:$});return T.families.set(S.key,W),T.defaults.set(S.key,S.default),f}function QA(T,S){if("mutable"in S)return CM(T,S);return F$(T,S)}function O$(T,S,$){let f={key:S.key,type:"readonly_selector_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","readonly_selector_family",S.key,`Overwriting an existing ${pS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new fT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},w=`${S.key}(${k})`,K=I(T),G=xM(K,{key:w,get:S.get(A)},X);return J.next({type:"state_creation",token:G}),G},f,{internalRoles:$,subject:J,install:(A)=>O$(A,S),default:(A)=>{return S.get(A)({get:(...X)=>kT(T,...X),find:(X,w)=>YT(T,X,w),seek:(X,w)=>CT(T,X,w),json:(X)=>PT(T,X)})}});return T.families.set(S.key,W),f}function jM(T,S){if("set"in S)return IM(T,S);return O$(T,S)}var Q4={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function jf(T,S){let $=e(S),f=`${T.key}(${$})`,M=Q4[T.type],J={key:f,type:M};if(M==="molecule")Object.assign(J,{key:S,family:T});else Object.assign(J,{family:{key:T.key,subKey:$}});return Object.assign(J,{counterfeit:!0}),J}function XS(T){let S={key:T.key,type:T.type};if("family"in T)S.family=T.family;return S}var ly=Symbol("provenance");function tW(T,S,$){let f=e($);try{let M=[],J;if(S==="root")M.push(T.molecules.get('"root"')),J="all";else if(typeof S==="string"&&S.startsWith(U4)){J="any";let X=e(S),w=T.molecules.get(X);if(!w)throw new Error(`Molecule ${X} not found in store "${T.config.name}"`);M.push(w)}else if($.startsWith("T$--")){J="all";for(let w of S){let K=e(w),G=T.molecules.get(K);if(!G)throw new Error(`Molecule ${K} not found in store "${T.config.name}"`);M.push(G)}}else{J="any";let w=e(S),K=T.molecules.get(w);if(!K)throw new Error(`Molecule ${w} not found in store "${T.config.name}"`);M.push(K)}let F=new If(M,$);F._dependsOn=J,T.molecules.set(f,F);for(let X of M)X.below.set(F.stringKey,F);let W={type:"molecule_creation",subType:"modern",key:F.key,provenance:S},A=I(T);if(XT(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(W);else A.on.moleculeCreationStart.next(W)}catch(M){if(M instanceof Error)T.logger.error("\u274C","molecule",f,"allocation failed:",M.message)}return $}function bM(T,S){let $=e(S),f=T.molecules.get($);if(!f)throw new Error(`Molecule ${$} not found in store "${T.config.name}"`);for(let k of f.joins.values())k.relations.delete(f.key),k.molecules.delete(f.stringKey);let M;if(f.above.size===1)M=f.above.values().next().value.key;else M=[...f.above.values()].map(({key:k})=>k);let J=[];for(let k of f.tokens.values()){let X=k.family;J.push([X.key,T.valueMap.get(k.key)])}for(let k of f.tokens.values())RS(T,k);for(let k of f.below.values())if(k.dependsOn==="all")bM(T,k.key);else if(k.above.delete(f.stringKey),k.above.size===0)bM(T,k.key);f.below.clear();let F={type:"molecule_disposal",subType:"modern",key:f.key,values:J,provenance:M},W=I(T);if(XT(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(F);else W.on.moleculeDisposal.next(F);W.molecules.delete(f.stringKey);for(let k of f.above.values())k.below.delete(f.stringKey)}var U4="T$";function bf(T){return UA(WT.STORE,T)}function s$(T){return QA(WT.STORE,T)}function pW(...T){if(T.length===2)return kT(WT.STORE,...T);return kT(WT.STORE,...T)}var iW=(T)=>(S,$,f,M,...J)=>{console[T](`${S} ${$} "${f}" ${M}`,...J)},V4={error:iW("error"),info:iW("info"),warn:iW("warn")};class dW{logLevel;filter;logger;constructor(T,S,$=V4){this.logLevel=T;this.filter=S;this.logger=$}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}function lJ(T){return jM(WT.STORE,T)}function ZM(T){return uW(T,WT.STORE)}class BS{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,S)=>`${T}:${S}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,S){let $=this.relations.get(T),f=this.relations.get(S);if($)$.add(S);else $=new Set([S]),this.relations.set(T,$);if(f)f.add(T);else f=new Set([T]),this.relations.set(S,f)}deleteRelation(T,S){let $=this.relations.get(T);if($){if($.delete(S),$.size===0)this.relations.delete(T);let f=this.relations.get(S);if(f){if(f.delete(T),f.size===0)this.relations.delete(S)}}}replaceRelationsUnsafely(T,S){this.relations.set(T,new Set(S));for(let $ of S){let f=new Set().add(T);this.relations.set($,f)}}replaceRelationsSafely(T,S){let $=this.relations.get(T),f=this.isAType?.(T)?T:void 0,M=f===void 0?T:void 0;if($)for(let J of $){f??=J,M??=J;let F=this.relations.get(J);if(F){if(F.size===1)this.relations.delete(J);else F.delete(T);this.contents.delete(this.makeContentKey(f,M))}}this.relations.set(T,new Set(S));for(let J of S){let F=this.relations.get(J);if(F)F.add(T);else F=new Set().add(T),this.relations.set(J,F)}}getContentInternal(T){return this.contents.get(T)}setContent(T,S){this.contents.set(T,S)}deleteContent(T){this.contents.delete(T)}constructor(T,S){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!S?.externalStore)this.relations=new Map(T.relations?.map(([$,f])=>[$,new Set(f)])),this.contents=new Map(T.contents);if(this.isAType=S?.isAType??null,this.isBType=S?.isBType??null,this.isContent=S?.isContent??null,S?.makeContentKey)this.makeContentKey=S.makeContentKey;if(S?.externalStore){let $=S.externalStore;if(this.has=(f,M)=>$.has(f,M),this.addRelation=(f,M)=>{$.addRelation(f,M)},this.deleteRelation=(f,M)=>{$.deleteRelation(f,M)},this.replaceRelationsSafely=(f,M)=>{$.replaceRelationsSafely(f,M)},this.replaceRelationsUnsafely=(f,M)=>{$.replaceRelationsUnsafely(f,M)},this.getRelatedKeys=(f)=>$.getRelatedKeys(f),$.getContent)this.getContentInternal=(f)=>{return $.getContent(f)},this.setContent=(f,M)=>{$.setContent(f,M)},this.deleteContent=(f)=>{$.deleteContent(f)};for(let[f,M]of T.relations??[]){let J=this.isAType?.(f)?f:void 0,F=J===void 0?f:void 0;for(let W of M)J??=W,F??=W,this.addRelation(J,F)}for(let[f,M]of T.contents??[])this.setContent(f,M)}if(S?.warn)this.warn=S.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,S])=>[T,[...S]]),contents:[...this.contents.entries()]}}set(T,...S){let $=typeof S[0]==="string"?S[0]:T[this.b],f=S[1]??typeof S[0]==="string"?void 0:S[0];switch(T=typeof T==="string"?T:T[this.a],this.cardinality){case"1:1":{let M=this.getRelatedKey(T);if(M&&M!==$)this.delete(T,M)}case"1:n":{let M=this.getRelatedKey($);if(M&&M!==T)this.delete(M,$)}}if(f){let M=this.makeContentKey(T,$);this.setContent(M,f)}return this.addRelation(T,$),this}delete(T,S){S=typeof S==="string"?S:T[this.b];let $=typeof T==="string"?T:T[this.a];if($===void 0&&typeof S==="string"){let f=this.getRelatedKeys(S);if(f)for(let M of f)this.delete(M,S)}if(typeof $==="string"&&S===void 0){let f=this.getRelatedKeys($);if(f)for(let M of f)this.delete($,M)}if(typeof $==="string"&&typeof S==="string"){this.deleteRelation($,S);let f=this.makeContentKey($,S);this.deleteContent(f)}return this}getRelatedKey(T){let S=this.getRelatedKeys(T);if(S){if(S.size>1)this.warn?.(`${S.size} related keys were found for key "${T}": (${[...S].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let $;for(let f of S){$=f;break}return $}}replaceRelations(T,S,$){let f=!Array.isArray(S),M=f?Object.keys(S):S;if($?.reckless)this.replaceRelationsUnsafely(T,M);else this.replaceRelationsSafely(T,M);if(f)for(let J of M){let F=this.makeContentKey(T,J),W=S[J];this.setContent(F,W)}return this}getContent(T,S){let $=this.makeContentKey(T,S);return this.getContentInternal($)}getRelationEntries(T){let S=T[this.a],$=T[this.b];if(S!==void 0&&$===void 0){let f=this.getRelatedKeys(S);if(f)return[...f].map((M)=>{return[M,this.getContent(S,M)]})}if(S===void 0&&$!==void 0){let f=this.getRelatedKeys($);if(f)return[...f].map((M)=>{return[M,this.getContent(M,$)]})}return[]}has(T,S){if(S)return this.getRelatedKeys(T)?.has(S)??!1;return this.relations.has(T)}}function nT(T){return"epoch"in T.transactionMeta}function XT(T){return"phase"in T.transactionMeta}var BA=(T)=>{let S=I(T);if(!XT(S)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",S.transactionMeta.update.key,"Aborting transaction"),S.parent.child=null};var B4=(T)=>T[0].toUpperCase()+T.slice(1);function pS(T){return T.type.split("_").map(B4).join(" ")}class DS extends Error{constructor(...T){let S=T[0],$=T.length===2?T[1]:T[2];if(T.length===2)super(`${pS(S)} ${e(S.key)} not found in store "${$.config.name}".`);else{let f=T[1];super(`${pS(S)} "${S.key}" member ${e(f)} not found in store "${$.config.name}".`)}}}function m$(T,S,$){return(...f)=>{let M=TT(T,$);if(M)return M.run(f,S);throw new DS(T,$)}}var rJ=(T)=>(S)=>T instanceof Function?T(S):T;var h$=(T,S)=>{if(S.valueMap.has(T.key))return S.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),LA(T,S);if(T.type==="selector"||T.type==="readonly_selector")return S.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();let $=T.default instanceof Function?T.default():T.default;return S.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",$),T.default instanceof Function?T.default():T.default};var NA=(T,S)=>{if(T.operation.open){let $=performance.now();return T.logger.info("\u2757",S.type,S.key,`deferring setState at T-${$} until setState for "${T.operation.token.key}" is done`),$}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:S},T.logger.info("\u2B55",S.type,S.key,`operation start in store "${T.config.name}"${!XT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},CA=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},xA=(T,S)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",S,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(S)},Zf=(T,S)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",S,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(S)};var jA=(T,S,$)=>{switch(T.type){case"mutable_atom":$.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",S.newValue,") subscribers:",T.subject.subscribers);break;default:$.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",S.oldValue,"->",S.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(S)};var lW=(T,S)=>{let $=I(S),f=$.selectorAtoms.getRelatedKeys(T.key);if($.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if($.operation.open)$.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...$.operation.done].join(", ")} ] already done`);for(let M of f){if(xA($,M))continue;IA(M,$),Zf($,M)}}};function L4(T,S){if(ZA(S.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var bA=(T,S,$)=>{let{key:f}=T,M=I($);if(!XT(M)||M.transactionMeta.phase!=="building"){$.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!L4(f,S))return;let F={type:"atom_update",key:f,...S};if(T.family)F.family=T.family;M.transactionMeta.update.updates.push(F),$.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")};var qA=(T,S,$)=>{let f=h$(T,$),M=f;if(T.type==="mutable_atom"&&XT($)){let{parent:F}=$;M=qM(T,F,$)}if(M=rJ(S)(M),$.logger.info("\uD83D\uDCDD","atom",T.key,"set to",M),M=qS(T.key,M,T.subject,$),mA(T.key,$))hA(T.key,$);Zf($,T.key),lW(T,$);let J={oldValue:f,newValue:M};if(nT($))jA(T,J,$);else if($.parent){if($.on.transactionApplying.state===null)bA(T,J,$);else if(T.key.startsWith("*")){let F=T.key.slice(1),W=$.atoms.get(F),A=$.valueMap.get(F);if(W.type==="mutable_atom"&&XT($)){let{parent:X}=$;A=qM(W,X,$)}if(A.do(J.newValue)===null)lW(W,$)}}};var aJ=(T,S,$)=>{switch(T.type){case"atom":case"mutable_atom":qA(T,S,$);break;case"selector":T.set(S);break}};function eJ(T,S){if(S.family){let $=T.families.get(S.family.key);if($)return $}}function ZT(T,...S){let $,f,M,J;if(S.length===2){if($=S[0],J=S[1],f=eJ(T,$)??null,f)M=$.family?iT($.family.subKey):null,$=YT(T,f,M)}else f=S[0],M=S[1],J=S[2],$=YT(T,f,M);if("counterfeit"in $){let A=T.disposalTraces.buffer.find((k)=>k?.key===$.key);T.logger.error("\u274C",$.type,$.key,`could not be set because it was not found in the store "${T.config.name}".`,A?`This state was previously disposed:
4
+ ${A.trace}`:"No previous disposal trace was found.");return}let F=NA(T,$);if(F){let A=T.on.operationClose.subscribe(`waiting to set "${$.key}" at T-${F}`,()=>{A(),T.logger.info("\uD83D\uDFE2",$.type,$.key,`resuming deferred setState from T-${F}`),ZT(T,$,J)});return}let W=TT($,T);aJ(W,J,T),CA(T)}function sJ(T,S,$){let{key:f,newValue:M,oldValue:J}=S,F=T==="newValue"?M:J,W={key:f,type:"atom"};if(S.family)Object.assign(W,{family:S.family});ZT($,W,F)}function vA(T,S){let $=new fT,f={type:"molecule_family",key:S.key,dependsOn:S.dependsOn??"all"},M={...f,subject:$,new:S.new};return T.moleculeFamilies.set(S.key,M),f}function iS(T,S,$){let f=R$($,S,T.key);T.tokens.set(f.key,f);let M=XT($)&&$.transactionMeta.phase==="building",J=$.moleculeInProgress===T.key;if(!M&&!J)T.subject.next({type:"state_creation",token:f});return f}function TF(T){return{store:T}}function kT(T,...S){let $,f,M;if(S.length===1){if($=S[0],$.type!=="molecule"){if(f=eJ(T,$)??null,f)M=$.family?iT($.family.subKey):null,$=YT(T,f,M)}}else{f=S[0],M=S[1];let J;if(f.type==="molecule_family")J=CT(T,f,M)??jf(f,M);else J=YT(T,f,M);$=J}if("counterfeit"in $&&"family"in $){f=$.type==="molecule"?TT($.family,T):T.families.get($.family.key);let J=$.type==="molecule"?$.key:$.family.subKey,F=T.disposalTraces.buffer.find((W)=>W?.key===$.key);switch(T.logger.error("\u274C",$.type,$.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,F?`This state was previously disposed:
5
+ ${F.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(f.key))return T.defaults.get($.family.key);let W=TT(f,T).default(J);return T.defaults.set(f.key,W),W}case"molecule_family":throw new DS(f,J,T)}}switch($.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return h$(TT($,T),T);case"molecule":return TT($,T).instance}}class If{key;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new fT;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(T,S,$){this.key=S;if(this.stringKey=e(S),$)this.family=$,this._dependsOn=$.dependsOn;if(T)for(let f of T)this.above.set(f.stringKey,f)}}function PA(T){return T[0].toUpperCase()+T.slice(1)}function G$(T,S,$,f,...M){let J=DA(T),F=I(T),W=e(f);F.moleculeInProgress=W;let A=Array.isArray(S)?S:[S],k=A.map((D)=>{if(D instanceof If)return D;let B=e(D.key),L=T.molecules.get(B);if(!L)throw new Error(`Molecule ${B} not found in store "${T.config.name}"`);return L}),X=new If(k,f,$);F.molecules.set(W,X);for(let D of k)D.below.set(X.stringKey,X);let w={get:(...D)=>kT(I(J),...D),set:(...D)=>{ZT(I(J),...D)},seek:(D,B)=>CT(I(J),D,B),json:(D)=>PT(I(J),D),run:(D,B=xf())=>m$(D,B,I(T)),make:(D,B,L,...Z)=>G$(I(J),D,B,L,...Z),dispose:(D)=>{RS(I(J),D)},env:()=>TF(I(J)),bond:(D,B)=>{if(D.type==="join"){let{as:L}=B,Z=mM(D,J);Z.molecules.set(W,X),X.joins.set(D.key,Z);let j=K.subject.subscribe(`join:${D.key}-${W}`,(R)=>{if(R.type==="molecule_disposal"){if(e(R.token.key)===W)j(),Z.molecules.delete(W)}});if(L===null)return;let E=D.a===L?D.b:D.a,_=nA(D,f),Q=_[`${E}KeysOf${PA(L)}`],b=_[`${E}EntriesOf${PA(L)}`],h={relatedKeys:Q};if(b)h=Object.assign(h,{relatedEntries:b});return h}return iS(X,TT(D,J),I(J))},claim:(D,B)=>{let{exclusive:L}=B,Z=I(T).molecules.get(e(D.key));if(Z)if(L){for(let j of Z.above.values())j.below.delete(Z.stringKey);Z.above.clear(),Z.above.set(X.stringKey,X),X.below.set(Z.stringKey,Z)}else Z.above.set(X.stringKey,X),X.below.set(Z.stringKey,Z)},spawn:(D,B,...L)=>G$(I(T),[X],TT(D,T),B,...L)},K=TT($,T),G=K.new;X.instance=new G(w,f,...M);let z={type:"molecule",key:f,family:$},U={type:"molecule_creation",subType:"classic",token:z,family:$,context:A,params:M};if(nT(F))K.subject.next(U);else if(XT(F)&&F.on.transactionApplying.state===null)F.transactionMeta.update.updates.push(U);return F.moleculeInProgress=null,z}function rW(T,S,$){switch(S){case"newValue":{cA(T,$);break}case"oldValue":{RS($,T.token);break}}}function aW(T,S,$){switch(S){case"newValue":{RS($,T.token);break}case"oldValue":{cA(T,$),$.valueMap.set(T.token.key,T.value);break}}}function cA(T,S){let{family:$}=T.token;if($){let f=S.families.get($.key);if(f)YT(S,f,iT($.subKey))}}function eW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":G$($,T.context,T.family,T.token.key,...T.params);break;case"modern":tW($,T.provenance,T.key);break}break;case"oldValue":switch(T.subType){case"classic":RS($,T.token);break;case"modern":bM($,T.key);break}break}}function sW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":RS($,T.token);break;case"modern":bM($,T.key);break}break;case"oldValue":switch(T.subType){case"classic":{let f=G$($,T.context,T.family,T.token.key);for(let[M,J]of T.values){let F=`${M}(${e(f.key)})`,W=TT(f,$),A=W.tokens.has(F),k=$.families.get(M);if(k&&!A)iS(W,k,$);$.valueMap.set(F,J)}}break;case"modern":{tW($,T.provenance,T.key);for(let[f,M]of T.values){let J=$.families.get(f);if(J){YT($,J,T.key);let F=`${f}(${e(T.key)})`;$.valueMap.set(F,M)}}}}break}}function SF(T,S,$){let f=T==="newValue"?S.updates:[...S.updates].reverse();for(let M of f)switch(M.type){case"atom_update":case"selector_update":sJ(T,M,$);break;case"state_creation":rW(M,T,$);break;case"state_disposal":aW(M,T,$);break;case"molecule_creation":eW(M,T,$);break;case"molecule_disposal":sW(M,T,$);break;case"transaction_update":SF(T,M,$);break}}function gA(T,S,$){if(nT($)&&T)$.transactionMeta.epoch.set(T,S)}function oA(T,S,$){if(!nT($))return;let M=$.transactionMeta.actionContinuities.getRelatedKey(T);if(M!==void 0)$.transactionMeta.epoch.set(M,S)}var tA=(T,S)=>{let $=I(S),{parent:f}=$;if(f===null||!XT($)||$.transactionMeta?.phase!=="building"){S.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}$.transactionMeta.phase="applying",$.transactionMeta.update.output=T,f.child=null,f.on.transactionApplying.next($.transactionMeta);let{updates:M}=$.transactionMeta.update;if(S.logger.info("\uD83D\uDEC4","transaction",$.transactionMeta.update.key,`Applying transaction with ${M.length} updates:`,M),SF("newValue",$.transactionMeta.update,f),nT(f))oA($.transactionMeta.update.key,$.transactionMeta.update.epoch,f),TT({key:$.transactionMeta.update.key,type:"transaction"},S)?.subject.next($.transactionMeta.update),S.logger.info("\uD83D\uDEEC","transaction",$.transactionMeta.update.key,"Finished applying transaction.");else if(XT(f))f.transactionMeta.update.updates.push($.transactionMeta.update);f.on.transactionApplying.next(null)};function pA(T,S,$){if(!nT($))return;let{epoch:M,actionContinuities:J}=$.transactionMeta;if(J.set(T,S),!M.has(T))M.set(T,-1)}class mS extends Map{source;deleted=new Set;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,S){return this.deleted.delete(T),super.set(T,S)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var iA=(T,S,$,f)=>{let M=I($),J={parent:M,child:null,on:M.on,loggers:M.loggers,logger:M.logger,config:M.config,atoms:new mS(M.atoms),atomsThatAreDefault:new Set(M.atomsThatAreDefault),families:new mS(M.families),operation:{open:!1},readonlySelectors:new mS(M.readonlySelectors),timelines:new mS(M.timelines),timelineTopics:new BS(M.timelineTopics.toJSON()),trackers:new Map,transactions:new mS(M.transactions),selectorAtoms:new BS(M.selectorAtoms.toJSON()),selectorGraph:new BS(M.selectorGraph.toJSON(),{makeContentKey:(...k)=>k.sort().join(":")}),selectors:new mS(M.selectors),valueMap:new mS(M.valueMap),defaults:M.defaults,disposalTraces:$.disposalTraces.copy(),molecules:new mS(M.molecules),moleculeFamilies:new mS(M.moleculeFamilies),moleculeInProgress:M.moleculeInProgress,miscResources:new mS(M.miscResources)},F=dA(T,$),W={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:F===void 0?Number.NaN:F+1,updates:[],params:S,output:void 0},toolkit:{get:(...k)=>kT(A,...k),set:(...k)=>{ZT(A,...k)},run:(k,X=xf())=>m$(k,X,A),find:(k,X)=>YT(A,k,X),seek:(k,X)=>CT(A,k,X),json:(k)=>PT(A,k),make:(k,X,w,...K)=>G$(A,k,X,w,...K),dispose:(...k)=>{RS(A,...k)},env:()=>TF(A)}},A=Object.assign(J,{transactionMeta:W});return M.child=A,$.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",S),A};function uW(T,S){let $={key:T.key,type:"transaction",run:(J,F)=>{let W=iA(T.key,J,S,F);try{let A=I(S),{toolkit:k}=W.transactionMeta,X=T.do(k,...J);return tA(X,A),X}catch(A){throw BA(f),S.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",A),A}},install:(J)=>uW(T,J),subject:new fT},f=I(S);f.transactions.set($.key,$);let M=XS($);return S.on.transactionCreation.next(M),M}function dA(T,S){let $=nT(S),f=$?S.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return $&&f!==void 0?S.transactionMeta.epoch.get(f):void 0}class $F{_buffer;_index=0;constructor(T){let S;if(typeof T==="number")S=T;else S=T.length;this._buffer=Array.from({length:S})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new $F([...this._buffer]);return T._index=this._index,T}}class uA{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new BS({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new BS({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new BS({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new BS({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new $F(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new fT,atomDisposal:new fT,selectorCreation:new fT,selectorDisposal:new fT,timelineCreation:new fT,transactionCreation:new fT,transactionApplying:new oW(null),operationClose:new fT,moleculeCreationStart:new fT,moleculeCreationDone:new fT,moleculeDisposal:new fT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new dW("warn",(T,S,$)=>!$.includes("\uD83D\uDD0D"))];logger={error:(...T)=>{for(let S of this.loggers)S.error(...T)},info:(...T)=>{for(let S of this.loggers)S.info(...T)},warn:(...T)=>{for(let S of this.loggers)S.warn(...T)}};constructor(T,S=null){if(this.config={...S?.config,...T},S!==null){if(this.valueMap=new Map(S?.valueMap),this.operation={...S?.operation},nT(S))this.transactionMeta={epoch:new Map(S?.transactionMeta.epoch),actionContinuities:new BS(S?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of S.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let $=new Set;for(let[,f]of S.atoms){if($.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let M=PT(S,f),J=z$(f);$.add(M.key),$.add(J.key)}}for(let[,f]of S.readonlySelectors)f.install(this);for(let[,f]of S.selectors){if($.has(f.key))continue;f.install(this)}for(let[,f]of S.transactions)f.install(this);for(let[,f]of S.timelines)f.install(this)}}}var WT={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new uA({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function TT(T,S){let $,f=S;while(f!==null){switch(T.type){case"atom":case"mutable_atom":$=f.atoms.get(T.key);break;case"selector":$=f.selectors.get(T.key);break;case"readonly_selector":$=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":$=f.families.get(T.key);break;case"timeline":$=f.timelines.get(T.key);break;case"transaction":$=f.transactions.get(T.key);break;case"molecule":$=f.molecules.get(e(T.key));break;case"molecule_family":$=f.moleculeFamilies.get(T.key);break}if($)return $;f=f.child}throw new DS(T,S)}function fF(T,S){let $;$=TT(T,S);let{family:f}=T;for(let F of $.joins.values())F.relations.delete($.key),F.molecules.delete($.stringKey);let M=[];for(let F of $.above.values())M.push(XS(F));let J=[];for(let F of $.tokens.values()){let W=F.family;J.push([W.key,S.valueMap.get(F.key)])}if(f){let F=TT(f,S),W={type:"molecule_disposal",subType:"classic",token:T,family:f,context:M,values:J};if(T.family)W.family=T.family;for(let k of $.tokens.values())RS(S,k);for(let k of $.below.values())if(k.dependsOn==="all")fF(k,S);else if(k.above.delete($.stringKey),k.above.size===0)fF(k,S);if($.below.clear(),XT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push(W);else F.subject.next(W);S.molecules.delete($.stringKey)}for(let F of $.above.values())F.below.delete($.stringKey)}function R$(T,S,$){let f=T.families.get(S.key);if(f===void 0)throw new DS(S,T);let M=f($),J=I(T);if(M.family&&J.moleculeInProgress===null){if(nT(J))switch(M.type){case"atom":case"mutable_atom":T.on.atomCreation.next(M);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(M);break}else if(XT(J)&&J.on.transactionApplying.state===null)J.transactionMeta.update.updates.push({type:"state_creation",token:M})}return M}function CT(T,S,$){let f=e($),M=`${S.key}(${f})`,J=I(T),F;switch(S.type){case"atom_family":case"mutable_atom_family":F=J.atoms.get(M);break;case"selector_family":F=J.selectors.get(M);break;case"readonly_selector_family":F=J.readonlySelectors.get(M);break;case"molecule_family":F=J.molecules.get(e($))}if(F)return XS(F);return F}function YT(T,S,$){let f=CT(T,S,$);if(f)return f;let M=T.molecules.get(e($));if(M)return iS(M,S,T);if(T.config.lifespan==="immortal"){let J=jf(S,$);return T.logger.error("\u274C",J.type,J.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),J}return f=R$(T,S,$),f}function RS(T,...S){let $,f;if(S.length===1)$=S[0],f=$.key;else{let J=S[0],F=S[1];$=J.type==="molecule_family"?CT(T,J,F)??jf(J,F):YT(T,J,F)}try{TT($,T)}catch(J){let F=T.disposalTraces.buffer.find((W)=>W?.key===$.key);T.logger.error("\u274C",$.type,$.key,`could not be disposed because it was not found in the store "${T.config.name}".`,F?`
6
+ This state was most recently disposed
7
+ ${F.trace}`:"No previous disposal trace was found.");return}switch($.type){case"atom":case"mutable_atom":T0($,T);break;case"selector":case"readonly_selector":lA($,T);break;case"molecule":fF($,T);break}let{stack:M}=new Error;if(M){let J=M?.split(`
8
+ `)?.slice(3)?.join(`
9
+ `);T.disposalTraces.add({key:$.key,trace:J})}}var MF=(T,S)=>I(S).atoms.has(T),N4=(T,S)=>I(S).selectors.has(T),C4=(T,S)=>I(S).readonlySelectors.has(T),rA=(T,S)=>MF(T,S)||N4(T,S)||C4(T,S);var JF=(T,S)=>{return I(S).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([f,{source:M}])=>M!==T).map(([f,{source:M}])=>M).filter((f)=>rA(f,S))};var S0=(T,S,$)=>{let f=[],M=JF(T,$);while(M.length>0){let J=M.shift();if(S.has(J))continue;if(S.add(J),!MF(J,$))M.push(...JF(J,$));else if(!f.includes(J))f.push(J)}return f},aA=(T,S)=>{let $=T.key,f=JF($,S),M=new Set;return f.flatMap((J)=>MF(J,S)?J:S0(J,M,S))};var eA=(T,S,$,f)=>{let M=I(f);if(S.type==="atom"||S.type==="mutable_atom")M.selectorAtoms.set({selectorKey:T,atomKey:S.key}),f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${S.key}"`);else{let J=S0(S.key,$,f);f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${J.map((F)=>`"${F}"`).join(", ")} ]`);for(let F of J)M.selectorAtoms=M.selectorAtoms.set({selectorKey:T,atomKey:F})}$.add(S.key)};var FF=(T,S,$)=>({get:(...f)=>{let M=I($),J;if(f.length===2){let[A,k]=f;switch(A.type){case"molecule_family":return kT($,A,k);default:if($.config.lifespan==="ephemeral")J=YT($,A,k);else{let X=CT($,A,k);if(X)J=X;else throw new DS(A,k,$)}}}else[J]=f;if(J.type==="molecule")return kT($,J);let F=TT(J,$),W=h$(F,$);return $.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${J.key}" =`,W,")"),M.selectorGraph.set({upstreamSelectorKey:J.key,downstreamSelectorKey:T},{source:J.key}),eA(T,J,S,$),W},set:(...f)=>{let M,J;if(f.length===2)M=f[0],J=f[1];else{let A=f[0],k=f[1];J=f[2];let X=$.config.lifespan==="ephemeral"?YT($,A,k):CT($,A,k);if(!X)throw new DS(A,k,$);M=X}let F=I($),W=TT(M,F);aJ(W,J,F)},find:(f,M)=>YT($,f,M),seek:(f,M)=>CT($,f,M),json:(f)=>PT($,f)});var xM=(T,S,$)=>{let f=I(T),M=new fT,J=new Set,{get:F,find:W,seek:A,json:k}=FF(S.key,J,f),X=()=>{let z=S.get({get:F,find:W,seek:A,json:k});return qS(S.key,z,M,I(T)),J.clear(),z},w={...S,subject:M,install:(z)=>xM(z,S,$),get:X,type:"readonly_selector",...$&&{family:$}};f.readonlySelectors.set(S.key,w);let K=X();T.logger.info("\u2728",w.type,w.key,"=",K);let G={key:S.key,type:"readonly_selector"};if($)G.family=$;return G};var hM=(T,S,$)=>{let f=I(T),M=new fT,J=new Set,F=FF(S.key,J,f),{find:W,get:A,seek:k,json:X}=F,w={find:W,get:A,seek:k,json:X},K=(B=S.get,L=I(T))=>{let Z=B(w);return qS(S.key,Z,M,L),J.clear(),Z},z={...S,subject:M,install:(B)=>hM(B,S,$),get:K,set:(B)=>{let L=I(T),Z=K(S.get,L),j=rJ(B)(Z);if(T.logger.info("\uD83D\uDCDD","selector",S.key,"set (",Z,"->",j,")"),qS(S.key,j,M,L),Zf(L,S.key),nT(L))M.next({newValue:j,oldValue:Z});S.set(F,j)},type:"selector",...$&&{family:$}};f.selectors.set(S.key,z);let U=K();T.logger.info("\u2728",z.type,z.key,"=",U);let D={key:S.key,type:"selector"};if($)D.family=$;return D};function tS(T,S){if("set"in S){let M=hM(T,S,void 0);return T.on.selectorCreation.next(M),M}let f=xM(T,S,void 0);return T.on.selectorCreation.next(f),f}function lA(T,S){let $=I(S),{key:f}=T,M=TT(T,$);if(!M.family)S.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{let J=$.molecules.get(M.family.subKey);if(J)J.tokens.delete(f);switch(T.type){case"selector":$.selectors.delete(f),TT({key:M.family.key,type:"selector_family"},S).subject.next({type:"state_disposal",token:T});break;case"readonly_selector":$.readonlySelectors.delete(f),TT({key:M.family.key,type:"readonly_selector_family"},S).subject.next({type:"state_disposal",token:T});break}if($.valueMap.delete(f),$.selectorAtoms.delete(f),$.selectorGraph.delete(f),S.logger.info("\uD83D\uDD25",T.type,f,"deleted"),XT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.selectorDisposal.next(T)}}function IM(T,S,$){let f={key:S.key,type:"selector_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","selector_family",S.key,`Overwriting an existing ${pS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new fT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},w=`${S.key}(${k})`,K=I(T),G=hM(K,{key:w,get:S.get(A),set:S.set(A)},X);return J.next({type:"state_creation",token:G}),G},f,{internalRoles:$,subject:J,install:(A)=>IM(A,S),default:(A)=>{return S.get(A)({get:(...X)=>kT(T,...X),find:(X,w)=>YT(T,X,w),seek:(X,w)=>CT(T,X,w),json:(X)=>PT(T,X)})}});return T.families.set(S.key,W),f}function sA(T,S,$=WT.STORE){let f=IM($,{key:`${T.key}:JSON`,get:(J)=>({seek:F,get:W})=>{let A=F(T,J);if(A)return S.toJson(W(A));let k=e(J),X=$.molecules.get(k);if(X){let K=iS(X,T,$);return S.toJson(W(K))}if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${k}"`);let w=R$($,T,J);return S.toJson(W(w))},set:(J)=>({seek:F,set:W},A)=>{let k=F(T,J);if(k)W(k,S.fromJson(A));else{let X=e(J),w=$.molecules.get(X);if(w){let K=iS(w,T,$);W(K,S.fromJson(A))}else{if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${X}"`);W(R$($,T,J),S.fromJson(A))}}}},["mutable","json"]);return TT(T,$).subject.subscribe(`store=${$.config.name}::json-selector-family`,(J)=>{if(J.token.family)CT($,f,iT(J.token.family.subKey))}),f}var iT=(T)=>JSON.parse(T),e=(T)=>JSON.stringify(T),uG=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var Tk=(T,S)=>{let $=I(S);if($.operation.open)return $.operation.prev.get(T.key);return $.valueMap.get(T.key)};var M0=(T,S)=>{let $=I(S);return aA(T,S).map((M)=>{let J=$.atoms.get(M);if(J===void 0)throw new Error(`Atom "${M}", a dependency of selector "${T.key}", not found in store "${S.config.name}".`);return J.subject.subscribe(`${T.type}:${T.key}`,(F)=>{S.logger.info("\uD83D\uDCE2",T.type,T.key,"root",M,"went",F.oldValue,"->",F.newValue);let W=Tk(T,$),A=h$(T,$);S.logger.info("\u2728",T.type,T.key,"went",W,"->",A),T.subject.next({newValue:A,oldValue:W})})})};function wS(T,S,$,f){function M(w){if(f.operation.open){let K=f.on.operationClose.subscribe(`state subscription ${$}`,()=>{K(),S(w)})}else S(w)}let J=TT(T,f);f.logger.info("\uD83D\uDC40",J.type,J.key,`Adding subscription "${$}"`);let F=J.type==="selector"||J.type==="readonly_selector",W=null,A=M;if(F)W=M0(J,f),A=(w)=>{if(W)W.length=0,W.push(...M0(J,f));M(w)};let k=J.subject.subscribe($,A);return()=>{if(f.logger.info("\uD83D\uDE48",J.type,J.key,`Removing subscription "${$}"`),k(),W)for(let w of W)w()}}var $0=(T,S,$,f)=>{let M=TT(T,f);f.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${$}"`);let J=M.subject.subscribe($,S);return()=>{f.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${$}" from timeline`),J()}};var f0=(T,S,$,f)=>{let M=TT(T,f);f.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${$}"`);let J=M.subject.subscribe($,S);return()=>{f.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${$}"`),J()}};class v${Update;initializeState(T,S){let $=`*${T.key}`;S.atoms.delete($),S.valueMap.delete($);let f=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,M=ES(S,{key:$,default:null},f);if(S.parent?.valueMap.has($)){let J=S.parent.valueMap.get($);S.valueMap.set($,J)}return M}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,S,$){let f=`tracker:${$.config.name}:${XT($)?$.transactionMeta.update.key:"main"}:${T.key}`,M=kT($,T);this.unsubscribeFromInnerValue=M.subscribe(f,(J)=>{ZT($,S,J)}),this.unsubscribeFromState=wS(T,(J)=>{if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(f,(F)=>{ZT($,S,F)})},f,$)}updateCore(T,S,$){let f=`tracker:${$.config.name}:${XT($)?$.transactionMeta.update.key:"main"}:${T.key}`;wS(S,({newValue:M,oldValue:J})=>{let F=$.timelineTopics.getRelatedKey(S.key);if(F){if($.timelines.get(F)?.timeTraveling){let k=$0({key:F,type:"timeline"},(X)=>{k(),ZT($,T,(w)=>{if(X==="redo"&&M)w.do(M);else if(X==="undo"&&J)w.undo(J);return w})},f,$);return}}let W=$.on.operationClose.subscribe(f,()=>{W();let A=kT($,T),k=M===null?-1:A.getUpdateNumber(M),X=k-A.cacheUpdateNumber;if(M&&X===1)ZT($,T,(w)=>(w.do(M),w));else $.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${A.cacheUpdateNumber+1}, but got ${k}`)})},f,$)}mutableState;latestUpdateState;dispose;constructor(T,S){this.mutableState=T;let $=I(S);this.latestUpdateState=this.initializeState(T,$),this.observeCore(T,this.latestUpdateState,$),this.updateCore(T,this.latestUpdateState,$),$.trackers.set(T.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),$.trackers.delete(T.key)}}}function vM(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let f=I(T),M=f.atoms.get(S.key);if(M&&M.type==="mutable_atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),XS(M);let J=new fT,F={...S,type:"mutable_atom",install:(k)=>{return k.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${k.config.name}"`),vM(k,S,$)},subject:J};if($)F.family=$;let W=S.default();f.atoms.set(F.key,F),WF(S.key,T),qS(S.key,W,J,f);let A=XS(F);if(S.effects){let k=0,X=[];for(let w of S.effects){let K=w({setSelf:(G)=>{ZT(T,A,G)},onSet:(G)=>wS(A,G,`effect[${k}]`,T)});if(K)X.push(K);++k}F.cleanup=()=>{for(let w of X)w()}}if(new v$(A,T),!$)EA(A,S,T);return A}class J0{Update;latestUpdateAtoms;mutableAtoms;constructor(T,S){let $=F$(S,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=TT($,S),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let M=iT(f.token.family.subKey);CT(S,this.latestUpdateAtoms,M),new v$(f.token,S)}}),this.latestUpdateAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let M=iT(f.token.family.subKey),J=CT(S,this.mutableAtoms,M);if(J)new v$(J,S)}})}}function CM(T,S,$){let f={key:S.key,type:"mutable_atom_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","mutable_atom_family",S.key,`Overwriting an existing ${pS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new fT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},w=`${S.key}(${k})`,K=I(T),G={key:w,default:()=>S.default(A),toJson:S.toJson,fromJson:S.fromJson,mutable:!0};if(S.effects)G.effects=S.effects(A);let z=vM(K,G,X);return J.next({type:"state_creation",token:z}),z},f,{subject:J,install:(A)=>CM(A,S),toJson:S.toJson,fromJson:S.fromJson,internalRoles:$});return T.families.set(S.key,W),sA(W,S,T),new J0(W,T),f}var F0=(T,S)=>{let $=I(S),f=`${T.key}:JSON`;return $.families.get(f)};var PT=(T,S)=>{if(S.family){let f=I(T),J={key:`${S.family.key}:JSON`,type:"selector_family"},F=TT(J,f),W=JSON.parse(S.family.subKey);return YT(T,F,W)}return{type:"selector",key:`${S.key}:JSON`}};var z$=(T)=>{let $={type:"atom",key:`*${T.key}`};if(T.family)$.family={key:`*${T.family.key}`,subKey:T.family.subKey};return $};function ZA(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function qM(T,S,$){let f=S.valueMap.get(T.key),M=$.valueMap.get(T.key);if(f===M){if(f===void 0)return typeof T.default==="function"?T.default():T.default;S.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let J=T.toJson(f),F=T.fromJson(J);return $.valueMap.set(T.key,F),new v$(T,S),F}return M}function qS(T,S,$,f){let M=f.valueMap.get(T);if(M instanceof NM)M.use(S);if(S instanceof Promise){let J=new NM(S);return f.valueMap.set(T,J),J.then((F)=>{qS(T,F,$,f),$.next({newValue:F,oldValue:J})}).catch((F)=>{f.logger.error("\uD83D\uDCA5","state",T,"rejected:",F)}),J}return f.valueMap.set(T,S),S}var LA=(T,S)=>{let $=S.valueMap.get(T.key);if(T.type==="mutable_atom"&&XT(S)){let{parent:f}=S;$=qM(T,f,S)}return $},IA=(T,S)=>{let $=S.valueMap.get(T);if($ instanceof NM){let f=$,M=S.selectors.get(T)??S.readonlySelectors.get(T);if(M)f.use(M.get());return}if(S.operation.open)S.operation.prev.set(T,$);S.valueMap.delete(T),S.logger.info("\uD83D\uDDD1","state",T,"evicted")};var mA=(T,S)=>{return I(S).atomsThatAreDefault.has(T)},WF=(T,S)=>{let $=I(S);$.atomsThatAreDefault=new Set($.atomsThatAreDefault).add(T)},hA=(T,S)=>{let $=I(S);$.atomsThatAreDefault=new Set(I(S).atomsThatAreDefault),$.atomsThatAreDefault.delete(T)};function ES(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let f=I(T),M=f.atoms.get(S.key);if(M&&M.type==="atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),XS(M);let J=new fT,F={...S,type:"atom",install:(k)=>{return k.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${k.config.name}"`),ES(k,S,$)},subject:J};if($)F.family=$;let W=S.default;if(S.default instanceof Function)W=S.default();f.atoms.set(F.key,F),WF(S.key,T),qS(S.key,W,J,f);let A=XS(F);if(S.effects){let k=0,X=[];for(let w of S.effects){let K=w({setSelf:(G)=>{ZT(T,A,G)},onSet:(G)=>wS(A,G,`effect[${k}]`,T)});if(K)X.push(K);++k}F.cleanup=()=>{for(let w of X)w()}}return A}function UA(T,S){if("mutable"in S){let M=vM(T,S,void 0);return T.on.atomCreation.next(M),M}let f=ES(T,S,void 0);return T.on.atomCreation.next(f),f}function T0(T,S){let $=I(S),{key:f}=T,M=TT(T,$);if(!M.family)S.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{M.cleanup?.();let J=S.valueMap.get(M.key);TT({key:M.family.key,type:"atom_family"},S).subject.next({type:"state_disposal",token:T,value:J});let W=$.molecules.get(M.family.subKey);if(W)W.tokens.delete(f);if($.atoms.delete(f),$.valueMap.delete(f),$.selectorAtoms.delete(f),$.atomsThatAreDefault.delete(f),S.timelineTopics.delete(f),T.type==="mutable_atom"){let A=z$(T);T0(A,S),S.trackers.delete(f)}if(S.logger.info("\uD83D\uDD25","atom",f,"deleted"),XT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.atomDisposal.next(T)}}class dT extends Set{mode="record";subject=new fT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,S=0){super(T);if(T instanceof dT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(S)this.cacheLimit=S,this.cache=new Array(S),this.subscribe("auto cache",($)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=$})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let S=new dT(T.members,T.cacheLimit);return S.cache=T.cache,S.cacheIdx=T.cacheIdx,S.cacheUpdateNumber=T.cacheUpdateNumber,S}add(T){let S=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${e(T)}`);return S}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let S=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${e(T)}`);return S}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new dT(this);let S=this.child._subscribe("transaction",($)=>{this.transactionUpdates?.push($)});try{if(T(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch($){throw console.error("Failed to apply transaction to SetRTX:",$),$}finally{S(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,S){return this.subject.subscribe(T,S)}subscribe(T,S){return this.subject.subscribe(T,($)=>{S(`${this.cacheUpdateNumber}=${$}`)})}emit(T){this.subject.next(T)}doStep(T){let S=T.indexOf(":"),$=T.substring(0,S),f=T.substring(S+1);switch($){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let M of f.split(";"))this.doStep(M)}}getUpdateNumber(T){let S=T.indexOf("=");return Number(T.substring(0,S))}do(T){let S=T.indexOf("="),$=Number(T.substring(0,S)),f=$-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let J=T.substring(S+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=$,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let J=this.cacheIdx+f;if(this.cache[J]===T)return null;this.mode="playback";let W=!1;while(!W){this.cacheIdx%=this.cacheLimit;let k=this.cache[this.cacheIdx];if(this.cacheIdx--,!k)return"OUT_OF_RANGE";this.undo(k),W=this.cacheIdx===J-1}let A=T.substring(S+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=$,null}return"OUT_OF_RANGE"}undoStep(T){let S=T.indexOf(":"),$=T.substring(0,S),f=T.substring(S+1);switch($){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let M=JSON.parse(f);for(let J of M)this.add(J);break}case"tx":{let M=f.split(";");for(let J=M.length-1;J>=0;J--)this.undoStep(M[J])}}}undo(T){let S=T.indexOf("=");if(Number(T.substring(0,S))===this.cacheUpdateNumber){this.mode="playback";let f=T.substring(S+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function IT(T){return T[0].toUpperCase()+T.slice(1)}class A0{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(T,S){let $=this.toolkit;this.toolkit=T,S(this),this.toolkit=$}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(T){let S=T.config.name,$=this.alternates.get(S);if($)return $;let f=new A0(this.options,this.defaultContent,T);return this.alternates.set(S,f),f.alternates=this.alternates,f}constructor(T,S,$=WT.STORE){this.store=$,this.options=T,this.defaultContent=S,this.alternates=new Map,this.alternates.set($.config.name,this),this.store.miscResources.set(`join:${T.key}`,this),this.retrieve=(E,_)=>{let Q=this.toolkit.seek(E,_);if(Q)return Q;let b=this.store.molecules.get(e(_));if(b){let h=TT(E,$);return iS(b,h,$)}if($.config.lifespan==="immortal")throw new DS(E,_,$);return R$($,E,_)},this.toolkit={get:(...E)=>kT($,...E),set:(...E)=>{ZT($,...E)},find:this.retrieve,seek:(...E)=>CT($,...E),json:(E)=>PT($,E),dispose:(...E)=>{RS($,...E)}};let f=T.between[0],M=T.between[1],J=CM($,{key:`${T.key}/relatedKeys`,default:()=>new dT,mutable:!0,fromJson:(E)=>dT.fromJSON(E),toJson:(E)=>E.toJSON()},["join","relations"]);this.core={findRelatedKeysState:J};let F=({get:E},_)=>E(this.retrieve(J,_)),W=(E,_,Q)=>{let{set:b}=E,h=this.retrieve(J,_),R=this.retrieve(J,Q);b(h,(g)=>g.add(Q)),b(R,(g)=>g.add(_))},A=(E,_,Q)=>{let{set:b}=E,h=this.retrieve(J,_),R=this.retrieve(J,Q),g,n;b(h,(p)=>{if(p.delete(Q),p.size===0)g=`"${_}"`;return p}),b(R,(p)=>{if(p.delete(_),p.size===0)n=`"${Q}"`;return p})},k=(E,_,Q)=>{let{get:b,set:h}=E,R=this.retrieve(J,_),g=b(R);for(let n of g){if(Q.includes(n))continue;let OT=this.retrieve(J,n);h(OT,(_T)=>{return _T.delete(_),_T})}h(R,(n)=>{return n.transaction((p)=>{p.clear();for(let OT of Q){let _T=F(E,OT),HS=_T.has(_);if(this.relations.cardinality==="1:n"){let y$=[];for(let N of _T){if(N===_)continue;let l=F(E,N);if(l.delete(OT),l.size===0)y$.push(N)}if(!HS&&_T.size>0)_T.clear();for(let N of y$){let l=[OT,N].sort(),RT=`"${l[0]}:${l[1]}"`;this.molecules.delete(RT)}}if(!HS)_T.add(_);p.add(OT)}return!0}),n})},X=(E,_,Q)=>{let{set:b}=E,h=this.retrieve(J,_);b(h,(R)=>{return R.transaction((g)=>{for(let n of Q)g.add(n);return!0}),R});for(let R of Q){let g=this.retrieve(J,R);b(g,(n)=>{return n.add(_),n})}return!0},w=(E,_,Q)=>{let b=F(E,_);return Q?b.has(Q):b.size>0},K={getRelatedKeys:(E)=>F(this.toolkit,E),addRelation:(E,_)=>{W(this.toolkit,E,_)},deleteRelation:(E,_)=>{A(this.toolkit,E,_)},replaceRelationsSafely:(E,_)=>{k(this.toolkit,E,_)},replaceRelationsUnsafely:(E,_)=>{X(this.toolkit,E,_)},has:(E,_)=>w(this.toolkit,E,_)},G,z,U;if(S){z=F$($,{key:`${T.key}/content`,default:S},["join","content"]),U=vA($,{key:`${T.key}/content-molecules`,new:class h{key;constructor(R,g){this.key=g}}});let E=({get:h},R)=>h(this.retrieve(z,R)),_=({set:h},R,g)=>{h(this.retrieve(z,R),g)},Q=(h,R)=>{let g=$.molecules.get(`"${R}"`);if(g)this.toolkit.dispose(g),this.molecules.delete(`"${R}"`)};G=Object.assign(K,{getContent:(h)=>{return E(this.toolkit,h)},setContent:(h,R)=>{_(this.toolkit,h,R)},deleteContent:(h)=>{Q(this.toolkit,h)}})}else G=K;let D=new BS(T,{externalStore:G,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...E)=>{let _=E.sort(),Q=`${_[0]}:${_[1]}`,[b,h]=_.map((R)=>this.molecules.get(e(R)));if($.config.lifespan==="immortal"&&b&&h){let R=I($),g=G$(R,[b,h],U,Q);this.molecules.set(`"${Q}"`,TT(g,R))}return Q}}),B=()=>O$($,{key:`${T.key}/singleRelatedKey`,get:(E)=>({get:_})=>{let Q=this.retrieve(J,E),b=_(Q);for(let h of b)return h;return null}},["join","keys"]),L=()=>{return O$($,{key:`${T.key}/multipleRelatedKeys`,get:(E)=>({get:_})=>{let Q=F0(J,$),b=this.retrieve(Q,E);return _(b).members}},["join","keys"])},Z=()=>O$($,{key:`${T.key}/singleRelatedEntry`,get:(E)=>({get:_})=>{let Q=this.retrieve(J,E),b=_(Q);for(let h of b){let R=D.isAType?.(E)?E:void 0,g=R===void 0?E:void 0;R??=h,g??=h;let n=D.makeContentKey(R,g),p=this.retrieve(z,n),OT=_(p);return[h,OT]}return null}},["join","entries"]),j=()=>O$($,{key:`${T.key}/multipleRelatedEntries`,get:(E)=>({get:_})=>{let Q=F0(J,$),b=this.retrieve(Q,E);return _(b).members.map((R)=>{let g=D.isAType?.(E)?E:void 0,n=g===void 0?E:void 0;g??=R,n??=R;let p=D.makeContentKey(g,n),OT=this.retrieve(z,p),_T=_(OT);return[R,_T]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let E=B(),_=`${f}KeyOf${IT(M)}`,Q=`${M}KeyOf${IT(f)}`,b={[_]:E,[Q]:E},h;if(S){let R=Z(),g=`${f}EntryOf${IT(M)}`,n=`${M}EntryOf${IT(f)}`,p={[g]:R,[n]:R};h=Object.assign(b,p)}else h=b;this.relations=D,this.states=h;break}case"1:n":{let E=B(),_=L(),Q=`${f}KeyOf${IT(M)}`,b=`${M}KeysOf${IT(f)}`,h={[Q]:E,[b]:_},R;if(S){let g=Z(),n=j(),p=`${f}EntryOf${IT(M)}`,OT=`${M}EntriesOf${IT(f)}`,_T={[p]:g,[OT]:n};R=Object.assign(h,_T)}else R=h;this.relations=D,this.states=R;break}default:{let E=L(),_=`${f}KeysOf${IT(M)}`,Q=`${M}KeysOf${IT(f)}`,b={[_]:E,[Q]:E},h;if(S){let R=j(),g=`${f}EntriesOf${IT(M)}`,n=`${M}EntriesOf${IT(f)}`,p={[g]:R,[n]:R};h=Object.assign(b,p)}else h=b;this.relations=D,this.states=h}}}}function AF(T,S,$=WT.STORE){return W0($).set(T.key,new A0(T,S,$)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function W0(T){if("joins"in T&&T.joins instanceof Map)return T.joins;let S=new Map;return T.joins=S,S}function mM(T,S){let $=W0(S),f=$.get(T.key);if(f===void 0){if(f=W0(WT.STORE).get(T.key)?.in(S),f===void 0)throw new Error(`Join "${T.key}" not found in store "${S.config.name}"`);$.set(T.key,f)}return f}function kF(T,S,$){let f=mM(T,$),M;switch(T.cardinality){case"1:1":{let J=`${T.a}KeyOf${IT(T.b)}`,F=`${T.b}KeyOf${IT(T.a)}`;M={get[J](){let A=f.states[J];return f.retrieve(A,S)},get[F](){let A=f.states[F];return f.retrieve(A,S)}};let W=`${T.a}EntryOf${IT(T.b)}`;if(W in f.states){let A=`${T.b}EntryOf${IT(T.a)}`;Object.assign(M,{get[W](){let k=f.states[W];return f.retrieve(k,S)},get[A](){let k=f.states[A];return f.retrieve(k,S)}})}break}case"1:n":{let J=`${T.a}KeyOf${IT(T.b)}`,F=`${T.b}KeysOf${IT(T.a)}`;M={get[J](){let A=f.states[J];return f.retrieve(A,S)},get[F](){let A=f.states[F];return f.retrieve(A,S)}};let W=`${T.a}EntryOf${IT(T.b)}`;if(W in f.states){let A=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(M,{get[W](){let k=f.states[W];return f.retrieve(k,S)},get[A](){let k=f.states[A];return f.retrieve(k,S)}})}break}case"n:n":{let J=`${T.a}KeysOf${IT(T.b)}`,F=`${T.b}KeysOf${IT(T.a)}`;M={get[J](){let A=f.states[J];return f.retrieve(A,S)},get[F](){let A=f.states[F];return f.retrieve(A,S)}};let W=`${T.a}EntriesOf${IT(T.b)}`;if(W in f.states){let A=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(M,{get[W](){let k=f.states[W];return f.retrieve(k,S)},get[A](){let k=f.states[A];return f.retrieve(k,S)}})}}}return M}function nA(T,S){return kF(T,S,WT.STORE)}function XF(T,S,$){let f=mM(T,$),M=I($);if(XT(M)){let{toolkit:J}=M.transactionMeta;f.transact(J,({relations:F})=>{S(F)})}else S(f.relations)}function x4(T,S){return mM(T,S).core.findRelatedKeysState}function Sk(T){return x4(T,WT.STORE)}class $k extends Map{set(T,S){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:S}),this;return super.set(T,S)}clear(){throw new Error("Cannot clear an InvariantMap")}}class wF{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new $k;static create(T,S){let $=new wF(T),{type:f,globals:M,actions:J,perspectives:F}=S($),W={type:f,key:T,globals:M,actions:J,perspectives:F};return wF.existing.set(T,W),W}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":{let[$,f]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:$,viewAtoms:f})}break}return this}}function p_(T){let{key:S,config:$}=T,f=wF.create(S,$),{actions:M}=f;for(let J of M)pA(S,J.key,WT.STORE);return gA(S,-1,WT.STORE),f}var r_=bf({key:"usersInRoomIndex",mutable:!0,default:()=>new dT,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),k0=bf({key:"roomIndex",default:()=>new dT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),j4={enteredAtEpoch:0},PM=AF({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},j4),a_=lJ({key:"usersInMyRoomView",get:(T)=>({find:S})=>{let $=Sk(PM);return[S($,T)]}});import{spawn as I4}from"child_process";class qf{emit;listeners;globalListeners;handleEvent(T,...S){for(let f of this.globalListeners)f(T,...S);let $=this.listeners.get(T);if($)for(let f of $)f(...S)}id="no_id_retrieved";constructor(T){this.emit=T;this.listeners=new Map,this.globalListeners=new Set}on(T,S){let $=this.listeners.get(T);if($)$.add(S);else this.listeners.set(T,new Set([S]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,S){let $=this.listeners.get(T);if($)if(S)$.delete(S);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class X0 extends qf{process;key;logger;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(T){if(Array.isArray(T)){let[S,...$]=T;switch(S){case"i":this.logger.info(this.id,this.key,...$);break;case"w":this.logger.warn(this.id,this.key,...$);break;case"e":this.logger.error(this.id,this.key,...$);break}}}constructor(T,S,$=console){super((f,...M)=>{let J=JSON.stringify([f,...M])+"\x03",F=(W)=>{if(W.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",F)};return this.process.stdin.once("error",F),this.process.stdin.write(J),this});this.process=T;this.key=S;this.logger=$;if(this.process=T,this.process.stdout.on("data",(f)=>{let M=f.toString();if(M==="ALIVE")return;this.unprocessedEvents.push(...M.split("\x03"));let J=this.unprocessedEvents.shift();this.incompleteData+=J??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let F=iT(this.incompleteData);this.handleEvent(...F);while(this.unprocessedEvents.length>0){let W=this.unprocessedEvents.shift();if(W){if(this.unprocessedEvents.length===0)this.incompleteData=W;F=iT(W),this.handleEvent(...F)}}this.incompleteData=""}catch(F){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(F)}}),this.process.stderr.on("data",(f)=>{let M=f.toString();this.unprocessedLogs.push(...M.split("\x03"));let J=this.unprocessedLogs.shift();this.incompleteLog+=J??"";try{let F=iT(this.incompleteLog);this.handleLog(F);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)F=iT(this.incompleteLog),this.handleLog(F)}catch(F){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(F),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class fk extends qf{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...S)=>{return this.out.next(S),this});this.id=T,this.in=new fT,this.out=new fT,this.in.subscribe("socket",(S)=>{this.handleEvent(...S)})}dispose(){for(let T of this.disposalFunctions)T()}}class w0 extends qf{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(e(T.map((S)=>S instanceof dT?`{ ${S.toJSON().members.join(" | ")} }`:S))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...S)=>{let $=JSON.stringify([T,...S]);return this.process.stdout.write($+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let S=T.toString();this.unprocessedEvents.push(...S.split("\x03"));let $=this.unprocessedEvents.shift();this.incompleteData+=$??"";try{let f=iT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let M=this.unprocessedEvents.shift();if(M){if(this.unprocessedEvents.length===0)this.incompleteData=M;let J=iT(M);this.handleEvent(...J)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let S=new fk(`user:${T}`);this.relays.set(T,S),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let $ of this.relayServices){let f=$(S);if(f)S.disposalFunctions.push(f)}this.on(`user:${T}`,(...$)=>{S.in.next($)}),S.out.subscribe("socket",($)=>{this.emit(...$)})}),this.on("user-leaves",(T)=>{let S=this.relays.get(T);if(this.off(`relay:${T}`),S)S.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var K0=s$({key:"roomArguments",default:["echo",["Hello World!"]]}),Mk=lJ({key:"room",get:(T)=>async({get:S,find:$})=>{let f=$(K0,T),M=S(f),[J,F]=M,W=await new Promise((A)=>{let k=I4(J,F,{env:process.env}),X=(w)=>{if(w.toString()==="ALIVE")k.stdout.off("data",X),A(k)};k.stdout.on("data",X)});return new X0(W,T)}});var VH=ZM({key:"createRoom",do:({get:T,set:S,find:$},f,M,J)=>{let F=J?[M,J]:[M],W=$(K0,f);S(W,F),S(k0,(X)=>X.add(f));let A=$(Mk,f);return T(A)}}),BH=ZM({key:"joinRoom",do:(T,S,$,f)=>{let M={enteredAtEpoch:f};return XF(PM,(J)=>{J.set({room:S,user:$},M)},T.env().store),M}}),LH=ZM({key:"leaveRoom",do:(T,S,$)=>{XF(PM,(f)=>{f.delete({room:S,user:$})},T.env().store)}}),NH=ZM({key:"destroyRoom",do:(T,S)=>{XF(PM,($)=>{$.delete({room:S})},T.env().store),T.set(k0,($)=>($.delete(S),$))}});function Y0(T,S){return S.map(($)=>{switch($.type){case"transaction_update":{let f=Y0(T,$.updates);return{...$,updates:f}}default:return $}}).filter(($)=>{switch($.type){case"atom_update":case"selector_update":return T.includes($.key);case"state_creation":return T.includes($.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var jH=s$({key:"redactor",default:{occlude:(T)=>T}}),mf=s$({key:"unacknowledgedUpdates",default:()=>[]});var Jk=s$({key:"sockets",default:null}),mH=bf({key:"socketsIndex",mutable:!0,default:()=>new dT,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),hH=bf({key:"usersIndex",mutable:!0,default:()=>new dT,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),y0=AF({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function Fk(T,S,$,f){let M=S.key;return function J(){let F=[];for(let A of S.globals){let k=A.type==="mutable_atom"?PT(T,A):A,X=kT(T,k);F.push(k,X)}for(let A of S.perspectives){let{viewAtoms:k,resourceAtoms:X}=A,w=YT(T,k,$),K=kT(T,w);T.logger.info("\uD83D\uDC41","atom",X.key,`${$} can see`,{viewAtoms:k,resourceAtoms:X,userView:K});for(let G of K){let z=G.type==="mutable_atom"?PT(T,G):G,U=kT(T,z);F.push(z,U)}}let W=nT(T)?T.transactionMeta.epoch.get(M)??null:null;f?.emit(`continuity-init:${M}`,W,F)}}function Wk(T,S,$){let f=S.key;return function M(J){T.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",J);let{key:F,id:W}=J,A=`tx-run:${F}:${W}`,k=`${A}:start`,X=`${A}:end`;performance.mark(k);try{m$({type:"transaction",key:F},W,T)(...J.params)}catch(K){if(K instanceof Error)T.logger.error("\u274C","continuity",f,`failed to run transaction ${F} from ${$} with update ${W}`,K.message)}performance.mark(X);let w=performance.measure(A,k,X);T?.logger.info("\uD83D\uDE80","transaction",F,W,$,w.duration)}}function Ak(T,S,$,f){let M=S.key;return function J(F){if(T.logger.info("\uD83D\uDC4D","continuity",M,`${$} acknowledged epoch ${F}`),f[0]?.epoch===F)ZT(T,mf,$,(A)=>{return A.shift(),T.logger.info("\uD83D\uDC4D","continuity",M,`${$} unacknowledged update queue now has`,A.length,"items"),A})}}function kk(T,S,$,f){let M=S.key,J=[];for(let F of S.actions){let W=f0(F,(A)=>{try{let k=S.globals.map((K)=>{if(K.type==="atom")return K.key;return z$(K).key}).concat(S.perspectives.flatMap((K)=>{let{viewAtoms:G}=K,z=YT(T,G,$);return kT(T,z).map((D)=>{return D.type==="mutable_atom"?"*"+D.key:D.key})})),X=Y0(k,A.updates),w={...A,updates:X};ZT(T,mf,$,(K)=>{if(w)K.push(w),K.sort((G,z)=>G.epoch-z.epoch),T.logger.info("\uD83D\uDC4D","continuity",M,`${$} unacknowledged update queue now has`,K.length,"items");return K}),f?.emit(`tx-new:${M}`,w)}catch(k){if(k instanceof Error)T.logger.error("\u274C","continuity",M,`${$} failed to send update from transaction ${F.key} to ${$}`,k.message)}},`sync-continuity:${M}:${$}`,T);J.push(W)}return J}function Xk(T,S,$,f){let M=S.key,J=[];for(let F of S.perspectives){let{viewAtoms:W}=F,A=YT(T,W,$),k=wS(A,({oldValue:X,newValue:w})=>{let K=X.map((D)=>D.key),G=w.map((D)=>D.key),z=X.filter((D)=>!G.includes(D.key)),U=w.filter((D)=>!K.includes(D.key)).flatMap((D)=>{let B=D.type==="mutable_atom"?PT(T,D):D,L=kT(T,B);return[B,L]});if(T.logger.info("\uD83D\uDC41","atom",F.resourceAtoms.key,`${$} has a new perspective`,{oldKeys:K,newKeys:G,revealed:U,concealed:z}),U.length>0)f?.emit(`reveal:${M}`,U);if(z.length>0)f?.emit(`conceal:${M}`,z)},`sync-continuity:${M}:${$}:perspective:${F.resourceAtoms.key}`,T);J.push(k)}return J}function YE({socket:T,store:S=WT.STORE}){return function $(f){let M=T,J=f.key,F=kF(y0,`socket::${M.id}`,S).userKeyOfSocket,W=kT(S,F);if(!W)return S.logger.error("\u274C","continuity",J,`Tried to create a synchronizer for a socket (${M.id}) that is not connected to a user.`),()=>{};let A=kF(y0,W,S).socketKeyOfUser,k=wS(A,({newValue:B})=>{if(S.logger.info("\uD83D\uDC4B","continuity",J,`seeing ${W} on new socket ${B}`),B===null){S.logger.warn("\u274C","continuity",J,`User (${W}) is not connected to a socket, waiting for them to reappear.`);return}let L=YT(S,Jk,B);M=kT(S,L);for(let j of X)M?.emit(`tx-new:${J}`,j)},`sync-continuity:${J}:${W}`,S),X=kT(S,mf,W),w=[],K=Xk(S,f,W,M),G=kk(S,f,W,M);w.push(...K,...G);let z=Fk(S,f,W,T);M.off(`get:${J}`,z),M.on(`get:${J}`,z);let U=Wk(S,f,W);M.off(`tx-run:${J}`,U),M.on(`tx-run:${J}`,U);let D=Ak(S,f,W,X);return M?.on(`ack:${J}`,D),()=>{for(let B of w)B();M?.off(`ack:${J}`,D),M?.off(`get:${J}`,z),M?.off(`tx-run:${J}`,U)}}}var Kk=Symbol("Let zodToJsonSchema decide on which parser to use"),wk={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Yk=(T)=>typeof T==="string"?{...wk,name:T}:{...wk,...T};var yk=(T)=>{let S=Yk(T),$=S.name!==void 0?[...S.basePath,S.definitionPath,S.name]:S.basePath;return{...S,currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(S.definitions).map(([f,M])=>[M._def,{def:M._def,path:[...S.basePath,S.definitionPath,f],jsonSchema:void 0}]))}};function O0(T,S,$,f){if(!f?.errorMessages)return;if($)T.errorMessage={...T.errorMessage,[S]:$}}function wT(T,S,$,f,M){T[S]=$,O0(T,S,f,M)}var yT;(function(T){T.assertEqual=(M)=>M;function S(M){}T.assertIs=S;function $(M){throw new Error}T.assertNever=$,T.arrayToEnum=(M)=>{let J={};for(let F of M)J[F]=F;return J},T.getValidEnumValues=(M)=>{let J=T.objectKeys(M).filter((W)=>typeof M[M[W]]!=="number"),F={};for(let W of J)F[W]=M[W];return T.objectValues(F)},T.objectValues=(M)=>{return T.objectKeys(M).map(function(J){return M[J]})},T.objectKeys=typeof Object.keys==="function"?(M)=>Object.keys(M):(M)=>{let J=[];for(let F in M)if(Object.prototype.hasOwnProperty.call(M,F))J.push(F);return J},T.find=(M,J)=>{for(let F of M)if(J(F))return F;return},T.isInteger=typeof Number.isInteger==="function"?(M)=>Number.isInteger(M):(M)=>typeof M==="number"&&isFinite(M)&&Math.floor(M)===M;function f(M,J=" | "){return M.map((F)=>typeof F==="string"?`'${F}'`:F).join(J)}T.joinValues=f,T.jsonStringifyReplacer=(M,J)=>{if(typeof J==="bigint")return J.toString();return J}})(yT||(yT={}));var G0;(function(T){T.mergeShapes=(S,$)=>{return{...S,...$}}})(G0||(G0={}));var o=yT.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P$=(T)=>{switch(typeof T){case"undefined":return o.undefined;case"string":return o.string;case"number":return isNaN(T)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":if(Array.isArray(T))return o.array;if(T===null)return o.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return o.promise;if(typeof Map!=="undefined"&&T instanceof Map)return o.map;if(typeof Set!=="undefined"&&T instanceof Set)return o.set;if(typeof Date!=="undefined"&&T instanceof Date)return o.date;return o.object;default:return o.unknown}},x=yT.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"]),b4=(T)=>{return JSON.stringify(T,null,2).replace(/"([^"]+)":/g,"$1:")};class LS extends Error{constructor(T){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let S=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,S);else this.__proto__=S;this.name="ZodError",this.issues=T}get errors(){return this.issues}format(T){let S=T||function(M){return M.message},$={_errors:[]},f=(M)=>{for(let J of M.issues)if(J.code==="invalid_union")J.unionErrors.map(f);else if(J.code==="invalid_return_type")f(J.returnTypeError);else if(J.code==="invalid_arguments")f(J.argumentsError);else if(J.path.length===0)$._errors.push(S(J));else{let F=$,W=0;while(W<J.path.length){let A=J.path[W];if(W!==J.path.length-1)F[A]=F[A]||{_errors:[]};else F[A]=F[A]||{_errors:[]},F[A]._errors.push(S(J));F=F[A],W++}}};return f(this),$}static assert(T){if(!(T instanceof LS))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,yT.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=(S)=>S.message){let S={},$=[];for(let f of this.issues)if(f.path.length>0)S[f.path[0]]=S[f.path[0]]||[],S[f.path[0]].push(T(f));else $.push(T(f));return{formErrors:$,fieldErrors:S}}get formErrors(){return this.flatten()}}LS.create=(T)=>{return new LS(T)};var nf=(T,S)=>{let $;switch(T.code){case x.invalid_type:if(T.received===o.undefined)$="Required";else $=`Expected ${T.expected}, received ${T.received}`;break;case x.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(T.expected,yT.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:$=`Unrecognized key(s) in object: ${yT.joinValues(T.keys,", ")}`;break;case x.invalid_union:$="Invalid input";break;case x.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${yT.joinValues(T.options)}`;break;case x.invalid_enum_value:$=`Invalid enum value. Expected ${yT.joinValues(T.options)}, received '${T.received}'`;break;case x.invalid_arguments:$="Invalid function arguments";break;case x.invalid_return_type:$="Invalid function return type";break;case x.invalid_date:$="Invalid date";break;case x.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if($=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)$=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)$=`Invalid input: must end with "${T.validation.endsWith}"`;else yT.assertNever(T.validation);else if(T.validation!=="regex")$=`Invalid ${T.validation}`;else $="Invalid";break;case x.too_small:if(T.type==="array")$=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")$=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")$=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")$=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else $="Invalid input";break;case x.too_big:if(T.type==="array")$=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")$=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")$=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")$=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")$=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else $="Invalid input";break;case x.custom:$="Invalid input";break;case x.invalid_intersection_types:$="Intersection results could not be merged";break;case x.not_multiple_of:$=`Number must be a multiple of ${T.multipleOf}`;break;case x.not_finite:$="Number must be finite";break;default:$=S.defaultError,yT.assertNever(T)}return{message:$}},Gk=nf;function Z4(T){Gk=T}function KF(){return Gk}var YF=(T)=>{let{data:S,path:$,errorMaps:f,issueData:M}=T,J=[...$,...M.path||[]],F={...M,path:J};if(M.message!==void 0)return{...M,path:J,message:M.message};let W="",A=f.filter((k)=>!!k).slice().reverse();for(let k of A)W=k(F,{data:S,defaultError:W}).message;return{...M,path:J,message:W}},q4=[];function P(T,S){let $=KF(),f=YF({issueData:S,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$,$===nf?void 0:nf].filter((M)=>!!M)});T.common.issues.push(f)}class KS{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,S){let $=[];for(let f of S){if(f.status==="aborted")return ST;if(f.status==="dirty")T.dirty();$.push(f.value)}return{status:T.value,value:$}}static async mergeObjectAsync(T,S){let $=[];for(let f of S){let M=await f.key,J=await f.value;$.push({key:M,value:J})}return KS.mergeObjectSync(T,$)}static mergeObjectSync(T,S){let $={};for(let f of S){let{key:M,value:J}=f;if(M.status==="aborted")return ST;if(J.status==="aborted")return ST;if(M.status==="dirty")T.dirty();if(J.status==="dirty")T.dirty();if(M.value!=="__proto__"&&(typeof J.value!=="undefined"||f.alwaysSet))$[M.value]=J.value}return{status:T.value,value:$}}}var ST=Object.freeze({status:"aborted"}),vf=(T)=>({status:"dirty",value:T}),GS=(T)=>({status:"valid",value:T}),z0=(T)=>T.status==="aborted",_0=(T)=>T.status==="dirty",gM=(T)=>T.status==="valid",oM=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function yF(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)}function zk(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$}var d;(function(T){T.errToObj=(S)=>typeof S==="string"?{message:S}:S||{},T.toString=(S)=>typeof S==="string"?S:S===null||S===void 0?void 0:S.message})(d||(d={}));var nM,cM;class rS{constructor(T,S,$,f){this._cachedPath=[],this.parent=T,this.data=S,this._path=$,this._key=f}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Ok=(T,S)=>{if(gM(S))return{success:!0,data:S.value};else{if(!T.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new LS(T.common.issues);return this._error=$,this._error}}}};function MT(T){if(!T)return{};let{errorMap:S,invalid_type_error:$,required_error:f,description:M}=T;if(S&&($||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(S)return{errorMap:S,description:M};return{errorMap:(F,W)=>{var A,k;let{message:X}=T;if(F.code==="invalid_enum_value")return{message:X!==null&&X!==void 0?X:W.defaultError};if(typeof W.data==="undefined")return{message:(A=X!==null&&X!==void 0?X:f)!==null&&A!==void 0?A:W.defaultError};if(F.code!=="invalid_type")return{message:W.defaultError};return{message:(k=X!==null&&X!==void 0?X:$)!==null&&k!==void 0?k:W.defaultError}},description:M}}class JT{constructor(T){this.spa=this.safeParseAsync,this._def=T,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)}get description(){return this._def.description}_getType(T){return P$(T.data)}_getOrReturnCtx(T,S){return S||{common:T.parent.common,data:T.data,parsedType:P$(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new KS,ctx:{common:T.parent.common,data:T.data,parsedType:P$(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){let S=this._parse(T);if(oM(S))throw new Error("Synchronous parse encountered promise.");return S}_parseAsync(T){let S=this._parse(T);return Promise.resolve(S)}parse(T,S){let $=this.safeParse(T,S);if($.success)return $.data;throw $.error}safeParse(T,S){var $;let f={common:{issues:[],async:($=S===null||S===void 0?void 0:S.async)!==null&&$!==void 0?$:!1,contextualErrorMap:S===null||S===void 0?void 0:S.errorMap},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:P$(T)},M=this._parseSync({data:T,path:f.path,parent:f});return Ok(f,M)}async parseAsync(T,S){let $=await this.safeParseAsync(T,S);if($.success)return $.data;throw $.error}async safeParseAsync(T,S){let $={common:{issues:[],contextualErrorMap:S===null||S===void 0?void 0:S.errorMap,async:!0},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:P$(T)},f=this._parse({data:T,path:$.path,parent:$}),M=await(oM(f)?f:Promise.resolve(f));return Ok($,M)}refine(T,S){let $=(f)=>{if(typeof S==="string"||typeof S==="undefined")return{message:S};else if(typeof S==="function")return S(f);else return S};return this._refinement((f,M)=>{let J=T(f),F=()=>M.addIssue({code:x.custom,...$(f)});if(typeof Promise!=="undefined"&&J instanceof Promise)return J.then((W)=>{if(!W)return F(),!1;else return!0});if(!J)return F(),!1;else return!0})}refinement(T,S){return this._refinement(($,f)=>{if(!T($))return f.addIssue(typeof S==="function"?S($,f):S),!1;else return!0})}_refinement(T){return new hS({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}optional(){return lS.create(this,this._def)}nullable(){return H$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return uS.create(this,this._def)}promise(){return ff.create(this,this._def)}or(T){return tf.create([this,T],this._def)}and(T){return pf.create(this,T,this._def)}transform(T){return new hS({...MT(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:T}})}default(T){let S=typeof T==="function"?T:()=>T;return new rf({...MT(this._def),innerType:this,defaultValue:S,typeName:C.ZodDefault})}brand(){return new RF({typeName:C.ZodBranded,type:this,...MT(this._def)})}catch(T){let S=typeof T==="function"?T:()=>T;return new af({...MT(this._def),innerType:this,catchValue:S,typeName:C.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return lM.create(this,T)}readonly(){return ef.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var m4=/^c[^\s-]{8,}$/i,h4=/^[0-9a-z]+$/,v4=/^[0-9A-HJKMNP-TV-Z]{26}$/,P4=/^[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,n4=/^[a-z0-9_-]{21}$/i,c4=/^[-+]?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)?)??$/,g4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,o4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",R0,t4=/^(?:(?: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])$/,p4=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,i4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_k="((\\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])))",d4=new RegExp(`^${_k}$`);function Hk(T){let S="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)S=`${S}\\.\\d{${T.precision}}`;else if(T.precision==null)S=`${S}(\\.\\d+)?`;return S}function u4(T){return new RegExp(`^${Hk(T)}$`)}function Ek(T){let S=`${_k}T${Hk(T)}`,$=[];if($.push(T.local?"Z?":"Z"),T.offset)$.push("([+-]\\d{2}:?\\d{2})");return S=`${S}(${$.join("|")})`,new RegExp(`^${S}$`)}function l4(T,S){if((S==="v4"||!S)&&t4.test(T))return!0;if((S==="v6"||!S)&&p4.test(T))return!0;return!1}class dS extends JT{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==o.string){let M=this._getOrReturnCtx(T);return P(M,{code:x.invalid_type,expected:o.string,received:M.parsedType}),ST}let $=new KS,f=void 0;for(let M of this._def.checks)if(M.kind==="min"){if(T.data.length<M.value)f=this._getOrReturnCtx(T,f),P(f,{code:x.too_small,minimum:M.value,type:"string",inclusive:!0,exact:!1,message:M.message}),$.dirty()}else if(M.kind==="max"){if(T.data.length>M.value)f=this._getOrReturnCtx(T,f),P(f,{code:x.too_big,maximum:M.value,type:"string",inclusive:!0,exact:!1,message:M.message}),$.dirty()}else if(M.kind==="length"){let J=T.data.length>M.value,F=T.data.length<M.value;if(J||F){if(f=this._getOrReturnCtx(T,f),J)P(f,{code:x.too_big,maximum:M.value,type:"string",inclusive:!0,exact:!0,message:M.message});else if(F)P(f,{code:x.too_small,minimum:M.value,type:"string",inclusive:!0,exact:!0,message:M.message});$.dirty()}}else if(M.kind==="email"){if(!g4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"email",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="emoji"){if(!R0)R0=new RegExp(o4,"u");if(!R0.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"emoji",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="uuid"){if(!P4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"uuid",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="nanoid"){if(!n4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"nanoid",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="cuid"){if(!m4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"cuid",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="cuid2"){if(!h4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"cuid2",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="ulid"){if(!v4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"ulid",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="url")try{new URL(T.data)}catch(J){f=this._getOrReturnCtx(T,f),P(f,{validation:"url",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="regex"){if(M.regex.lastIndex=0,!M.regex.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"regex",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="trim")T.data=T.data.trim();else if(M.kind==="includes"){if(!T.data.includes(M.value,M.position))f=this._getOrReturnCtx(T,f),P(f,{code:x.invalid_string,validation:{includes:M.value,position:M.position},message:M.message}),$.dirty()}else if(M.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(M.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(M.kind==="startsWith"){if(!T.data.startsWith(M.value))f=this._getOrReturnCtx(T,f),P(f,{code:x.invalid_string,validation:{startsWith:M.value},message:M.message}),$.dirty()}else if(M.kind==="endsWith"){if(!T.data.endsWith(M.value))f=this._getOrReturnCtx(T,f),P(f,{code:x.invalid_string,validation:{endsWith:M.value},message:M.message}),$.dirty()}else if(M.kind==="datetime"){if(!Ek(M).test(T.data))f=this._getOrReturnCtx(T,f),P(f,{code:x.invalid_string,validation:"datetime",message:M.message}),$.dirty()}else if(M.kind==="date"){if(!d4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{code:x.invalid_string,validation:"date",message:M.message}),$.dirty()}else if(M.kind==="time"){if(!u4(M).test(T.data))f=this._getOrReturnCtx(T,f),P(f,{code:x.invalid_string,validation:"time",message:M.message}),$.dirty()}else if(M.kind==="duration"){if(!c4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"duration",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="ip"){if(!l4(T.data,M.version))f=this._getOrReturnCtx(T,f),P(f,{validation:"ip",code:x.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="base64"){if(!i4.test(T.data))f=this._getOrReturnCtx(T,f),P(f,{validation:"base64",code:x.invalid_string,message:M.message}),$.dirty()}else yT.assertNever(M);return{status:$.value,value:T.data}}_regex(T,S,$){return this.refinement((f)=>T.test(f),{validation:S,code:x.invalid_string,...d.errToObj($)})}_addCheck(T){return new dS({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...d.errToObj(T)})}url(T){return this._addCheck({kind:"url",...d.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...d.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...d.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...d.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...d.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...d.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...d.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...d.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...d.errToObj(T)})}datetime(T){var S,$;if(typeof T==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:T});return this._addCheck({kind:"datetime",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,offset:(S=T===null||T===void 0?void 0:T.offset)!==null&&S!==void 0?S:!1,local:($=T===null||T===void 0?void 0:T.local)!==null&&$!==void 0?$:!1,...d.errToObj(T===null||T===void 0?void 0:T.message)})}date(T){return this._addCheck({kind:"date",message:T})}time(T){if(typeof T==="string")return this._addCheck({kind:"time",precision:null,message:T});return this._addCheck({kind:"time",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,...d.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...d.errToObj(T)})}regex(T,S){return this._addCheck({kind:"regex",regex:T,...d.errToObj(S)})}includes(T,S){return this._addCheck({kind:"includes",value:T,position:S===null||S===void 0?void 0:S.position,...d.errToObj(S===null||S===void 0?void 0:S.message)})}startsWith(T,S){return this._addCheck({kind:"startsWith",value:T,...d.errToObj(S)})}endsWith(T,S){return this._addCheck({kind:"endsWith",value:T,...d.errToObj(S)})}min(T,S){return this._addCheck({kind:"min",value:T,...d.errToObj(S)})}max(T,S){return this._addCheck({kind:"max",value:T,...d.errToObj(S)})}length(T,S){return this._addCheck({kind:"length",value:T,...d.errToObj(S)})}nonempty(T){return this.min(1,d.errToObj(T))}trim(){return new dS({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new dS({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new dS({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((T)=>T.kind==="datetime")}get isDate(){return!!this._def.checks.find((T)=>T.kind==="date")}get isTime(){return!!this._def.checks.find((T)=>T.kind==="time")}get isDuration(){return!!this._def.checks.find((T)=>T.kind==="duration")}get isEmail(){return!!this._def.checks.find((T)=>T.kind==="email")}get isURL(){return!!this._def.checks.find((T)=>T.kind==="url")}get isEmoji(){return!!this._def.checks.find((T)=>T.kind==="emoji")}get isUUID(){return!!this._def.checks.find((T)=>T.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((T)=>T.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((T)=>T.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((T)=>T.kind==="cuid2")}get isULID(){return!!this._def.checks.find((T)=>T.kind==="ulid")}get isIP(){return!!this._def.checks.find((T)=>T.kind==="ip")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get minLength(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxLength(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}dS.create=(T)=>{var S;return new dS({checks:[],typeName:C.ZodString,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...MT(T)})};function r4(T,S){let $=(T.toString().split(".")[1]||"").length,f=(S.toString().split(".")[1]||"").length,M=$>f?$:f,J=parseInt(T.toFixed(M).replace(".","")),F=parseInt(S.toFixed(M).replace(".",""));return J%F/Math.pow(10,M)}class c$ extends JT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(T){if(this._def.coerce)T.data=Number(T.data);if(this._getType(T)!==o.number){let M=this._getOrReturnCtx(T);return P(M,{code:x.invalid_type,expected:o.number,received:M.parsedType}),ST}let $=void 0,f=new KS;for(let M of this._def.checks)if(M.kind==="int"){if(!yT.isInteger(T.data))$=this._getOrReturnCtx(T,$),P($,{code:x.invalid_type,expected:"integer",received:"float",message:M.message}),f.dirty()}else if(M.kind==="min"){if(M.inclusive?T.data<M.value:T.data<=M.value)$=this._getOrReturnCtx(T,$),P($,{code:x.too_small,minimum:M.value,type:"number",inclusive:M.inclusive,exact:!1,message:M.message}),f.dirty()}else if(M.kind==="max"){if(M.inclusive?T.data>M.value:T.data>=M.value)$=this._getOrReturnCtx(T,$),P($,{code:x.too_big,maximum:M.value,type:"number",inclusive:M.inclusive,exact:!1,message:M.message}),f.dirty()}else if(M.kind==="multipleOf"){if(r4(T.data,M.value)!==0)$=this._getOrReturnCtx(T,$),P($,{code:x.not_multiple_of,multipleOf:M.value,message:M.message}),f.dirty()}else if(M.kind==="finite"){if(!Number.isFinite(T.data))$=this._getOrReturnCtx(T,$),P($,{code:x.not_finite,message:M.message}),f.dirty()}else yT.assertNever(M);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,d.toString(S))}gt(T,S){return this.setLimit("min",T,!1,d.toString(S))}lte(T,S){return this.setLimit("max",T,!0,d.toString(S))}lt(T,S){return this.setLimit("max",T,!1,d.toString(S))}setLimit(T,S,$,f){return new c$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:d.toString(f)}]})}_addCheck(T){return new c$({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:d.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:d.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:d.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:d.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:d.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:d.toString(S)})}finite(T){return this._addCheck({kind:"finite",message:d.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:d.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:d.toString(T)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&yT.isInteger(T.value))}get isFinite(){let T=null,S=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(S===null||$.value>S)S=$.value}else if($.kind==="max"){if(T===null||$.value<T)T=$.value}return Number.isFinite(S)&&Number.isFinite(T)}}c$.create=(T)=>{return new c$({checks:[],typeName:C.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...MT(T)})};class g$ extends JT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)T.data=BigInt(T.data);if(this._getType(T)!==o.bigint){let M=this._getOrReturnCtx(T);return P(M,{code:x.invalid_type,expected:o.bigint,received:M.parsedType}),ST}let $=void 0,f=new KS;for(let M of this._def.checks)if(M.kind==="min"){if(M.inclusive?T.data<M.value:T.data<=M.value)$=this._getOrReturnCtx(T,$),P($,{code:x.too_small,type:"bigint",minimum:M.value,inclusive:M.inclusive,message:M.message}),f.dirty()}else if(M.kind==="max"){if(M.inclusive?T.data>M.value:T.data>=M.value)$=this._getOrReturnCtx(T,$),P($,{code:x.too_big,type:"bigint",maximum:M.value,inclusive:M.inclusive,message:M.message}),f.dirty()}else if(M.kind==="multipleOf"){if(T.data%M.value!==BigInt(0))$=this._getOrReturnCtx(T,$),P($,{code:x.not_multiple_of,multipleOf:M.value,message:M.message}),f.dirty()}else yT.assertNever(M);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,d.toString(S))}gt(T,S){return this.setLimit("min",T,!1,d.toString(S))}lte(T,S){return this.setLimit("max",T,!0,d.toString(S))}lt(T,S){return this.setLimit("max",T,!1,d.toString(S))}setLimit(T,S,$,f){return new g$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:d.toString(f)}]})}_addCheck(T){return new g$({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:d.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:d.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:d.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:d.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:d.toString(S)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}g$.create=(T)=>{var S;return new g$({checks:[],typeName:C.ZodBigInt,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...MT(T)})};class cf extends JT{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==o.boolean){let $=this._getOrReturnCtx(T);return P($,{code:x.invalid_type,expected:o.boolean,received:$.parsedType}),ST}return GS(T.data)}}cf.create=(T)=>{return new cf({typeName:C.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...MT(T)})};class Tf extends JT{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==o.date){let M=this._getOrReturnCtx(T);return P(M,{code:x.invalid_type,expected:o.date,received:M.parsedType}),ST}if(isNaN(T.data.getTime())){let M=this._getOrReturnCtx(T);return P(M,{code:x.invalid_date}),ST}let $=new KS,f=void 0;for(let M of this._def.checks)if(M.kind==="min"){if(T.data.getTime()<M.value)f=this._getOrReturnCtx(T,f),P(f,{code:x.too_small,message:M.message,inclusive:!0,exact:!1,minimum:M.value,type:"date"}),$.dirty()}else if(M.kind==="max"){if(T.data.getTime()>M.value)f=this._getOrReturnCtx(T,f),P(f,{code:x.too_big,message:M.message,inclusive:!0,exact:!1,maximum:M.value,type:"date"}),$.dirty()}else yT.assertNever(M);return{status:$.value,value:new Date(T.data.getTime())}}_addCheck(T){return new Tf({...this._def,checks:[...this._def.checks,T]})}min(T,S){return this._addCheck({kind:"min",value:T.getTime(),message:d.toString(S)})}max(T,S){return this._addCheck({kind:"max",value:T.getTime(),message:d.toString(S)})}get minDate(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T!=null?new Date(T):null}}Tf.create=(T)=>{return new Tf({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:C.ZodDate,...MT(T)})};class tM extends JT{_parse(T){if(this._getType(T)!==o.symbol){let $=this._getOrReturnCtx(T);return P($,{code:x.invalid_type,expected:o.symbol,received:$.parsedType}),ST}return GS(T.data)}}tM.create=(T)=>{return new tM({typeName:C.ZodSymbol,...MT(T)})};class gf extends JT{_parse(T){if(this._getType(T)!==o.undefined){let $=this._getOrReturnCtx(T);return P($,{code:x.invalid_type,expected:o.undefined,received:$.parsedType}),ST}return GS(T.data)}}gf.create=(T)=>{return new gf({typeName:C.ZodUndefined,...MT(T)})};class of extends JT{_parse(T){if(this._getType(T)!==o.null){let $=this._getOrReturnCtx(T);return P($,{code:x.invalid_type,expected:o.null,received:$.parsedType}),ST}return GS(T.data)}}of.create=(T)=>{return new of({typeName:C.ZodNull,...MT(T)})};class Sf extends JT{constructor(){super(...arguments);this._any=!0}_parse(T){return GS(T.data)}}Sf.create=(T)=>{return new Sf({typeName:C.ZodAny,...MT(T)})};class n$ extends JT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return GS(T.data)}}n$.create=(T)=>{return new n$({typeName:C.ZodUnknown,...MT(T)})};class W$ extends JT{_parse(T){let S=this._getOrReturnCtx(T);return P(S,{code:x.invalid_type,expected:o.never,received:S.parsedType}),ST}}W$.create=(T)=>{return new W$({typeName:C.ZodNever,...MT(T)})};class pM extends JT{_parse(T){if(this._getType(T)!==o.undefined){let $=this._getOrReturnCtx(T);return P($,{code:x.invalid_type,expected:o.void,received:$.parsedType}),ST}return GS(T.data)}}pM.create=(T)=>{return new pM({typeName:C.ZodVoid,...MT(T)})};class uS extends JT{_parse(T){let{ctx:S,status:$}=this._processInputParams(T),f=this._def;if(S.parsedType!==o.array)return P(S,{code:x.invalid_type,expected:o.array,received:S.parsedType}),ST;if(f.exactLength!==null){let J=S.data.length>f.exactLength.value,F=S.data.length<f.exactLength.value;if(J||F)P(S,{code:J?x.too_big:x.too_small,minimum:F?f.exactLength.value:void 0,maximum:J?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),$.dirty()}if(f.minLength!==null){if(S.data.length<f.minLength.value)P(S,{code:x.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),$.dirty()}if(f.maxLength!==null){if(S.data.length>f.maxLength.value)P(S,{code:x.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),$.dirty()}if(S.common.async)return Promise.all([...S.data].map((J,F)=>{return f.type._parseAsync(new rS(S,J,S.path,F))})).then((J)=>{return KS.mergeArray($,J)});let M=[...S.data].map((J,F)=>{return f.type._parseSync(new rS(S,J,S.path,F))});return KS.mergeArray($,M)}get element(){return this._def.type}min(T,S){return new uS({...this._def,minLength:{value:T,message:d.toString(S)}})}max(T,S){return new uS({...this._def,maxLength:{value:T,message:d.toString(S)}})}length(T,S){return new uS({...this._def,exactLength:{value:T,message:d.toString(S)}})}nonempty(T){return this.min(1,T)}}uS.create=(T,S)=>{return new uS({type:T,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...MT(S)})};function hf(T){if(T instanceof qT){let S={};for(let $ in T.shape){let f=T.shape[$];S[$]=lS.create(hf(f))}return new qT({...T._def,shape:()=>S})}else if(T instanceof uS)return new uS({...T._def,type:hf(T.element)});else if(T instanceof lS)return lS.create(hf(T.unwrap()));else if(T instanceof H$)return H$.create(hf(T.unwrap()));else if(T instanceof A$)return A$.create(T.items.map((S)=>hf(S)));else return T}class qT extends JT{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let T=this._def.shape(),S=yT.objectKeys(T);return this._cached={shape:T,keys:S}}_parse(T){if(this._getType(T)!==o.object){let A=this._getOrReturnCtx(T);return P(A,{code:x.invalid_type,expected:o.object,received:A.parsedType}),ST}let{status:$,ctx:f}=this._processInputParams(T),{shape:M,keys:J}=this._getCached(),F=[];if(!(this._def.catchall instanceof W$&&this._def.unknownKeys==="strip")){for(let A in f.data)if(!J.includes(A))F.push(A)}let W=[];for(let A of J){let k=M[A],X=f.data[A];W.push({key:{status:"valid",value:A},value:k._parse(new rS(f,X,f.path,A)),alwaysSet:A in f.data})}if(this._def.catchall instanceof W$){let A=this._def.unknownKeys;if(A==="passthrough")for(let k of F)W.push({key:{status:"valid",value:k},value:{status:"valid",value:f.data[k]}});else if(A==="strict"){if(F.length>0)P(f,{code:x.unrecognized_keys,keys:F}),$.dirty()}else if(A==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let A=this._def.catchall;for(let k of F){let X=f.data[k];W.push({key:{status:"valid",value:k},value:A._parse(new rS(f,X,f.path,k)),alwaysSet:k in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let A=[];for(let k of W){let X=await k.key,w=await k.value;A.push({key:X,value:w,alwaysSet:k.alwaysSet})}return A}).then((A)=>{return KS.mergeObjectSync($,A)});else return KS.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(T){return d.errToObj,new qT({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:(S,$)=>{var f,M,J,F;let W=(J=(M=(f=this._def).errorMap)===null||M===void 0?void 0:M.call(f,S,$).message)!==null&&J!==void 0?J:$.defaultError;if(S.code==="unrecognized_keys")return{message:(F=d.errToObj(T).message)!==null&&F!==void 0?F:W};return{message:W}}}:{}})}strip(){return new qT({...this._def,unknownKeys:"strip"})}passthrough(){return new qT({...this._def,unknownKeys:"passthrough"})}extend(T){return new qT({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new qT({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:C.ZodObject})}setKey(T,S){return this.augment({[T]:S})}catchall(T){return new qT({...this._def,catchall:T})}pick(T){let S={};return yT.objectKeys(T).forEach(($)=>{if(T[$]&&this.shape[$])S[$]=this.shape[$]}),new qT({...this._def,shape:()=>S})}omit(T){let S={};return yT.objectKeys(this.shape).forEach(($)=>{if(!T[$])S[$]=this.shape[$]}),new qT({...this._def,shape:()=>S})}deepPartial(){return hf(this)}partial(T){let S={};return yT.objectKeys(this.shape).forEach(($)=>{let f=this.shape[$];if(T&&!T[$])S[$]=f;else S[$]=f.optional()}),new qT({...this._def,shape:()=>S})}required(T){let S={};return yT.objectKeys(this.shape).forEach(($)=>{if(T&&!T[$])S[$]=this.shape[$];else{let M=this.shape[$];while(M instanceof lS)M=M._def.innerType;S[$]=M}}),new qT({...this._def,shape:()=>S})}keyof(){return Dk(yT.objectKeys(this.shape))}}qT.create=(T,S)=>{return new qT({shape:()=>T,unknownKeys:"strip",catchall:W$.create(),typeName:C.ZodObject,...MT(S)})};qT.strictCreate=(T,S)=>{return new qT({shape:()=>T,unknownKeys:"strict",catchall:W$.create(),typeName:C.ZodObject,...MT(S)})};qT.lazycreate=(T,S)=>{return new qT({shape:T,unknownKeys:"strip",catchall:W$.create(),typeName:C.ZodObject,...MT(S)})};class tf extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$=this._def.options;function f(M){for(let F of M)if(F.result.status==="valid")return F.result;for(let F of M)if(F.result.status==="dirty")return S.common.issues.push(...F.ctx.common.issues),F.result;let J=M.map((F)=>new LS(F.ctx.common.issues));return P(S,{code:x.invalid_union,unionErrors:J}),ST}if(S.common.async)return Promise.all($.map(async(M)=>{let J={...S,common:{...S.common,issues:[]},parent:null};return{result:await M._parseAsync({data:S.data,path:S.path,parent:J}),ctx:J}})).then(f);else{let M=void 0,J=[];for(let W of $){let A={...S,common:{...S.common,issues:[]},parent:null},k=W._parseSync({data:S.data,path:S.path,parent:A});if(k.status==="valid")return k;else if(k.status==="dirty"&&!M)M={result:k,ctx:A};if(A.common.issues.length)J.push(A.common.issues)}if(M)return S.common.issues.push(...M.ctx.common.issues),M.result;let F=J.map((W)=>new LS(W));return P(S,{code:x.invalid_union,unionErrors:F}),ST}}get options(){return this._def.options}}tf.create=(T,S)=>{return new tf({options:T,typeName:C.ZodUnion,...MT(S)})};var _$=(T)=>{if(T instanceof df)return _$(T.schema);else if(T instanceof hS)return _$(T.innerType());else if(T instanceof uf)return[T.value];else if(T instanceof o$)return T.options;else if(T instanceof lf)return yT.objectValues(T.enum);else if(T instanceof rf)return _$(T._def.innerType);else if(T instanceof gf)return[void 0];else if(T instanceof of)return[null];else if(T instanceof lS)return[void 0,..._$(T.unwrap())];else if(T instanceof H$)return[null,..._$(T.unwrap())];else if(T instanceof RF)return _$(T.unwrap());else if(T instanceof ef)return _$(T.unwrap());else if(T instanceof af)return _$(T._def.innerType);else return[]};class OF extends JT{_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==o.object)return P(S,{code:x.invalid_type,expected:o.object,received:S.parsedType}),ST;let $=this.discriminator,f=S.data[$],M=this.optionsMap.get(f);if(!M)return P(S,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),ST;if(S.common.async)return M._parseAsync({data:S.data,path:S.path,parent:S});else return M._parseSync({data:S.data,path:S.path,parent:S})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,S,$){let f=new Map;for(let M of S){let J=_$(M.shape[T]);if(!J.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let F of J){if(f.has(F))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String(F)}`);f.set(F,M)}}return new OF({typeName:C.ZodDiscriminatedUnion,discriminator:T,options:S,optionsMap:f,...MT($)})}}function H0(T,S){let $=P$(T),f=P$(S);if(T===S)return{valid:!0,data:T};else if($===o.object&&f===o.object){let M=yT.objectKeys(S),J=yT.objectKeys(T).filter((W)=>M.indexOf(W)!==-1),F={...T,...S};for(let W of J){let A=H0(T[W],S[W]);if(!A.valid)return{valid:!1};F[W]=A.data}return{valid:!0,data:F}}else if($===o.array&&f===o.array){if(T.length!==S.length)return{valid:!1};let M=[];for(let J=0;J<T.length;J++){let F=T[J],W=S[J],A=H0(F,W);if(!A.valid)return{valid:!1};M.push(A.data)}return{valid:!0,data:M}}else if($===o.date&&f===o.date&&+T===+S)return{valid:!0,data:T};else return{valid:!1}}class pf extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T),f=(M,J)=>{if(z0(M)||z0(J))return ST;let F=H0(M.value,J.value);if(!F.valid)return P($,{code:x.invalid_intersection_types}),ST;if(_0(M)||_0(J))S.dirty();return{status:S.value,value:F.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([M,J])=>f(M,J));else return f(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}pf.create=(T,S,$)=>{return new pf({left:T,right:S,typeName:C.ZodIntersection,...MT($)})};class A$ extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==o.array)return P($,{code:x.invalid_type,expected:o.array,received:$.parsedType}),ST;if($.data.length<this._def.items.length)return P($,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ST;if(!this._def.rest&&$.data.length>this._def.items.length)P($,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.dirty();let M=[...$.data].map((J,F)=>{let W=this._def.items[F]||this._def.rest;if(!W)return null;return W._parse(new rS($,J,$.path,F))}).filter((J)=>!!J);if($.common.async)return Promise.all(M).then((J)=>{return KS.mergeArray(S,J)});else return KS.mergeArray(S,M)}get items(){return this._def.items}rest(T){return new A$({...this._def,rest:T})}}A$.create=(T,S)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new A$({items:T,typeName:C.ZodTuple,rest:null,...MT(S)})};class iM extends JT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==o.object)return P($,{code:x.invalid_type,expected:o.object,received:$.parsedType}),ST;let f=[],M=this._def.keyType,J=this._def.valueType;for(let F in $.data)f.push({key:M._parse(new rS($,F,$.path,F)),value:J._parse(new rS($,$.data[F],$.path,F)),alwaysSet:F in $.data});if($.common.async)return KS.mergeObjectAsync(S,f);else return KS.mergeObjectSync(S,f)}get element(){return this._def.valueType}static create(T,S,$){if(S instanceof JT)return new iM({keyType:T,valueType:S,typeName:C.ZodRecord,...MT($)});return new iM({keyType:dS.create(),valueType:T,typeName:C.ZodRecord,...MT(S)})}}class dM extends JT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==o.map)return P($,{code:x.invalid_type,expected:o.map,received:$.parsedType}),ST;let f=this._def.keyType,M=this._def.valueType,J=[...$.data.entries()].map(([F,W],A)=>{return{key:f._parse(new rS($,F,$.path,[A,"key"])),value:M._parse(new rS($,W,$.path,[A,"value"]))}});if($.common.async){let F=new Map;return Promise.resolve().then(async()=>{for(let W of J){let A=await W.key,k=await W.value;if(A.status==="aborted"||k.status==="aborted")return ST;if(A.status==="dirty"||k.status==="dirty")S.dirty();F.set(A.value,k.value)}return{status:S.value,value:F}})}else{let F=new Map;for(let W of J){let{key:A,value:k}=W;if(A.status==="aborted"||k.status==="aborted")return ST;if(A.status==="dirty"||k.status==="dirty")S.dirty();F.set(A.value,k.value)}return{status:S.value,value:F}}}}dM.create=(T,S,$)=>{return new dM({valueType:S,keyType:T,typeName:C.ZodMap,...MT($)})};class $f extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==o.set)return P($,{code:x.invalid_type,expected:o.set,received:$.parsedType}),ST;let f=this._def;if(f.minSize!==null){if($.data.size<f.minSize.value)P($,{code:x.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),S.dirty()}if(f.maxSize!==null){if($.data.size>f.maxSize.value)P($,{code:x.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),S.dirty()}let M=this._def.valueType;function J(W){let A=new Set;for(let k of W){if(k.status==="aborted")return ST;if(k.status==="dirty")S.dirty();A.add(k.value)}return{status:S.value,value:A}}let F=[...$.data.values()].map((W,A)=>M._parse(new rS($,W,$.path,A)));if($.common.async)return Promise.all(F).then((W)=>J(W));else return J(F)}min(T,S){return new $f({...this._def,minSize:{value:T,message:d.toString(S)}})}max(T,S){return new $f({...this._def,maxSize:{value:T,message:d.toString(S)}})}size(T,S){return this.min(T,S).max(T,S)}nonempty(T){return this.min(1,T)}}$f.create=(T,S)=>{return new $f({valueType:T,minSize:null,maxSize:null,typeName:C.ZodSet,...MT(S)})};class Pf extends JT{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==o.function)return P(S,{code:x.invalid_type,expected:o.function,received:S.parsedType}),ST;function $(F,W){return YF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,KF(),nf].filter((A)=>!!A),issueData:{code:x.invalid_arguments,argumentsError:W}})}function f(F,W){return YF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,KF(),nf].filter((A)=>!!A),issueData:{code:x.invalid_return_type,returnTypeError:W}})}let M={errorMap:S.common.contextualErrorMap},J=S.data;if(this._def.returns instanceof ff){let F=this;return GS(async function(...W){let A=new LS([]),k=await F._def.args.parseAsync(W,M).catch((K)=>{throw A.addIssue($(W,K)),A}),X=await Reflect.apply(J,this,k);return await F._def.returns._def.type.parseAsync(X,M).catch((K)=>{throw A.addIssue(f(X,K)),A})})}else{let F=this;return GS(function(...W){let A=F._def.args.safeParse(W,M);if(!A.success)throw new LS([$(W,A.error)]);let k=Reflect.apply(J,this,A.data),X=F._def.returns.safeParse(k,M);if(!X.success)throw new LS([f(k,X.error)]);return X.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new Pf({...this._def,args:A$.create(T).rest(n$.create())})}returns(T){return new Pf({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,S,$){return new Pf({args:T?T:A$.create([]).rest(n$.create()),returns:S||n$.create(),typeName:C.ZodFunction,...MT($)})}}class df extends JT{get schema(){return this._def.getter()}_parse(T){let{ctx:S}=this._processInputParams(T);return this._def.getter()._parse({data:S.data,path:S.path,parent:S})}}df.create=(T,S)=>{return new df({getter:T,typeName:C.ZodLazy,...MT(S)})};class uf extends JT{_parse(T){if(T.data!==this._def.value){let S=this._getOrReturnCtx(T);return P(S,{received:S.data,code:x.invalid_literal,expected:this._def.value}),ST}return{status:"valid",value:T.data}}get value(){return this._def.value}}uf.create=(T,S)=>{return new uf({value:T,typeName:C.ZodLiteral,...MT(S)})};function Dk(T,S){return new o$({values:T,typeName:C.ZodEnum,...MT(S)})}class o$ extends JT{constructor(){super(...arguments);nM.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){let S=this._getOrReturnCtx(T),$=this._def.values;return P(S,{expected:yT.joinValues($),received:S.parsedType,code:x.invalid_type}),ST}if(!yF(this,nM,"f"))zk(this,nM,new Set(this._def.values),"f");if(!yF(this,nM,"f").has(T.data)){let S=this._getOrReturnCtx(T),$=this._def.values;return P(S,{received:S.data,code:x.invalid_enum_value,options:$}),ST}return GS(T.data)}get options(){return this._def.values}get enum(){let T={};for(let S of this._def.values)T[S]=S;return T}get Values(){let T={};for(let S of this._def.values)T[S]=S;return T}get Enum(){let T={};for(let S of this._def.values)T[S]=S;return T}extract(T,S=this._def){return o$.create(T,{...this._def,...S})}exclude(T,S=this._def){return o$.create(this.options.filter(($)=>!T.includes($)),{...this._def,...S})}}nM=new WeakMap;o$.create=Dk;class lf extends JT{constructor(){super(...arguments);cM.set(this,void 0)}_parse(T){let S=yT.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(T);if($.parsedType!==o.string&&$.parsedType!==o.number){let f=yT.objectValues(S);return P($,{expected:yT.joinValues(f),received:$.parsedType,code:x.invalid_type}),ST}if(!yF(this,cM,"f"))zk(this,cM,new Set(yT.getValidEnumValues(this._def.values)),"f");if(!yF(this,cM,"f").has(T.data)){let f=yT.objectValues(S);return P($,{received:$.data,code:x.invalid_enum_value,options:f}),ST}return GS(T.data)}get enum(){return this._def.values}}cM=new WeakMap;lf.create=(T,S)=>{return new lf({values:T,typeName:C.ZodNativeEnum,...MT(S)})};class ff extends JT{unwrap(){return this._def.type}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==o.promise&&S.common.async===!1)return P(S,{code:x.invalid_type,expected:o.promise,received:S.parsedType}),ST;let $=S.parsedType===o.promise?S.data:Promise.resolve(S.data);return GS($.then((f)=>{return this._def.type.parseAsync(f,{path:S.path,errorMap:S.common.contextualErrorMap})}))}}ff.create=(T,S)=>{return new ff({type:T,typeName:C.ZodPromise,...MT(S)})};class hS extends JT{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){let{status:S,ctx:$}=this._processInputParams(T),f=this._def.effect||null,M={addIssue:(J)=>{if(P($,J),J.fatal)S.abort();else S.dirty()},get path(){return $.path}};if(M.addIssue=M.addIssue.bind(M),f.type==="preprocess"){let J=f.transform($.data,M);if($.common.async)return Promise.resolve(J).then(async(F)=>{if(S.value==="aborted")return ST;let W=await this._def.schema._parseAsync({data:F,path:$.path,parent:$});if(W.status==="aborted")return ST;if(W.status==="dirty")return vf(W.value);if(S.value==="dirty")return vf(W.value);return W});else{if(S.value==="aborted")return ST;let F=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(F.status==="aborted")return ST;if(F.status==="dirty")return vf(F.value);if(S.value==="dirty")return vf(F.value);return F}}if(f.type==="refinement"){let J=(F)=>{let W=f.refinement(F,M);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return F};if($.common.async===!1){let F=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(F.status==="aborted")return ST;if(F.status==="dirty")S.dirty();return J(F.value),{status:S.value,value:F.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((F)=>{if(F.status==="aborted")return ST;if(F.status==="dirty")S.dirty();return J(F.value).then(()=>{return{status:S.value,value:F.value}})})}if(f.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!gM(J))return J;let F=f.transform(J.value,M);if(F instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:S.value,value:F}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!gM(J))return J;return Promise.resolve(f.transform(J.value,M)).then((F)=>({status:S.value,value:F}))});yT.assertNever(f)}}hS.create=(T,S,$)=>{return new hS({schema:T,typeName:C.ZodEffects,effect:S,...MT($)})};hS.createWithPreprocess=(T,S,$)=>{return new hS({schema:S,effect:{type:"preprocess",transform:T},typeName:C.ZodEffects,...MT($)})};class lS extends JT{_parse(T){if(this._getType(T)===o.undefined)return GS(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}lS.create=(T,S)=>{return new lS({innerType:T,typeName:C.ZodOptional,...MT(S)})};class H$ extends JT{_parse(T){if(this._getType(T)===o.null)return GS(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}H$.create=(T,S)=>{return new H$({innerType:T,typeName:C.ZodNullable,...MT(S)})};class rf extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$=S.data;if(S.parsedType===o.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:S.path,parent:S})}removeDefault(){return this._def.innerType}}rf.create=(T,S)=>{return new rf({innerType:T,typeName:C.ZodDefault,defaultValue:typeof S.default==="function"?S.default:()=>S.default,...MT(S)})};class af extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$={...S,common:{...S.common,issues:[]}},f=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(oM(f))return f.then((M)=>{return{status:"valid",value:M.status==="valid"?M.value:this._def.catchValue({get error(){return new LS($.common.issues)},input:$.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new LS($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}af.create=(T,S)=>{return new af({innerType:T,typeName:C.ZodCatch,catchValue:typeof S.catch==="function"?S.catch:()=>S.catch,...MT(S)})};class uM extends JT{_parse(T){if(this._getType(T)!==o.nan){let $=this._getOrReturnCtx(T);return P($,{code:x.invalid_type,expected:o.nan,received:$.parsedType}),ST}return{status:"valid",value:T.data}}}uM.create=(T)=>{return new uM({typeName:C.ZodNaN,...MT(T)})};var a4=Symbol("zod_brand");class RF extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$=S.data;return this._def.type._parse({data:$,path:S.path,parent:S})}unwrap(){return this._def.type}}class lM extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.common.async)return(async()=>{let M=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(M.status==="aborted")return ST;if(M.status==="dirty")return S.dirty(),vf(M.value);else return this._def.out._parseAsync({data:M.value,path:$.path,parent:$})})();else{let f=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(f.status==="aborted")return ST;if(f.status==="dirty")return S.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:$.path,parent:$})}}static create(T,S){return new lM({in:T,out:S,typeName:C.ZodPipeline})}}class ef extends JT{_parse(T){let S=this._def.innerType._parse(T),$=(f)=>{if(gM(f))f.value=Object.freeze(f.value);return f};return oM(S)?S.then((f)=>$(f)):$(S)}unwrap(){return this._def.innerType}}ef.create=(T,S)=>{return new ef({innerType:T,typeName:C.ZodReadonly,...MT(S)})};function Qk(T,S={},$){if(T)return Sf.create().superRefine((f,M)=>{var J,F;if(!T(f)){let W=typeof S==="function"?S(f):typeof S==="string"?{message:S}:S,A=(F=(J=W.fatal)!==null&&J!==void 0?J:$)!==null&&F!==void 0?F:!0,k=typeof W==="string"?{message:W}:W;M.addIssue({code:"custom",...k,fatal:A})}});return Sf.create()}var e4={object:qT.lazycreate},C;(function(T){T.ZodString="ZodString",T.ZodNumber="ZodNumber",T.ZodNaN="ZodNaN",T.ZodBigInt="ZodBigInt",T.ZodBoolean="ZodBoolean",T.ZodDate="ZodDate",T.ZodSymbol="ZodSymbol",T.ZodUndefined="ZodUndefined",T.ZodNull="ZodNull",T.ZodAny="ZodAny",T.ZodUnknown="ZodUnknown",T.ZodNever="ZodNever",T.ZodVoid="ZodVoid",T.ZodArray="ZodArray",T.ZodObject="ZodObject",T.ZodUnion="ZodUnion",T.ZodDiscriminatedUnion="ZodDiscriminatedUnion",T.ZodIntersection="ZodIntersection",T.ZodTuple="ZodTuple",T.ZodRecord="ZodRecord",T.ZodMap="ZodMap",T.ZodSet="ZodSet",T.ZodFunction="ZodFunction",T.ZodLazy="ZodLazy",T.ZodLiteral="ZodLiteral",T.ZodEnum="ZodEnum",T.ZodEffects="ZodEffects",T.ZodNativeEnum="ZodNativeEnum",T.ZodOptional="ZodOptional",T.ZodNullable="ZodNullable",T.ZodDefault="ZodDefault",T.ZodCatch="ZodCatch",T.ZodPromise="ZodPromise",T.ZodBranded="ZodBranded",T.ZodPipeline="ZodPipeline",T.ZodReadonly="ZodReadonly"})(C||(C={}));var s4=(T,S={message:`Input not instance of ${T.name}`})=>Qk(($)=>$ instanceof T,S),Uk=dS.create,Vk=c$.create,TY=uM.create,SY=g$.create,Bk=cf.create,$Y=Tf.create,fY=tM.create,MY=gf.create,JY=of.create,FY=Sf.create,WY=n$.create,AY=W$.create,kY=pM.create,XY=uS.create,rM=qT.create,wY=qT.strictCreate,KY=tf.create,YY=OF.create,yY=pf.create,OY=A$.create,RY=iM.create,GY=dM.create,zY=$f.create,_Y=Pf.create,HY=df.create,EY=uf.create,DY=o$.create,QY=lf.create,UY=ff.create,Rk=hS.create,VY=lS.create,BY=H$.create,LY=hS.createWithPreprocess,NY=lM.create,CY=()=>Uk().optional(),xY=()=>Vk().optional(),jY=()=>Bk().optional(),IY={string:(T)=>dS.create({...T,coerce:!0}),number:(T)=>c$.create({...T,coerce:!0}),boolean:(T)=>cf.create({...T,coerce:!0}),bigint:(T)=>g$.create({...T,coerce:!0}),date:(T)=>Tf.create({...T,coerce:!0})},bY=ST,zT=Object.freeze({__proto__:null,defaultErrorMap:nf,setErrorMap:Z4,getErrorMap:KF,makeIssue:YF,EMPTY_PATH:q4,addIssueToContext:P,ParseStatus:KS,INVALID:ST,DIRTY:vf,OK:GS,isAborted:z0,isDirty:_0,isValid:gM,isAsync:oM,get util(){return yT},get objectUtil(){return G0},ZodParsedType:o,getParsedType:P$,ZodType:JT,datetimeRegex:Ek,ZodString:dS,ZodNumber:c$,ZodBigInt:g$,ZodBoolean:cf,ZodDate:Tf,ZodSymbol:tM,ZodUndefined:gf,ZodNull:of,ZodAny:Sf,ZodUnknown:n$,ZodNever:W$,ZodVoid:pM,ZodArray:uS,ZodObject:qT,ZodUnion:tf,ZodDiscriminatedUnion:OF,ZodIntersection:pf,ZodTuple:A$,ZodRecord:iM,ZodMap:dM,ZodSet:$f,ZodFunction:Pf,ZodLazy:df,ZodLiteral:uf,ZodEnum:o$,ZodNativeEnum:lf,ZodPromise:ff,ZodEffects:hS,ZodTransformer:hS,ZodOptional:lS,ZodNullable:H$,ZodDefault:rf,ZodCatch:af,ZodNaN:uM,BRAND:a4,ZodBranded:RF,ZodPipeline:lM,ZodReadonly:ef,custom:Qk,Schema:JT,ZodSchema:JT,late:e4,get ZodFirstPartyTypeKind(){return C},coerce:IY,any:FY,array:XY,bigint:SY,boolean:Bk,date:$Y,discriminatedUnion:YY,effect:Rk,enum:DY,function:_Y,instanceof:s4,intersection:yY,lazy:HY,literal:EY,map:GY,nan:TY,nativeEnum:QY,never:AY,null:JY,nullable:BY,number:Vk,object:rM,oboolean:jY,onumber:xY,optional:VY,ostring:CY,pipeline:NY,preprocess:LY,promise:UY,record:RY,set:zY,strictObject:wY,string:Uk,symbol:fY,transformer:Rk,tuple:OY,undefined:MY,union:KY,unknown:WY,void:kY,NEVER:bY,ZodIssueCode:x,quotelessJson:b4,ZodError:LS});function Lk(){return{}}function Nk(T,S){let $={type:"array"};if(T.type?._def&&T.type?._def?.typeName!==C.ZodAny)$.items=s(T.type._def,{...S,currentPath:[...S.currentPath,"items"]});if(T.minLength)wT($,"minItems",T.minLength.value,T.minLength.message,S);if(T.maxLength)wT($,"maxItems",T.maxLength.value,T.maxLength.message,S);if(T.exactLength)wT($,"minItems",T.exactLength.value,T.exactLength.message,S),wT($,"maxItems",T.exactLength.value,T.exactLength.message,S);return $}function Ck(T,S){let $={type:"integer",format:"int64"};if(!T.checks)return $;for(let f of T.checks)switch(f.kind){case"min":if(S.target==="jsonSchema7")if(f.inclusive)wT($,"minimum",f.value,f.message,S);else wT($,"exclusiveMinimum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMinimum=!0;wT($,"minimum",f.value,f.message,S)}break;case"max":if(S.target==="jsonSchema7")if(f.inclusive)wT($,"maximum",f.value,f.message,S);else wT($,"exclusiveMaximum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMaximum=!0;wT($,"maximum",f.value,f.message,S)}break;case"multipleOf":wT($,"multipleOf",f.value,f.message,S);break}return $}function xk(){return{type:"boolean"}}function GF(T,S){return s(T.type._def,S)}var jk=(T,S)=>{return s(T.innerType._def,S)};function E0(T,S,$){let f=$??S.dateStrategy;if(Array.isArray(f))return{anyOf:f.map((M,J)=>E0(T,S,M))};switch(f){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ZY(T,S)}}var ZY=(T,S)=>{let $={type:"integer",format:"unix-time"};if(S.target==="openApi3")return $;for(let f of T.checks)switch(f.kind){case"min":wT($,"minimum",f.value,f.message,S);break;case"max":wT($,"maximum",f.value,f.message,S);break}return $};function Ik(T,S){return{...s(T.innerType._def,S),default:T.defaultValue()}}function bk(T,S){return S.effectStrategy==="input"?s(T.schema._def,S):{}}function Zk(T){return{type:"string",enum:T.values}}var qY=(T)=>{if("type"in T&&T.type==="string")return!1;return"allOf"in T};function qk(T,S){let $=[s(T.left._def,{...S,currentPath:[...S.currentPath,"allOf","0"]}),s(T.right._def,{...S,currentPath:[...S.currentPath,"allOf","1"]})].filter((J)=>!!J),f=S.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,M=[];return $.forEach((J)=>{if(qY(J)){if(M.push(...J.allOf),J.unevaluatedProperties===void 0)f=void 0}else{let F=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...A}=J;F=A}else f=void 0;M.push(F)}}),M.length?{allOf:M,...f}:void 0}function mk(T,S){let $=typeof T.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(T.value)?"array":"object"};if(S.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[T.value]};return{type:$==="bigint"?"integer":$,const:T.value}}var D0,Mf={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(D0===void 0)D0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return D0},uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function zF(T,S){let $={type:"string"};function f(M){return S.patternStrategy==="escape"?mY(M):M}if(T.checks)for(let M of T.checks)switch(M.kind){case"min":wT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,M.value):M.value,M.message,S);break;case"max":wT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,M.value):M.value,M.message,S);break;case"email":switch(S.emailStrategy){case"format:email":aS($,"email",M.message,S);break;case"format:idn-email":aS($,"idn-email",M.message,S);break;case"pattern:zod":eS($,Mf.email,M.message,S);break}break;case"url":aS($,"uri",M.message,S);break;case"uuid":aS($,"uuid",M.message,S);break;case"regex":eS($,M.regex,M.message,S);break;case"cuid":eS($,Mf.cuid,M.message,S);break;case"cuid2":eS($,Mf.cuid2,M.message,S);break;case"startsWith":eS($,RegExp(`^${f(M.value)}`),M.message,S);break;case"endsWith":eS($,RegExp(`${f(M.value)}$`),M.message,S);break;case"datetime":aS($,"date-time",M.message,S);break;case"date":aS($,"date",M.message,S);break;case"time":aS($,"time",M.message,S);break;case"duration":aS($,"duration",M.message,S);break;case"length":wT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,M.value):M.value,M.message,S),wT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,M.value):M.value,M.message,S);break;case"includes":{eS($,RegExp(f(M.value)),M.message,S);break}case"ip":{if(M.version!=="v6")aS($,"ipv4",M.message,S);if(M.version!=="v4")aS($,"ipv6",M.message,S);break}case"emoji":eS($,Mf.emoji,M.message,S);break;case"ulid":{eS($,Mf.ulid,M.message,S);break}case"base64":{switch(S.base64Strategy){case"format:binary":{aS($,"binary",M.message,S);break}case"contentEncoding:base64":{wT($,"contentEncoding","base64",M.message,S);break}case"pattern:zod":{eS($,Mf.base64,M.message,S);break}}break}case"nanoid":eS($,Mf.nanoid,M.message,S);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(M)}return $}var mY=(T)=>Array.from(T).map((S)=>/[a-zA-Z0-9]/.test(S)?S:`\\${S}`).join(""),aS=(T,S,$,f)=>{if(T.format||T.anyOf?.some((M)=>M.format)){if(!T.anyOf)T.anyOf=[];if(T.format){if(T.anyOf.push({format:T.format,...T.errorMessage&&f.errorMessages&&{errorMessage:{format:T.errorMessage.format}}}),delete T.format,T.errorMessage){if(delete T.errorMessage.format,Object.keys(T.errorMessage).length===0)delete T.errorMessage}}T.anyOf.push({format:S,...$&&f.errorMessages&&{errorMessage:{format:$}}})}else wT(T,"format",S,$,f)},eS=(T,S,$,f)=>{if(T.pattern||T.allOf?.some((M)=>M.pattern)){if(!T.allOf)T.allOf=[];if(T.pattern){if(T.allOf.push({pattern:T.pattern,...T.errorMessage&&f.errorMessages&&{errorMessage:{pattern:T.errorMessage.pattern}}}),delete T.pattern,T.errorMessage){if(delete T.errorMessage.pattern,Object.keys(T.errorMessage).length===0)delete T.errorMessage}}T.allOf.push({pattern:hk(S,f),...$&&f.errorMessages&&{errorMessage:{pattern:$}}})}else wT(T,"pattern",hk(S,f),$,f)},hk=(T,S)=>{let $=typeof T==="function"?T():T;if(!S.applyRegexFlags||!$.flags)return $.source;let f={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},M=f.i?$.source.toLowerCase():$.source,J="",F=!1,W=!1,A=!1;for(let k=0;k<M.length;k++){if(F){J+=M[k],F=!1;continue}if(f.i){if(W){if(M[k].match(/[a-z]/)){if(A)J+=M[k],J+=`${M[k-2]}-${M[k]}`.toUpperCase(),A=!1;else if(M[k+1]==="-"&&M[k+2]?.match(/[a-z]/))J+=M[k],A=!0;else J+=`${M[k]}${M[k].toUpperCase()}`;continue}}else if(M[k].match(/[a-z]/)){J+=`[${M[k]}${M[k].toUpperCase()}]`;continue}}if(f.m){if(M[k]==="^"){J+=`(^|(?<=[\r
10
+ ]))`;continue}else if(M[k]==="$"){J+=`($|(?=[\r
11
+ ]))`;continue}}if(f.s&&M[k]==="."){J+=W?`${M[k]}\r
12
+ `:`[${M[k]}\r
13
+ ]`;continue}if(J+=M[k],M[k]==="\\")F=!0;else if(W&&M[k]==="]")W=!1;else if(!W&&M[k]==="[")W=!0}try{let k=new RegExp(J)}catch{return console.warn(`Could not convert regex pattern at ${S.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return J};function _F(T,S){if(S.target==="openApi3"&&T.keyType?._def.typeName===C.ZodEnum)return{type:"object",required:T.keyType._def.values,properties:T.keyType._def.values.reduce((f,M)=>({...f,[M]:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"properties",M]})??{}}),{}),additionalProperties:!1};let $={type:"object",additionalProperties:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??{}};if(S.target==="openApi3")return $;if(T.keyType?._def.typeName===C.ZodString&&T.keyType._def.checks?.length){let{type:f,...M}=zF(T.keyType._def,S);return{...$,propertyNames:M}}else if(T.keyType?._def.typeName===C.ZodEnum)return{...$,propertyNames:{enum:T.keyType._def.values}};else if(T.keyType?._def.typeName===C.ZodBranded&&T.keyType._def.type._def.typeName===C.ZodString&&T.keyType._def.type._def.checks?.length){let{type:f,...M}=GF(T.keyType._def,S);return{...$,propertyNames:M}}return $}function vk(T,S){if(S.mapStrategy==="record")return _F(T,S);let $=s(T.keyType._def,{...S,currentPath:[...S.currentPath,"items","items","0"]})||{},f=s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[$,f],minItems:2,maxItems:2}}}function Pk(T){let S=T.values,f=Object.keys(T.values).filter((J)=>{return typeof S[S[J]]!=="number"}).map((J)=>S[J]),M=Array.from(new Set(f.map((J)=>typeof J)));return{type:M.length===1?M[0]==="string"?"string":"number":["string","number"],enum:f}}function nk(){return{not:{}}}function ck(T){return T.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var aM={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ok(T,S){if(S.target==="openApi3")return gk(T,S);let $=T.options instanceof Map?Array.from(T.options.values()):T.options;if($.every((f)=>(f._def.typeName in aM)&&(!f._def.checks||!f._def.checks.length))){let f=$.reduce((M,J)=>{let F=aM[J._def.typeName];return F&&!M.includes(F)?[...M,F]:M},[]);return{type:f.length>1?f:f[0]}}else if($.every((f)=>f._def.typeName==="ZodLiteral"&&!f.description)){let f=$.reduce((M,J)=>{let F=typeof J._def.value;switch(F){case"string":case"number":case"boolean":return[...M,F];case"bigint":return[...M,"integer"];case"object":if(J._def.value===null)return[...M,"null"];case"symbol":case"undefined":case"function":default:return M}},[]);if(f.length===$.length){let M=f.filter((J,F,W)=>W.indexOf(J)===F);return{type:M.length>1?M:M[0],enum:$.reduce((J,F)=>{return J.includes(F._def.value)?J:[...J,F._def.value]},[])}}}else if($.every((f)=>f._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((f,M)=>[...f,...M._def.values.filter((J)=>!f.includes(J))],[])};return gk(T,S)}var gk=(T,S)=>{let $=(T.options instanceof Map?Array.from(T.options.values()):T.options).map((f,M)=>s(f._def,{...S,currentPath:[...S.currentPath,"anyOf",`${M}`]})).filter((f)=>!!f&&(!S.strictUnions||typeof f==="object"&&Object.keys(f).length>0));return $.length?{anyOf:$}:void 0};function tk(T,S){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(T.innerType._def.typeName)&&(!T.innerType._def.checks||!T.innerType._def.checks.length)){if(S.target==="openApi3")return{type:aM[T.innerType._def.typeName],nullable:!0};return{type:[aM[T.innerType._def.typeName],"null"]}}if(S.target==="openApi3"){let f=s(T.innerType._def,{...S,currentPath:[...S.currentPath]});if(f&&"$ref"in f)return{allOf:[f],nullable:!0};return f&&{...f,nullable:!0}}let $=s(T.innerType._def,{...S,currentPath:[...S.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function pk(T,S){let $={type:"number"};if(!T.checks)return $;for(let f of T.checks)switch(f.kind){case"int":$.type="integer",O0($,"type",f.message,S);break;case"min":if(S.target==="jsonSchema7")if(f.inclusive)wT($,"minimum",f.value,f.message,S);else wT($,"exclusiveMinimum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMinimum=!0;wT($,"minimum",f.value,f.message,S)}break;case"max":if(S.target==="jsonSchema7")if(f.inclusive)wT($,"maximum",f.value,f.message,S);else wT($,"exclusiveMaximum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMaximum=!0;wT($,"maximum",f.value,f.message,S)}break;case"multipleOf":wT($,"multipleOf",f.value,f.message,S);break}return $}function hY(T,S){if(S.removeAdditionalStrategy==="strict")return T.catchall._def.typeName==="ZodNever"?T.unknownKeys!=="strict":s(T.catchall._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??!0;else return T.catchall._def.typeName==="ZodNever"?T.unknownKeys==="passthrough":s(T.catchall._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??!0}function ik(T,S){let $={type:"object",...Object.entries(T.shape()).reduce((f,[M,J])=>{if(J===void 0||J._def===void 0)return f;let F=s(J._def,{...S,currentPath:[...S.currentPath,"properties",M],propertyPath:[...S.currentPath,"properties",M]});if(F===void 0)return f;return{properties:{...f.properties,[M]:F},required:J.isOptional()?f.required:[...f.required,M]}},{properties:{},required:[]}),additionalProperties:hY(T,S)};if(!$.required.length)delete $.required;return $}var dk=(T,S)=>{if(S.currentPath.toString()===S.propertyPath?.toString())return s(T.innerType._def,S);let $=s(T.innerType._def,{...S,currentPath:[...S.currentPath,"anyOf","1"]});return $?{anyOf:[{not:{}},$]}:{}};var uk=(T,S)=>{if(S.pipeStrategy==="input")return s(T.in._def,S);else if(S.pipeStrategy==="output")return s(T.out._def,S);let $=s(T.in._def,{...S,currentPath:[...S.currentPath,"allOf","0"]}),f=s(T.out._def,{...S,currentPath:[...S.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,f].filter((M)=>M!==void 0)}};function lk(T,S){return s(T.type._def,S)}function rk(T,S){let f={type:"array",uniqueItems:!0,items:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items"]})};if(T.minSize)wT(f,"minItems",T.minSize.value,T.minSize.message,S);if(T.maxSize)wT(f,"maxItems",T.maxSize.value,T.maxSize.message,S);return f}function ak(T,S){if(T.rest)return{type:"array",minItems:T.items.length,items:T.items.map(($,f)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${f}`]})).reduce(($,f)=>f===void 0?$:[...$,f],[]),additionalItems:s(T.rest._def,{...S,currentPath:[...S.currentPath,"additionalItems"]})};else return{type:"array",minItems:T.items.length,maxItems:T.items.length,items:T.items.map(($,f)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${f}`]})).reduce(($,f)=>f===void 0?$:[...$,f],[])}}function ek(){return{not:{}}}function sk(){return{}}var TX=(T,S)=>{return s(T.innerType._def,S)};function s(T,S,$=!1){let f=S.seen.get(T);if(S.override){let F=S.override?.(T,S,f,$);if(F!==Kk)return F}if(f&&!$){let F=vY(f,S);if(F!==void 0)return F}let M={def:T,path:S.currentPath,jsonSchema:void 0};S.seen.set(T,M);let J=nY(T,T.typeName,S);if(J)cY(T,S,J);return M.jsonSchema=J,J}var vY=(T,S)=>{switch(S.$refStrategy){case"root":return{$ref:T.path.join("/")};case"relative":return{$ref:PY(S.currentPath,T.path)};case"none":case"seen":{if(T.path.length<S.currentPath.length&&T.path.every(($,f)=>S.currentPath[f]===$))return console.warn(`Recursive reference detected at ${S.currentPath.join("/")}! Defaulting to any`),{};return S.$refStrategy==="seen"?{}:void 0}}},PY=(T,S)=>{let $=0;for(;$<T.length&&$<S.length;$++)if(T[$]!==S[$])break;return[(T.length-$).toString(),...S.slice($)].join("/")},nY=(T,S,$)=>{switch(S){case C.ZodString:return zF(T,$);case C.ZodNumber:return pk(T,$);case C.ZodObject:return ik(T,$);case C.ZodBigInt:return Ck(T,$);case C.ZodBoolean:return xk();case C.ZodDate:return E0(T,$);case C.ZodUndefined:return ek();case C.ZodNull:return ck($);case C.ZodArray:return Nk(T,$);case C.ZodUnion:case C.ZodDiscriminatedUnion:return ok(T,$);case C.ZodIntersection:return qk(T,$);case C.ZodTuple:return ak(T,$);case C.ZodRecord:return _F(T,$);case C.ZodLiteral:return mk(T,$);case C.ZodEnum:return Zk(T);case C.ZodNativeEnum:return Pk(T);case C.ZodNullable:return tk(T,$);case C.ZodOptional:return dk(T,$);case C.ZodMap:return vk(T,$);case C.ZodSet:return rk(T,$);case C.ZodLazy:return s(T.getter()._def,$);case C.ZodPromise:return lk(T,$);case C.ZodNaN:case C.ZodNever:return nk();case C.ZodEffects:return bk(T,$);case C.ZodAny:return Lk();case C.ZodUnknown:return sk();case C.ZodDefault:return Ik(T,$);case C.ZodBranded:return GF(T,$);case C.ZodReadonly:return TX(T,$);case C.ZodCatch:return jk(T,$);case C.ZodPipeline:return uk(T,$);case C.ZodFunction:case C.ZodVoid:case C.ZodSymbol:return;default:return((f)=>{return})(S)}},cY=(T,S,$)=>{if(T.description){if($.description=T.description,S.markdownDescription)$.markdownDescription=T.description}return $};var SX=(T,S)=>{let $=yk(S),f=typeof S==="object"&&S.definitions?Object.entries(S.definitions).reduce((A,[k,X])=>({...A,[k]:s(X._def,{...$,currentPath:[...$.basePath,$.definitionPath,k]},!0)??{}}),{}):void 0,M=typeof S==="string"?S:S?.nameStrategy==="title"?void 0:S?.name,J=s(T._def,M===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,M]},!1)??{},F=typeof S==="object"&&S.name!==void 0&&S.nameStrategy==="title"?S.name:void 0;if(F!==void 0)J.title=F;let W=M===void 0?f?{...J,[$.definitionPath]:f}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,M].join("/"),[$.definitionPath]:{...f,[M]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09")W.$schema="https://json-schema.org/draft/2019-09/schema#";return W};var $X=SX;function fX(T,S){return function $({schema:f,fallback:M}){let J=$X(f);return async function F(W,A=3){let k,X=[];while(X.length<A){k=await T(W,J,M,X);let w=f.safeParse(k);if(w.success)return w.data;S?.warn(`safegen failed to generate well-formed data.
4
14
  `,`Here's what was returned last time:
5
- `,JSON.stringify(k,null," "),`
15
+ `,JSON.stringify(k,null,"\t"),`
6
16
  `,`Here's the error message from zod:
7
- `,y.error.toString()),X.push({response:k,error:y.error})}return S?.error(`safegen was unable to generate well-formed data after ${A} failed attempts.`),M}}}function SX(T){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(T,null,2)].join(`
8
- `)}import{createHash as r6}from"crypto";var GF="RFC3986",zF={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},$X="RFC1738";var ow=Array.isArray,X$=(()=>{let T=[];for(let S=0;S<256;++S)T.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return T})();var z0=1024,fX=(T,S,$,f,M)=>{if(T.length===0)return T;let J=T;if(typeof T==="symbol")J=Symbol.prototype.toString.call(T);else if(typeof T!=="string")J=String(T);if($==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(W){return"%26%23"+parseInt(W.slice(2),16)+"%3B"});let F="";for(let W=0;W<J.length;W+=z0){let A=J.length>=z0?J.slice(W,W+z0):J,k=[];for(let X=0;X<A.length;++X){let y=A.charCodeAt(X);if(y===45||y===46||y===95||y===126||y>=48&&y<=57||y>=65&&y<=90||y>=97&&y<=122||M===$X&&(y===40||y===41)){k[k.length]=A.charAt(X);continue}if(y<128){k[k.length]=X$[y];continue}if(y<2048){k[k.length]=X$[192|y>>6]+X$[128|y&63];continue}if(y<55296||y>=57344){k[k.length]=X$[224|y>>12]+X$[128|y>>6&63]+X$[128|y&63];continue}X+=1,y=65536+((y&1023)<<10|A.charCodeAt(X)&1023),k[k.length]=X$[240|y>>18]+X$[128|y>>12&63]+X$[128|y>>6&63]+X$[128|y&63]}F+=k.join("")}return F};function MX(T){if(!T||typeof T!=="object")return!1;return!!(T.constructor&&T.constructor.isBuffer&&T.constructor.isBuffer(T))}function _0(T,S){if(ow(T)){let $=[];for(let f=0;f<T.length;f+=1)$.push(S(T[f]));return $}return S(T)}var gw=Object.prototype.hasOwnProperty,JX={brackets(T){return String(T)+"[]"},comma:"comma",indices(T,S){return String(T)+"["+S+"]"},repeat(T){return String(T)}},y$=Array.isArray,tw=Array.prototype.push,FX=function(T,S){tw.apply(T,y$(S)?S:[S])},pw=Date.prototype.toISOString,dT={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fX,encodeValuesOnly:!1,format:GF,formatter:zF[GF],indices:!1,serializeDate(T){return pw.call(T)},skipNulls:!1,strictNullHandling:!1};function iw(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}var H0={};function WX(T,S,$,f,M,J,F,W,A,k,X,y,K,G,z,Q,E,B){let L=T,b=B,C=0,D=!1;while((b=b.get(H0))!==void 0&&!D){let O=b.get(T);if(C+=1,typeof O!=="undefined")if(O===C)throw new RangeError("Cyclic object value");else D=!0;if(typeof b.get(H0)==="undefined")C=0}if(typeof k==="function")L=k(S,L);else if(L instanceof Date)L=K?.(L);else if($==="comma"&&y$(L))L=_0(L,function(O){if(O instanceof Date)return K?.(O);return O});if(L===null){if(J)return A&&!Q?A(S,dT.encoder,E,"key",G):S;L=""}if(iw(L)||MX(L)){if(A){let O=Q?S:A(S,dT.encoder,E,"key",G);return[z?.(O)+"="+z?.(A(L,dT.encoder,E,"value",G))]}return[z?.(S)+"="+z?.(String(L))]}let H=[];if(typeof L==="undefined")return H;let U;if($==="comma"&&y$(L)){if(Q&&A)L=_0(L,A);U=[{value:L.length>0?L.join(",")||null:void 0}]}else if(y$(k))U=k;else{let O=Object.keys(L);U=X?O.sort(X):O}let Z=W?String(S).replace(/\./g,"%2E"):String(S),h=f&&y$(L)&&L.length===1?Z+"[]":Z;if(M&&y$(L)&&L.length===0)return h+"[]";for(let O=0;O<U.length;++O){let o=U[O],P=typeof o==="object"&&typeof o.value!=="undefined"?o.value:L[o];if(F&&P===null)continue;let a=y&&W?o.replace(/\./g,"%2E"):o,MT=y$(L)?typeof $==="function"?$(h,a):h:h+(y?"."+a:"["+a+"]");B.set(T,C);let fT=new WeakMap;fT.set(H0,B),FX(H,WX(P,MT,$,f,M,J,F,W,$==="comma"&&Q&&y$(L)?null:A,k,X,y,K,G,z,Q,E,fT))}return H}function lw(T=dT){if(typeof T.allowEmptyArrays!=="undefined"&&typeof T.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof T.encodeDotInKeys!=="undefined"&&typeof T.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(T.encoder!==null&&typeof T.encoder!=="undefined"&&typeof T.encoder!=="function")throw new TypeError("Encoder has to be a function.");let S=T.charset||dT.charset;if(typeof T.charset!=="undefined"&&T.charset!=="utf-8"&&T.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let $=GF;if(typeof T.format!=="undefined"){if(!gw.call(zF,T.format))throw new TypeError("Unknown format option provided.");$=T.format}let f=zF[$],M=dT.filter;if(typeof T.filter==="function"||y$(T.filter))M=T.filter;let J;if(T.arrayFormat&&T.arrayFormat in JX)J=T.arrayFormat;else if("indices"in T)J=T.indices?"indices":"repeat";else J=dT.arrayFormat;if("commaRoundTrip"in T&&typeof T.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let F=typeof T.allowDots==="undefined"?!!T.encodeDotInKeys===!0?!0:dT.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:dT.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:dT.allowEmptyArrays,arrayFormat:J,charset:S,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:dT.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?dT.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:dT.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:dT.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:dT.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:dT.encodeValuesOnly,filter:M,format:$,formatter:f,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:dT.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:dT.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:dT.strictNullHandling}}function D0(T,S={}){let $=T,f=lw(S),M,J;if(typeof f.filter==="function")J=f.filter,$=J("",$);else if(y$(f.filter))J=f.filter,M=J;let F=[];if(typeof $!=="object"||$===null)return"";let W=JX[f.arrayFormat],A=W==="comma"&&f.commaRoundTrip;if(!M)M=Object.keys($);if(f.sort)M.sort(f.sort);let k=new WeakMap;for(let K=0;K<M.length;++K){let G=M[K];if(f.skipNulls&&$[G]===null)continue;FX(F,WX($[G],G,W,A,f.allowEmptyArrays,f.strictNullHandling,f.skipNulls,f.encodeDotInKeys,f.encode?f.encoder:null,f.filter,f.sort,f.allowDots,f.serializeDate,f.format,f.formatter,f.encodeValuesOnly,f.charset,k))}let X=F.join(f.delimiter),y=f.addQueryPrefix===!0?"?":"";if(f.charsetSentinel)if(f.charset==="iso-8859-1")y+="utf8=%26%2310003%3B&";else y+="utf8=%E2%9C%93&";return X.length>0?y+X:""}var Mf="4.72.0";var AX=!1,Jf=void 0,E0=void 0,dw=void 0,rw=void 0,aw=void 0,Q0=void 0,ew=void 0,_F=void 0,U0=void 0,V0=void 0,B0=void 0,HF=void 0,L0=void 0;function kX(T,S={auto:!1}){if(AX)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(Jf)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${Jf}'\``);AX=S.auto,Jf=T.kind,E0=T.fetch,dw=T.Request,rw=T.Response,aw=T.Headers,Q0=T.FormData,ew=T.Blob,_F=T.File,U0=T.ReadableStream,V0=T.getMultipartRequestOptions,B0=T.getDefaultAgent,HF=T.fileFromPath,L0=T.isFsReadStream}class N0{constructor(T){this.body=T}get[Symbol.toStringTag](){return"MultipartBody"}}function XX({manuallyImported:T}={}){let S=T?"You may need to use polyfills":`Add one of these imports before your first \`import \u2026 from 'openai'\`:
9
- - \`import 'openai/shims/node'\` (if you're running on Node)
10
- - \`import 'openai/shims/web'\` (otherwise)
11
- `,$,f,M,J;try{$=fetch,f=Request,M=Response,J=Headers}catch(F){throw new Error(`this environment is missing the following Web Fetch API type: ${F.message}. ${S}`)}return{kind:"web",fetch:$,Request:f,Response:M,Headers:J,FormData:typeof FormData!=="undefined"?FormData:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${S}`)}},Blob:typeof Blob!=="undefined"?Blob:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${S}`)}},File:typeof File!=="undefined"?File:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${S}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class F{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${S}`)}},getMultipartRequestOptions:async(F,W)=>({...W,body:new N0(F)}),getDefaultAgent:(F)=>{return},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(F)=>!1}}import{ReadStream as T6}from"fs";function yX(){let T=XX();function S($){return $ instanceof T6}return{...T,isFsReadStream:S}}if(!Jf)kX(yX(),{auto:!0});class $T extends Error{}class gT extends $T{constructor(T,S,$,f){super(`${gT.makeMessage(T,S,$)}`);this.status=T,this.headers=f,this.request_id=f?.["x-request-id"];let M=S;this.error=M,this.code=M?.code,this.param=M?.param,this.type=M?.type}static makeMessage(T,S,$){let f=S?.message?typeof S.message==="string"?S.message:JSON.stringify(S.message):S?JSON.stringify(S):$;if(T&&f)return`${T} ${f}`;if(T)return`${T} status code (no body)`;if(f)return f;return"(no status code or body)"}static generate(T,S,$,f){if(!T)return new Ff({message:$,cause:CF(S)});let M=S?.error;if(T===400)return new DF(T,M,$,f);if(T===401)return new EF(T,M,$,f);if(T===403)return new QF(T,M,$,f);if(T===404)return new UF(T,M,$,f);if(T===409)return new VF(T,M,$,f);if(T===422)return new BF(T,M,$,f);if(T===429)return new LF(T,M,$,f);if(T>=500)return new NF(T,M,$,f);return new gT(T,M,$,f)}}class SS extends gT{constructor({message:T}={}){super(void 0,void 0,T||"Request was aborted.",void 0);this.status=void 0}}class Ff extends gT{constructor({message:T,cause:S}){super(void 0,void 0,T||"Connection error.",void 0);if(this.status=void 0,S)this.cause=S}}class Wf extends Ff{constructor({message:T}={}){super({message:T??"Request timed out."})}}class DF extends gT{constructor(){super(...arguments);this.status=400}}class EF extends gT{constructor(){super(...arguments);this.status=401}}class QF extends gT{constructor(){super(...arguments);this.status=403}}class UF extends gT{constructor(){super(...arguments);this.status=404}}class VF extends gT{constructor(){super(...arguments);this.status=409}}class BF extends gT{constructor(){super(...arguments);this.status=422}}class LF extends gT{constructor(){super(...arguments);this.status=429}}class NF extends gT{}class aM extends $T{constructor(){super("Could not parse response content as the length limit was reached")}}class eM extends $T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class g${constructor(){this.buffer=[],this.trailingCR=!1}decode(T){let S=this.decodeText(T);if(this.trailingCR)S="\r"+S,this.trailingCR=!1;if(S.endsWith("\r"))this.trailingCR=!0,S=S.slice(0,-1);if(!S)return[];let $=g$.NEWLINE_CHARS.has(S[S.length-1]||""),f=S.split(g$.NEWLINE_REGEXP);if($)f.pop();if(f.length===1&&!$)return this.buffer.push(f[0]),[];if(this.buffer.length>0)f=[this.buffer.join("")+f[0],...f.slice(1)],this.buffer=[];if(!$)this.buffer=[f.pop()||""];return f}decodeText(T){if(T==null)return"";if(typeof T==="string")return T;if(typeof Buffer!=="undefined"){if(T instanceof Buffer)return T.toString();if(T instanceof Uint8Array)return Buffer.from(T).toString();throw new $T(`Unexpected: received non-Uint8Array (${T.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder!=="undefined"){if(T instanceof Uint8Array||T instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(T);throw new $T(`Unexpected: received non-Uint8Array/ArrayBuffer (${T.constructor.name}) in a web platform. Please report this error.`)}throw new $T("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let T=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,T}}g$.NEWLINE_CHARS=new Set(["\n","\r"]);g$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class NS{constructor(T,S){this.iterator=T,this.controller=S}static fromSSEResponse(T,S){let $=!1;async function*f(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let M=!1;try{for await(let J of $6(T,S)){if(M)continue;if(J.data.startsWith("[DONE]")){M=!0;continue}if(J.event===null){let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(F&&F.error)throw new gT(void 0,F.error,void 0,void 0);yield F}else{let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(J.event=="error")throw new gT(void 0,F.error,F.message,void 0);yield{event:J.event,data:F}}}M=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!M)S.abort()}}return new NS(f,S)}static fromReadableStream(T,S){let $=!1;async function*f(){let J=new g$,F=wX(T);for await(let W of F)for(let A of J.decode(W))yield A;for(let W of J.flush())yield W}async function*M(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let J=!1;try{for await(let F of f()){if(J)continue;if(F)yield JSON.parse(F)}J=!0}catch(F){if(F instanceof Error&&F.name==="AbortError")return;throw F}finally{if(!J)S.abort()}}return new NS(M,S)}[Symbol.asyncIterator](){return this.iterator()}tee(){let T=[],S=[],$=this.iterator(),f=(M)=>{return{next:()=>{if(M.length===0){let J=$.next();T.push(J),S.push(J)}return M.shift()}}};return[new NS(()=>f(T),this.controller),new NS(()=>f(S),this.controller)]}toReadableStream(){let T=this,S,$=new TextEncoder;return new U0({async start(){S=T[Symbol.asyncIterator]()},async pull(f){try{let{value:M,done:J}=await S.next();if(J)return f.close();let F=$.encode(JSON.stringify(M)+"\n");f.enqueue(F)}catch(M){f.error(M)}},async cancel(){await S.return?.()}})}}async function*$6(T,S){if(!T.body)throw S.abort(),new $T("Attempted to iterate over a response with no body");let $=new KX,f=new g$,M=wX(T.body);for await(let J of f6(M))for(let F of f.decode(J)){let W=$.decode(F);if(W)yield W}for(let J of f.flush()){let F=$.decode(J);if(F)yield F}}async function*f6(T){let S=new Uint8Array;for await(let $ of T){if($==null)continue;let f=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,M=new Uint8Array(S.length+f.length);M.set(S),M.set(f,S.length),S=M;let J;while((J=M6(S))!==-1)yield S.slice(0,J),S=S.slice(J)}if(S.length>0)yield S}function M6(T){for(let f=0;f<T.length-2;f++){if(T[f]===10&&T[f+1]===10)return f+2;if(T[f]===13&&T[f+1]===13)return f+2;if(T[f]===13&&T[f+1]===10&&f+3<T.length&&T[f+2]===13&&T[f+3]===10)return f+4}return-1}class KX{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(T){if(T.endsWith("\r"))T=T.substring(0,T.length-1);if(!T){if(!this.event&&!this.data.length)return null;let M={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],M}if(this.chunks.push(T),T.startsWith(":"))return null;let[S,$,f]=J6(T,":");if(f.startsWith(" "))f=f.substring(1);if(S==="event")this.event=f;else if(S==="data")this.data.push(f);return null}}function J6(T,S){let $=T.indexOf(S);if($!==-1)return[T.substring(0,$),S,T.substring($+S.length)];return[T,"",""]}function wX(T){if(T[Symbol.asyncIterator])return T;let S=T.getReader();return{async next(){try{let $=await S.read();if($?.done)S.releaseLock();return $}catch($){throw S.releaseLock(),$}},async return(){let $=S.cancel();return S.releaseLock(),await $,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var YX=(T)=>T!=null&&typeof T==="object"&&typeof T.url==="string"&&typeof T.blob==="function",RX=(T)=>T!=null&&typeof T==="object"&&typeof T.name==="string"&&typeof T.lastModified==="number"&&sM(T),sM=(T)=>T!=null&&typeof T==="object"&&typeof T.size==="number"&&typeof T.type==="string"&&typeof T.text==="function"&&typeof T.slice==="function"&&typeof T.arrayBuffer==="function",F6=(T)=>{return RX(T)||YX(T)||L0(T)};async function j0(T,S,$){if(T=await T,RX(T))return T;if(YX(T)){let M=await T.blob();S||(S=new URL(T.url).pathname.split(/[\\/]/).pop()??"unknown_file");let J=sM(M)?[await M.arrayBuffer()]:[M];return new _F(J,S,$)}let f=await W6(T);if(S||(S=k6(T)??"unknown_file"),!$?.type){let M=f[0]?.type;if(typeof M==="string")$={...$,type:M}}return new _F(f,S,$)}async function W6(T){let S=[];if(typeof T==="string"||ArrayBuffer.isView(T)||T instanceof ArrayBuffer)S.push(T);else if(sM(T))S.push(await T.arrayBuffer());else if(X6(T))for await(let $ of T)S.push($);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${A6(T)}`);return S}function A6(T){return`[${Object.getOwnPropertyNames(T).map(($)=>`"${$}"`).join(", ")}]`}function k6(T){return C0(T.name)||C0(T.filename)||C0(T.path)?.split(/[\\/]/).pop()}var C0=(T)=>{if(typeof T==="string")return T;if(typeof Buffer!=="undefined"&&T instanceof Buffer)return String(T);return},X6=(T)=>T!=null&&typeof T==="object"&&typeof T[Symbol.asyncIterator]==="function",I0=(T)=>T&&typeof T==="object"&&T.body&&T[Symbol.toStringTag]==="MultipartBody";var vS=async(T)=>{let S=await OX(T.body);return V0(S,T)},OX=async(T)=>{let S=new Q0;return await Promise.all(Object.entries(T||{}).map(([$,f])=>x0(S,$,f))),S};var x0=async(T,S,$)=>{if($===void 0)return;if($==null)throw new TypeError(`Received null for "${S}"; to pass null in FormData, you must use the string 'null'`);if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")T.append(S,String($));else if(F6($)){let f=await j0($);T.append(S,f)}else if(Array.isArray($))await Promise.all($.map((f)=>x0(T,S+"[]",f)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([f,M])=>x0(T,`${S}[${f}]`,M)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};var K6=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},w6=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},xF;async function EX(T){let{response:S}=T;if(T.options.stream){if(ef("response",S.status,S.url,S.headers,S.body),T.options.__streamClass)return T.options.__streamClass.fromSSEResponse(S,T.controller);return NS.fromSSEResponse(S,T.controller)}if(S.status===204)return null;if(T.options.__binaryResponse)return S;let $=S.headers.get("content-type");if($?.includes("application/json")||$?.includes("application/vnd.api+json")){let J=await S.json();return ef("response",S.status,S.url,S.headers,J),QX(J,S)}let M=await S.text();return ef("response",S.status,S.url,S.headers,M),M}function QX(T,S){if(!T||typeof T!=="object"||Array.isArray(T))return T;return Object.defineProperty(T,"_request_id",{value:S.headers.get("x-request-id"),enumerable:!1})}class jF extends Promise{constructor(T,S=EX){super(($)=>{$(null)});this.responsePromise=T,this.parseResponse=S}_thenUnwrap(T){return new jF(this.responsePromise,async(S)=>QX(T(await this.parseResponse(S),S),S.response))}asResponse(){return this.responsePromise.then((T)=>T.response)}async withResponse(){let[T,S]=await Promise.all([this.parse(),this.asResponse()]);return{data:T,response:S,request_id:S.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(T,S){return this.parse().then(T,S)}catch(T){return this.parse().catch(T)}finally(T){return this.parse().finally(T)}}class q0{constructor({baseURL:T,maxRetries:S=2,timeout:$=600000,httpAgent:f,fetch:M}){this.baseURL=T,this.maxRetries=b0("maxRetries",S),this.timeout=b0("timeout",$),this.httpAgent=f,this.fetch=M??E0}authHeaders(T){return{}}defaultHeaders(T){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...z6(),...this.authHeaders(T)}}validateHeaders(T,S){}defaultIdempotencyKey(){return`stainless-node-retry-${E6()}`}get(T,S){return this.methodRequest("get",T,S)}post(T,S){return this.methodRequest("post",T,S)}patch(T,S){return this.methodRequest("patch",T,S)}put(T,S){return this.methodRequest("put",T,S)}delete(T,S){return this.methodRequest("delete",T,S)}methodRequest(T,S,$){return this.request(Promise.resolve($).then(async(f)=>{let M=f&&sM(f?.body)?new DataView(await f.body.arrayBuffer()):f?.body instanceof DataView?f.body:f?.body instanceof ArrayBuffer?new DataView(f.body):f&&ArrayBuffer.isView(f?.body)?new DataView(f.body.buffer):f?.body;return{method:T,path:S,...f,body:M}}))}getAPIList(T,S,$){return this.requestAPIList(S,{method:"get",path:T,...$})}calculateContentLength(T){if(typeof T==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(T,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(T).length.toString()}else if(ArrayBuffer.isView(T))return T.byteLength.toString();return null}buildRequest(T,{retryCount:S=0}={}){let{method:$,path:f,query:M,headers:J={}}=T,F=ArrayBuffer.isView(T.body)||T.__binaryRequest&&typeof T.body==="string"?T.body:I0(T.body)?T.body.body:T.body?JSON.stringify(T.body,null,2):null,W=this.calculateContentLength(F),A=this.buildURL(f,M);if("timeout"in T)b0("timeout",T.timeout);let k=T.timeout??this.timeout,X=T.httpAgent??this.httpAgent??B0(A),y=k+1000;if(typeof X?.options?.timeout==="number"&&y>(X.options.timeout??0))X.options.timeout=y;if(this.idempotencyHeader&&$!=="get"){if(!T.idempotencyKey)T.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=T.idempotencyKey}let K=this.buildHeaders({options:T,headers:J,contentLength:W,retryCount:S});return{req:{method:$,...F&&{body:F},headers:K,...X&&{agent:X},signal:T.signal??null},url:A,timeout:k}}buildHeaders({options:T,headers:S,contentLength:$,retryCount:f}){let M={};if($)M["content-length"]=$;let J=this.defaultHeaders(T);if(HX(M,J),HX(M,S),I0(T.body)&&Jf!=="node")delete M["content-type"];if(DX(J,"x-stainless-retry-count")===void 0&&DX(S,"x-stainless-retry-count")===void 0)M["x-stainless-retry-count"]=String(f);return this.validateHeaders(M,S),M}async prepareOptions(T){}async prepareRequest(T,{url:S,options:$}){}parseHeaders(T){return!T?{}:(Symbol.iterator in T)?Object.fromEntries(Array.from(T).map((S)=>[...S])):{...T}}makeStatusError(T,S,$,f){return gT.generate(T,S,$,f)}request(T,S=null){return new jF(this.makeRequest(T,S))}async makeRequest(T,S){let $=await T,f=$.maxRetries??this.maxRetries;if(S==null)S=f;await this.prepareOptions($);let{req:M,url:J,timeout:F}=this.buildRequest($,{retryCount:f-S});if(await this.prepareRequest(M,{url:J,options:$}),ef("request",J,$,M.headers),$.signal?.aborted)throw new SS;let W=new AbortController,A=await this.fetchWithTimeout(J,M,F,W).catch(CF);if(A instanceof Error){if($.signal?.aborted)throw new SS;if(S)return this.retryRequest($,S);if(A.name==="AbortError")throw new Wf;throw new Ff({cause:A})}let k=Y6(A.headers);if(!A.ok){if(S&&this.shouldRetry(A)){let Q=`retrying, ${S} attempts remaining`;return ef(`response (error; ${Q})`,A.status,J,k),this.retryRequest($,S,k)}let X=await A.text().catch((Q)=>CF(Q).message),y=_6(X),K=y?void 0:X;throw ef(`response (error; ${S?"(error; no more retries left)":"(error; not retryable)"})`,A.status,J,k,K),this.makeStatusError(A.status,y,K,k)}return{response:A,options:$,controller:W}}requestAPIList(T,S){let $=this.makeRequest(S,null);return new UX(this,$,T)}buildURL(T,S){let $=D6(T)?new URL(T):new URL(this.baseURL+(this.baseURL.endsWith("/")&&T.startsWith("/")?T.slice(1):T)),f=this.defaultQuery();if(!VX(f))S={...f,...S};if(typeof S==="object"&&S&&!Array.isArray(S))$.search=this.stringifyQuery(S);return $.toString()}stringifyQuery(T){return Object.entries(T).filter(([S,$])=>typeof $!=="undefined").map(([S,$])=>{if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return`${encodeURIComponent(S)}=${encodeURIComponent($)}`;if($===null)return`${encodeURIComponent(S)}=`;throw new $T(`Cannot stringify type ${typeof $}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(T,S,$,f){let{signal:M,...J}=S||{};if(M)M.addEventListener("abort",()=>f.abort());let F=setTimeout(()=>f.abort(),$);return this.getRequestClient().fetch.call(void 0,T,{signal:f.signal,...J}).finally(()=>{clearTimeout(F)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(T){let S=T.headers.get("x-should-retry");if(S==="true")return!0;if(S==="false")return!1;if(T.status===408)return!0;if(T.status===409)return!0;if(T.status===429)return!0;if(T.status>=500)return!0;return!1}async retryRequest(T,S,$){let f,M=$?.["retry-after-ms"];if(M){let F=parseFloat(M);if(!Number.isNaN(F))f=F}let J=$?.["retry-after"];if(J&&!f){let F=parseFloat(J);if(!Number.isNaN(F))f=F*1000;else f=Date.parse(J)-Date.now()}if(!(f&&0<=f&&f<60000)){let F=T.maxRetries??this.maxRetries;f=this.calculateDefaultRetryTimeoutMillis(S,F)}return await D$(f),this.makeRequest(T,S-1)}calculateDefaultRetryTimeoutMillis(T,S){let M=S-T,J=Math.min(0.5*Math.pow(2,M),8),F=1-Math.random()*0.25;return J*F*1000}getUserAgent(){return`${this.constructor.name}/JS ${Mf}`}}class IF{constructor(T,S,$,f){xF.set(this,void 0),K6(this,xF,T,"f"),this.options=f,this.response=S,this.body=$}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let T=this.nextPageInfo();if(!T)throw new $T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let S={...this.options};if("params"in T&&typeof S.query==="object")S.query={...S.query,...T.params};else if("url"in T){let $=[...Object.entries(S.query||{}),...T.url.searchParams.entries()];for(let[f,M]of $)T.url.searchParams.set(f,M);S.query=void 0,S.path=T.url.toString()}return await w6(this,xF,"f").requestAPIList(this.constructor,S)}async*iterPages(){let T=this;yield T;while(T.hasNextPage())T=await T.getNextPage(),yield T}async*[(xF=new WeakMap,Symbol.asyncIterator)](){for await(let T of this.iterPages())for(let S of T.getPaginatedItems())yield S}}class UX extends jF{constructor(T,S,$){super(S,async(f)=>new $(T,f.response,await EX(f),f.options))}async*[Symbol.asyncIterator](){let T=await this;for await(let S of T)yield S}}var Y6=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get(S,$){let f=$.toString();return S[f.toLowerCase()]||S[f]}})},R6={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},LT=(T)=>{return typeof T==="object"&&T!==null&&!VX(T)&&Object.keys(T).every((S)=>BX(R6,S))},O6=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Mf,"X-Stainless-OS":zX(Deno.build.os),"X-Stainless-Arch":GX(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime!=="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Mf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process!=="undefined"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Mf,"X-Stainless-OS":zX(process.platform),"X-Stainless-Arch":GX(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let T=G6();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Mf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${T.browser}`,"X-Stainless-Runtime-Version":T.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Mf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function G6(){if(typeof navigator==="undefined"||!navigator)return null;let T=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:S,pattern:$}of T){let f=$.exec(navigator.userAgent);if(f){let M=f[1]||0,J=f[2]||0,F=f[3]||0;return{browser:S,version:`${M}.${J}.${F}`}}}return null}var GX=(T)=>{if(T==="x32")return"x32";if(T==="x86_64"||T==="x64")return"x64";if(T==="arm")return"arm";if(T==="aarch64"||T==="arm64")return"arm64";if(T)return`other:${T}`;return"unknown"},zX=(T)=>{if(T=T.toLowerCase(),T.includes("ios"))return"iOS";if(T==="android")return"Android";if(T==="darwin")return"MacOS";if(T==="win32")return"Windows";if(T==="freebsd")return"FreeBSD";if(T==="openbsd")return"OpenBSD";if(T==="linux")return"Linux";if(T)return`Other:${T}`;return"Unknown"},_X,z6=()=>{return _X??(_X=O6())},_6=(T)=>{try{return JSON.parse(T)}catch(S){return}},H6=new RegExp("^(?:[a-z]+:)?//","i"),D6=(T)=>{return H6.test(T)},D$=(T)=>new Promise((S)=>setTimeout(S,T)),b0=(T,S)=>{if(typeof S!=="number"||!Number.isInteger(S))throw new $T(`${T} must be an integer`);if(S<0)throw new $T(`${T} must be a positive integer`);return S},CF=(T)=>{if(T instanceof Error)return T;if(typeof T==="object"&&T!==null)try{return new Error(JSON.stringify(T))}catch{}return new Error(T)};var TJ=(T)=>{if(typeof process!=="undefined")return process.env?.[T]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(T)?.trim();return};function VX(T){if(!T)return!0;for(let S in T)return!1;return!0}function BX(T,S){return Object.prototype.hasOwnProperty.call(T,S)}function HX(T,S){for(let $ in S){if(!BX(S,$))continue;let f=$.toLowerCase();if(!f)continue;let M=S[$];if(M===null)delete T[f];else if(M!==void 0)T[f]=M}}function ef(T,...S){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true")console.log(`OpenAI:DEBUG:${T}`,...S)}var E6=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(T)=>{let S=Math.random()*16|0;return(T==="x"?S:S&3|8).toString(16)})},LX=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},Q6=(T)=>{return typeof T?.get==="function"};var DX=(T,S)=>{let $=S.toLowerCase();if(Q6(T)){let f=S[0]?.toUpperCase()+S.substring(1).replace(/([^\w])(\w)/g,(M,J,F)=>J+F.toUpperCase());for(let M of[S,$,S.toUpperCase(),f]){let J=T.get(M);if(J)return J}}for(let[f,M]of Object.entries(T))if(f.toLowerCase()===$){if(Array.isArray(M)){if(M.length<=1)return M[0];return console.warn(`Received ${M.length} entries for the ${S} header, using the first entry.`),M[0]}return M}return};function SJ(T){return T!=null&&typeof T==="object"&&!Array.isArray(T)}class Z0 extends IF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[],this.object=$.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class PT extends IF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){let T=this.nextPageInfo();if(!T)return null;if("params"in T)return T.params;let S=Object.fromEntries(T.url.searchParams);if(!Object.keys(S).length)return null;return S}nextPageInfo(){let T=this.getPaginatedItems();if(!T.length)return null;let S=T[T.length-1]?.id;if(!S)return null;return{params:{after:S}}}}class i{constructor(T){this._client=T}}class $J extends i{create(T,S){return this._client.post("/chat/completions",{body:T,...S,stream:T.stream??!1})}}class kf extends i{constructor(){super(...arguments);this.completions=new $J(this._client)}}kf.Completions=$J;class fJ extends i{create(T,S){return this._client.post("/audio/speech",{body:T,...S,__binaryResponse:!0})}}class MJ extends i{create(T,S){return this._client.post("/audio/transcriptions",vS({body:T,...S}))}}class JJ extends i{create(T,S){return this._client.post("/audio/translations",vS({body:T,...S}))}}class E$ extends i{constructor(){super(...arguments);this.transcriptions=new MJ(this._client),this.translations=new JJ(this._client),this.speech=new fJ(this._client)}}E$.Transcriptions=MJ;E$.Translations=JJ;E$.Speech=fJ;class Xf extends i{create(T,S){return this._client.post("/batches",{body:T,...S})}retrieve(T,S){return this._client.get(`/batches/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/batches",sf,{query:T,...S})}cancel(T,S){return this._client.post(`/batches/${T}/cancel`,S)}}class sf extends PT{}Xf.BatchesPage=sf;class TM extends i{create(T,S){return this._client.post("/assistants",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/assistants/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/assistants",FJ,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class FJ extends PT{}TM.AssistantsPage=FJ;function m0(T){return typeof T.parse==="function"}var t$=(T)=>{return T?.role==="assistant"},h0=(T)=>{return T?.role==="function"},v0=(T)=>{return T?.role==="tool"};var T$=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},mT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},P0,bF,qF,WJ,AJ,ZF,kJ,Q$,XJ,mF,hF,SM,NX;class yJ{constructor(){P0.add(this),this.controller=new AbortController,bF.set(this,void 0),qF.set(this,()=>{}),WJ.set(this,()=>{}),AJ.set(this,void 0),ZF.set(this,()=>{}),kJ.set(this,()=>{}),Q$.set(this,{}),XJ.set(this,!1),mF.set(this,!1),hF.set(this,!1),SM.set(this,!1),T$(this,bF,new Promise((T,S)=>{T$(this,qF,T,"f"),T$(this,WJ,S,"f")}),"f"),T$(this,AJ,new Promise((T,S)=>{T$(this,ZF,T,"f"),T$(this,kJ,S,"f")}),"f"),mT(this,bF,"f").catch(()=>{}),mT(this,AJ,"f").catch(()=>{})}_run(T){setTimeout(()=>{T().then(()=>{this._emitFinal(),this._emit("end")},mT(this,P0,"m",NX).bind(this))},0)}_connected(){if(this.ended)return;mT(this,qF,"f").call(this),this._emit("connect")}get ended(){return mT(this,XJ,"f")}get errored(){return mT(this,mF,"f")}get aborted(){return mT(this,hF,"f")}abort(){this.controller.abort()}on(T,S){return(mT(this,Q$,"f")[T]||(mT(this,Q$,"f")[T]=[])).push({listener:S}),this}off(T,S){let $=mT(this,Q$,"f")[T];if(!$)return this;let f=$.findIndex((M)=>M.listener===S);if(f>=0)$.splice(f,1);return this}once(T,S){return(mT(this,Q$,"f")[T]||(mT(this,Q$,"f")[T]=[])).push({listener:S,once:!0}),this}emitted(T){return new Promise((S,$)=>{if(T$(this,SM,!0,"f"),T!=="error")this.once("error",$);this.once(T,S)})}async done(){T$(this,SM,!0,"f"),await mT(this,AJ,"f")}_emit(T,...S){if(mT(this,XJ,"f"))return;if(T==="end")T$(this,XJ,!0,"f"),mT(this,ZF,"f").call(this);let $=mT(this,Q$,"f")[T];if($)mT(this,Q$,"f")[T]=$.filter((f)=>!f.once),$.forEach(({listener:f})=>f(...S));if(T==="abort"){let f=S[0];if(!mT(this,SM,"f")&&!$?.length)Promise.reject(f);mT(this,WJ,"f").call(this,f),mT(this,kJ,"f").call(this,f),this._emit("end");return}if(T==="error"){let f=S[0];if(!mT(this,SM,"f")&&!$?.length)Promise.reject(f);mT(this,WJ,"f").call(this,f),mT(this,kJ,"f").call(this,f),this._emit("end")}}_emitFinal(){}}bF=new WeakMap,qF=new WeakMap,WJ=new WeakMap,AJ=new WeakMap,ZF=new WeakMap,kJ=new WeakMap,Q$=new WeakMap,XJ=new WeakMap,mF=new WeakMap,hF=new WeakMap,SM=new WeakMap,P0=new WeakSet,NX=function T(S){if(T$(this,mF,!0,"f"),S instanceof Error&&S.name==="AbortError")S=new SS;if(S instanceof SS)return T$(this,hF,!0,"f"),this._emit("abort",S);if(S instanceof $T)return this._emit("error",S);if(S instanceof Error){let $=new $T(S.message);return $.cause=S,this._emit("error",$)}return this._emit("error",new $T(String(S)))};function n0(T){return T?.$brand==="auto-parseable-response-format"}function yf(T){return T?.$brand==="auto-parseable-tool"}function CX(T,S){if(!S||!c0(S))return{...T,choices:T.choices.map(($)=>({...$,message:{...$.message,parsed:null,tool_calls:$.message.tool_calls??[]}}))};return KJ(T,S)}function KJ(T,S){let $=T.choices.map((f)=>{if(f.finish_reason==="length")throw new aM;if(f.finish_reason==="content_filter")throw new eM;return{...f,message:{...f.message,tool_calls:f.message.tool_calls?.map((M)=>x6(S,M))??[],parsed:f.message.content&&!f.message.refusal?C6(S,f.message.content):null}}});return{...T,choices:$}}function C6(T,S){if(T.response_format?.type!=="json_schema")return null;if(T.response_format?.type==="json_schema"){if("$parseRaw"in T.response_format)return T.response_format.$parseRaw(S);return JSON.parse(S)}return null}function x6(T,S){let $=T.tools?.find((f)=>f.function?.name===S.function.name);return{...S,function:{...S.function,parsed_arguments:yf($)?$.$parseRaw(S.function.arguments):$?.function.strict?JSON.parse(S.function.arguments):null}}}function xX(T,S){if(!T)return!1;let $=T.tools?.find((f)=>f.function?.name===S.function.name);return yf($)||$?.function.strict||!1}function c0(T){if(n0(T.response_format))return!0;return T.tools?.some((S)=>yf(S)||S.type==="function"&&S.function.strict===!0)??!1}function jX(T){for(let S of T??[]){if(S.type!=="function")throw new $T(`Currently only \`function\` tool types support auto-parsing; Received \`${S.type}\``);if(S.function.strict!==!0)throw new $T(`The \`${S.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var DS=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},KS,o0,vF,g0,t0,p0,bX,i0,IX=10;class wJ extends yJ{constructor(){super(...arguments);KS.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(T){this._chatCompletions.push(T),this._emit("chatCompletion",T);let S=T.choices[0]?.message;if(S)this._addMessage(S);return T}_addMessage(T,S=!0){if(!("content"in T))T.content=null;if(this.messages.push(T),S){if(this._emit("message",T),(h0(T)||v0(T))&&T.content)this._emit("functionCallResult",T.content);else if(t$(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(t$(T)&&T.tool_calls){for(let $ of T.tool_calls)if($.type==="function")this._emit("functionCall",$.function)}}}async finalChatCompletion(){await this.done();let T=this._chatCompletions[this._chatCompletions.length-1];if(!T)throw new $T("stream ended without producing a ChatCompletion");return T}async finalContent(){return await this.done(),DS(this,KS,"m",o0).call(this)}async finalMessage(){return await this.done(),DS(this,KS,"m",vF).call(this)}async finalFunctionCall(){return await this.done(),DS(this,KS,"m",g0).call(this)}async finalFunctionCallResult(){return await this.done(),DS(this,KS,"m",t0).call(this)}async totalUsage(){return await this.done(),DS(this,KS,"m",p0).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let T=this._chatCompletions[this._chatCompletions.length-1];if(T)this._emit("finalChatCompletion",T);let S=DS(this,KS,"m",vF).call(this);if(S)this._emit("finalMessage",S);let $=DS(this,KS,"m",o0).call(this);if($)this._emit("finalContent",$);let f=DS(this,KS,"m",g0).call(this);if(f)this._emit("finalFunctionCall",f);let M=DS(this,KS,"m",t0).call(this);if(M!=null)this._emit("finalFunctionCallResult",M);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",DS(this,KS,"m",p0).call(this))}async _createChatCompletion(T,S,$){let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}DS(this,KS,"m",bX).call(this,S);let M=await T.chat.completions.create({...S,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(KJ(M,S))}async _runChatCompletion(T,S,$){for(let f of S.messages)this._addMessage(f,!1);return await this._createChatCompletion(T,S,$)}async _runFunctions(T,S,$){let{function_call:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.name,{maxChatCompletions:A=IX}=$||{},k={};for(let y of S.functions)k[y.name||y.function.name]=y;let X=S.functions.map((y)=>({name:y.name||y.function.name,parameters:y.parameters,description:y.description}));for(let y of S.messages)this._addMessage(y,!1);for(let y=0;y<A;++y){let G=(await this._createChatCompletion(T,{...F,function_call:M,functions:X,messages:[...this.messages]},$)).choices[0]?.message;if(!G)throw new $T("missing message in ChatCompletion response");if(!G.function_call)return;let{name:z,arguments:Q}=G.function_call,E=k[z];if(!E){let C=`Invalid function_call: ${JSON.stringify(z)}. Available options are: ${X.map((D)=>JSON.stringify(D.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:z,content:C});continue}else if(W&&W!==z){let C=`Invalid function_call: ${JSON.stringify(z)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"function",name:z,content:C});continue}let B;try{B=m0(E)?await E.parse(Q):Q}catch(C){this._addMessage({role:"function",name:z,content:C instanceof Error?C.message:String(C)});continue}let L=await E.function(B,this),b=DS(this,KS,"m",i0).call(this,L);if(this._addMessage({role:"function",name:z,content:b}),W)return}}async _runTools(T,S,$){let{tool_choice:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.function?.name,{maxChatCompletions:A=IX}=$||{},k=S.tools.map((K)=>{if(yf(K)){if(!K.$callback)throw new $T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:K.$callback,name:K.function.name,description:K.function.description||"",parameters:K.function.parameters,parse:K.$parseRaw,strict:!0}}}return K}),X={};for(let K of k)if(K.type==="function")X[K.function.name||K.function.function.name]=K.function;let y="tools"in S?k.map((K)=>K.type==="function"?{type:"function",function:{name:K.function.name||K.function.function.name,parameters:K.function.parameters,description:K.function.description,strict:K.function.strict}}:K):void 0;for(let K of S.messages)this._addMessage(K,!1);for(let K=0;K<A;++K){let z=(await this._createChatCompletion(T,{...F,tool_choice:M,tools:y,messages:[...this.messages]},$)).choices[0]?.message;if(!z)throw new $T("missing message in ChatCompletion response");if(!z.tool_calls?.length)return;for(let Q of z.tool_calls){if(Q.type!=="function")continue;let E=Q.id,{name:B,arguments:L}=Q.function,b=X[B];if(!b){let U=`Invalid tool_call: ${JSON.stringify(B)}. Available options are: ${Object.keys(X).map((Z)=>JSON.stringify(Z)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:E,content:U});continue}else if(W&&W!==B){let U=`Invalid tool_call: ${JSON.stringify(B)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:E,content:U});continue}let C;try{C=m0(b)?await b.parse(L):L}catch(U){let Z=U instanceof Error?U.message:String(U);this._addMessage({role:"tool",tool_call_id:E,content:Z});continue}let D=await b.function(C,this),H=DS(this,KS,"m",i0).call(this,D);if(this._addMessage({role:"tool",tool_call_id:E,content:H}),W)return}}return}}KS=new WeakSet,o0=function T(){return DS(this,KS,"m",vF).call(this).content??null},vF=function T(){let S=this.messages.length;while(S-- >0){let $=this.messages[S];if(t$($)){let{function_call:f,...M}=$,J={...M,content:$.content??null,refusal:$.refusal??null};if(f)J.function_call=f;return J}}throw new $T("stream ended without producing a ChatCompletionMessage with role=assistant")},g0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(t$($)&&$?.function_call)return $.function_call;if(t$($)&&$?.tool_calls?.length)return $.tool_calls.at(-1)?.function}return},t0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(h0($)&&$.content!=null)return $.content;if(v0($)&&$.content!=null&&typeof $.content==="string"&&this.messages.some((f)=>f.role==="assistant"&&f.tool_calls?.some((M)=>M.type==="function"&&M.id===$.tool_call_id)))return $.content}return},p0=function T(){let S={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:$}of this._chatCompletions)if($)S.completion_tokens+=$.completion_tokens,S.prompt_tokens+=$.prompt_tokens,S.total_tokens+=$.total_tokens;return S},bX=function T(S){if(S.n!=null&&S.n>1)throw new $T("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},i0=function T(S){return typeof S==="string"?S:S===void 0?"undefined":JSON.stringify(S)};class $M extends wJ{static runFunctions(T,S,$){let f=new $M,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){let f=new $M,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}_addMessage(T,S=!0){if(super._addMessage(T,S),t$(T)&&T.content)this._emit("content",T.content)}}var sT={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class qX extends Error{}class ZX extends Error{}function j6(T,S=sT.ALL){if(typeof T!=="string")throw new TypeError(`expecting str, got ${typeof T}`);if(!T.trim())throw new Error(`${T} is empty`);return I6(T.trim(),S)}var I6=(T,S)=>{let $=T.length,f=0,M=(K)=>{throw new qX(`${K} at position ${f}`)},J=(K)=>{throw new ZX(`${K} at position ${f}`)},F=()=>{if(y(),f>=$)M("Unexpected end of input");if(T[f]==='"')return W();if(T[f]==="{")return A();if(T[f]==="[")return k();if(T.substring(f,f+4)==="null"||sT.NULL&S&&$-f<4&&"null".startsWith(T.substring(f)))return f+=4,null;if(T.substring(f,f+4)==="true"||sT.BOOL&S&&$-f<4&&"true".startsWith(T.substring(f)))return f+=4,!0;if(T.substring(f,f+5)==="false"||sT.BOOL&S&&$-f<5&&"false".startsWith(T.substring(f)))return f+=5,!1;if(T.substring(f,f+8)==="Infinity"||sT.INFINITY&S&&$-f<8&&"Infinity".startsWith(T.substring(f)))return f+=8,1/0;if(T.substring(f,f+9)==="-Infinity"||sT.MINUS_INFINITY&S&&1<$-f&&$-f<9&&"-Infinity".startsWith(T.substring(f)))return f+=9,-1/0;if(T.substring(f,f+3)==="NaN"||sT.NAN&S&&$-f<3&&"NaN".startsWith(T.substring(f)))return f+=3,NaN;return X()},W=()=>{let K=f,G=!1;f++;while(f<$&&(T[f]!=='"'||G&&T[f-1]==="\\"))G=T[f]==="\\"?!G:!1,f++;if(T.charAt(f)=='"')try{return JSON.parse(T.substring(K,++f-Number(G)))}catch(z){J(String(z))}else if(sT.STR&S)try{return JSON.parse(T.substring(K,f-Number(G))+'"')}catch(z){return JSON.parse(T.substring(K,T.lastIndexOf("\\"))+'"')}M("Unterminated string literal")},A=()=>{f++,y();let K={};try{while(T[f]!=="}"){if(y(),f>=$&&sT.OBJ&S)return K;let G=W();y(),f++;try{let z=F();Object.defineProperty(K,G,{value:z,writable:!0,enumerable:!0,configurable:!0})}catch(z){if(sT.OBJ&S)return K;else throw z}if(y(),T[f]===",")f++}}catch(G){if(sT.OBJ&S)return K;else M("Expected '}' at end of object")}return f++,K},k=()=>{f++;let K=[];try{while(T[f]!=="]")if(K.push(F()),y(),T[f]===",")f++}catch(G){if(sT.ARR&S)return K;M("Expected ']' at end of array")}return f++,K},X=()=>{if(f===0){if(T==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T)}catch(G){if(sT.NUM&S)try{if(T[T.length-1]===".")return JSON.parse(T.substring(0,T.lastIndexOf(".")));return JSON.parse(T.substring(0,T.lastIndexOf("e")))}catch(z){}J(String(G))}}let K=f;if(T[f]==="-")f++;while(T[f]&&!",]}".includes(T[f]))f++;if(f==$&&!(sT.NUM&S))M("Unterminated number literal");try{return JSON.parse(T.substring(K,f))}catch(G){if(T.substring(K,f)==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T.substring(K,T.lastIndexOf("e")))}catch(z){J(String(z))}}},y=()=>{while(f<$&&" \n\r\t".includes(T[f]))f++};return F()},l0=(T)=>j6(T,sT.ALL^sT.NUM);var fM=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},DT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},rT,U$,MM,p$,u0,PF,d0,r0,a0,nF,e0,mX;class Kf extends wJ{constructor(T){super();rT.add(this),U$.set(this,void 0),MM.set(this,void 0),p$.set(this,void 0),fM(this,U$,T,"f"),fM(this,MM,[],"f")}get currentChatCompletionSnapshot(){return DT(this,p$,"f")}static fromReadableStream(T){let S=new Kf(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){let f=new Kf(S);return f._run(()=>f._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}async _createChatCompletion(T,S,$){super._createChatCompletion;let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}DT(this,rT,"m",u0).call(this);let M=await T.chat.completions.create({...S,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let J of M)DT(this,rT,"m",d0).call(this,J);if(M.controller.signal?.aborted)throw new SS;return this._addChatCompletion(DT(this,rT,"m",nF).call(this))}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}DT(this,rT,"m",u0).call(this),this._connected();let f=NS.fromReadableStream(T,this.controller),M;for await(let J of f){if(M&&M!==J.id)this._addChatCompletion(DT(this,rT,"m",nF).call(this));DT(this,rT,"m",d0).call(this,J),M=J.id}if(f.controller.signal?.aborted)throw new SS;return this._addChatCompletion(DT(this,rT,"m",nF).call(this))}[(U$=new WeakMap,MM=new WeakMap,p$=new WeakMap,rT=new WeakSet,u0=function T(){if(this.ended)return;fM(this,p$,void 0,"f")},PF=function T(S){let $=DT(this,MM,"f")[S.index];if($)return $;return $={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},DT(this,MM,"f")[S.index]=$,$},d0=function T(S){if(this.ended)return;let $=DT(this,rT,"m",mX).call(this,S);this._emit("chunk",S,$);for(let f of S.choices){let M=$.choices[f.index];if(f.delta.content!=null&&M.message?.role==="assistant"&&M.message?.content)this._emit("content",f.delta.content,M.message.content),this._emit("content.delta",{delta:f.delta.content,snapshot:M.message.content,parsed:M.message.parsed});if(f.delta.refusal!=null&&M.message?.role==="assistant"&&M.message?.refusal)this._emit("refusal.delta",{delta:f.delta.refusal,snapshot:M.message.refusal});if(f.logprobs?.content!=null&&M.message?.role==="assistant")this._emit("logprobs.content.delta",{content:f.logprobs?.content,snapshot:M.logprobs?.content??[]});if(f.logprobs?.refusal!=null&&M.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:f.logprobs?.refusal,snapshot:M.logprobs?.refusal??[]});let J=DT(this,rT,"m",PF).call(this,M);if(M.finish_reason){if(DT(this,rT,"m",a0).call(this,M),J.current_tool_call_index!=null)DT(this,rT,"m",r0).call(this,M,J.current_tool_call_index)}for(let F of f.delta.tool_calls??[]){if(J.current_tool_call_index!==F.index){if(DT(this,rT,"m",a0).call(this,M),J.current_tool_call_index!=null)DT(this,rT,"m",r0).call(this,M,J.current_tool_call_index)}J.current_tool_call_index=F.index}for(let F of f.delta.tool_calls??[]){let W=M.message.tool_calls?.[F.index];if(!W?.type)continue;if(W?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:W.function?.name,index:F.index,arguments:W.function.arguments,parsed_arguments:W.function.parsed_arguments,arguments_delta:F.function?.arguments??""});else vX(W?.type)}}},r0=function T(S,$){if(DT(this,rT,"m",PF).call(this,S).done_tool_calls.has($))return;let M=S.message.tool_calls?.[$];if(!M)throw new Error("no tool call snapshot");if(!M.type)throw new Error("tool call snapshot missing `type`");if(M.type==="function"){let J=DT(this,U$,"f")?.tools?.find((F)=>F.type==="function"&&F.function.name===M.function.name);this._emit("tool_calls.function.arguments.done",{name:M.function.name,index:$,arguments:M.function.arguments,parsed_arguments:yf(J)?J.$parseRaw(M.function.arguments):J?.function.strict?JSON.parse(M.function.arguments):null})}else vX(M.type)},a0=function T(S){let $=DT(this,rT,"m",PF).call(this,S);if(S.message.content&&!$.content_done){$.content_done=!0;let f=DT(this,rT,"m",e0).call(this);this._emit("content.done",{content:S.message.content,parsed:f?f.$parseRaw(S.message.content):null})}if(S.message.refusal&&!$.refusal_done)$.refusal_done=!0,this._emit("refusal.done",{refusal:S.message.refusal});if(S.logprobs?.content&&!$.logprobs_content_done)$.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:S.logprobs.content});if(S.logprobs?.refusal&&!$.logprobs_refusal_done)$.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:S.logprobs.refusal})},nF=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");let S=DT(this,p$,"f");if(!S)throw new $T("request ended without sending any chunks");return fM(this,p$,void 0,"f"),fM(this,MM,[],"f"),b6(S,DT(this,U$,"f"))},e0=function T(){let S=DT(this,U$,"f")?.response_format;if(n0(S))return S;return null},mX=function T(S){var $,f,M,J;let F=DT(this,p$,"f"),{choices:W,...A}=S;if(!F)F=fM(this,p$,{...A,choices:[]},"f");else Object.assign(F,A);for(let{delta:k,finish_reason:X,index:y,logprobs:K=null,...G}of S.choices){let z=F.choices[y];if(!z)z=F.choices[y]={finish_reason:X,index:y,message:{},logprobs:K,...G};if(K)if(!z.logprobs)z.logprobs=Object.assign({},K);else{let{content:D,refusal:H,...U}=K;if(hX(U),Object.assign(z.logprobs,U),D)($=z.logprobs).content??($.content=[]),z.logprobs.content.push(...D);if(H)(f=z.logprobs).refusal??(f.refusal=[]),z.logprobs.refusal.push(...H)}if(X){if(z.finish_reason=X,DT(this,U$,"f")&&c0(DT(this,U$,"f"))){if(X==="length")throw new aM;if(X==="content_filter")throw new eM}}if(Object.assign(z,G),!k)continue;let{content:Q,refusal:E,function_call:B,role:L,tool_calls:b,...C}=k;if(hX(C),Object.assign(z.message,C),E)z.message.refusal=(z.message.refusal||"")+E;if(L)z.message.role=L;if(B)if(!z.message.function_call)z.message.function_call=B;else{if(B.name)z.message.function_call.name=B.name;if(B.arguments)(M=z.message.function_call).arguments??(M.arguments=""),z.message.function_call.arguments+=B.arguments}if(Q){if(z.message.content=(z.message.content||"")+Q,!z.message.refusal&&DT(this,rT,"m",e0).call(this))z.message.parsed=l0(z.message.content)}if(b){if(!z.message.tool_calls)z.message.tool_calls=[];for(let{index:D,id:H,type:U,function:Z,...h}of b){let O=(J=z.message.tool_calls)[D]??(J[D]={});if(Object.assign(O,h),H)O.id=H;if(U)O.type=U;if(Z)O.function??(O.function={name:Z.name??"",arguments:""});if(Z?.name)O.function.name=Z.name;if(Z?.arguments){if(O.function.arguments+=Z.arguments,xX(DT(this,U$,"f"),O))O.function.parsed_arguments=l0(O.function.arguments)}}}}return F},Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("chunk",(f)=>{let M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function b6(T,S){let{id:$,choices:f,created:M,model:J,system_fingerprint:F,...W}=T,A={...W,id:$,choices:f.map(({message:k,finish_reason:X,index:y,logprobs:K,...G})=>{if(!X)throw new $T(`missing finish_reason for choice ${y}`);let{content:z=null,function_call:Q,tool_calls:E,...B}=k,L=k.role;if(!L)throw new $T(`missing role for choice ${y}`);if(Q){let{arguments:b,name:C}=Q;if(b==null)throw new $T(`missing function_call.arguments for choice ${y}`);if(!C)throw new $T(`missing function_call.name for choice ${y}`);return{...G,message:{content:z,function_call:{arguments:b,name:C},role:L,refusal:k.refusal??null},finish_reason:X,index:y,logprobs:K}}if(E)return{...G,index:y,finish_reason:X,logprobs:K,message:{...B,role:L,content:z,refusal:k.refusal??null,tool_calls:E.map((b,C)=>{let{function:D,type:H,id:U,...Z}=b,{arguments:h,name:O,...o}=D||{};if(U==null)throw new $T(`missing choices[${y}].tool_calls[${C}].id\n${cF(T)}`);if(H==null)throw new $T(`missing choices[${y}].tool_calls[${C}].type\n${cF(T)}`);if(O==null)throw new $T(`missing choices[${y}].tool_calls[${C}].function.name\n${cF(T)}`);if(h==null)throw new $T(`missing choices[${y}].tool_calls[${C}].function.arguments\n${cF(T)}`);return{...Z,id:U,type:H,function:{...o,name:O,arguments:h}}})}};return{...G,message:{...B,content:z,role:L,refusal:k.refusal??null},finish_reason:X,index:y,logprobs:K}}),created:M,model:J,object:"chat.completion",...F?{system_fingerprint:F}:{}};return CX(A,S)}function cF(T){return JSON.stringify(T)}function hX(T){return}function vX(T){}class wf extends Kf{static fromReadableStream(T){let S=new wf(null);return S._run(()=>S._fromReadableStream(T)),S}static runFunctions(T,S,$){let f=new wf(null),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){let f=new wf(S),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}}class oF extends i{parse(T,S){return jX(T.tools),this._client.chat.completions.create(T,{...S,headers:{...S?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(($)=>KJ($,T))}runFunctions(T,S){if(T.stream)return wf.runFunctions(this._client,T,S);return $M.runFunctions(this._client,T,S)}runTools(T,S){if(T.stream)return wf.runTools(this._client,T,S);return $M.runTools(this._client,T,S)}stream(T,S){return Kf.createChatCompletion(this._client,T,S)}}class YJ extends i{constructor(){super(...arguments);this.completions=new oF(this._client)}}(function(T){T.Completions=oF})(YJ||(YJ={}));var u=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},CS=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},$S,s0,K$,gF,S$,Rf,JM,Yf,iF,xS,tF,pF,GJ,RJ,OJ,PX,nX,cX,oX,gX,tX,pX;class jS extends yJ{constructor(){super(...arguments);$S.add(this),s0.set(this,[]),K$.set(this,{}),gF.set(this,{}),S$.set(this,void 0),Rf.set(this,void 0),JM.set(this,void 0),Yf.set(this,void 0),iF.set(this,void 0),xS.set(this,void 0),tF.set(this,void 0),pF.set(this,void 0),GJ.set(this,void 0)}[(s0=new WeakMap,K$=new WeakMap,gF=new WeakMap,S$=new WeakMap,Rf=new WeakMap,JM=new WeakMap,Yf=new WeakMap,iF=new WeakMap,xS=new WeakMap,tF=new WeakMap,pF=new WeakMap,GJ=new WeakMap,$S=new WeakSet,Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("event",(f)=>{let M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(T){let S=new jS;return S._run(()=>S._fromReadableStream(T)),S}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}this._connected();let f=NS.fromReadableStream(T,this.controller);for await(let M of f)u(this,$S,"m",RJ).call(this,M);if(f.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(T,S,$,f,M){let J=new jS;return J._run(()=>J._runToolAssistantStream(T,S,$,f,{...M,headers:{...M?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(T,S,$,f,M){let J=M?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let F={...f,stream:!0},W=await T.submitToolOutputs(S,$,F,{...M,signal:this.controller.signal});this._connected();for await(let A of W)u(this,$S,"m",RJ).call(this,A);if(W.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}static createThreadAssistantStream(T,S,$){let f=new jS;return f._run(()=>f._threadAssistantStream(T,S,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}static createAssistantStream(T,S,$,f){let M=new jS;return M._run(()=>M._runAssistantStream(T,S,$,{...f,headers:{...f?.headers,"X-Stainless-Helper-Method":"stream"}})),M}currentEvent(){return u(this,tF,"f")}currentRun(){return u(this,pF,"f")}currentMessageSnapshot(){return u(this,S$,"f")}currentRunStepSnapshot(){return u(this,GJ,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,K$,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,gF,"f"))}async finalRun(){if(await this.done(),!u(this,Rf,"f"))throw Error("Final run was not received.");return u(this,Rf,"f")}async _createThreadAssistantStream(T,S,$){let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}let M={...S,stream:!0},J=await T.createAndRun(M,{...$,signal:this.controller.signal});this._connected();for await(let F of J)u(this,$S,"m",RJ).call(this,F);if(J.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}async _createAssistantStream(T,S,$,f){let M=f?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}let J={...$,stream:!0},F=await T.create(S,J,{...f,signal:this.controller.signal});this._connected();for await(let W of F)u(this,$S,"m",RJ).call(this,W);if(F.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}static accumulateDelta(T,S){for(let[$,f]of Object.entries(S)){if(!T.hasOwnProperty($)){T[$]=f;continue}let M=T[$];if(M===null||M===void 0){T[$]=f;continue}if($==="index"||$==="type"){T[$]=f;continue}if(typeof M==="string"&&typeof f==="string")M+=f;else if(typeof M==="number"&&typeof f==="number")M+=f;else if(SJ(M)&&SJ(f))M=this.accumulateDelta(M,f);else if(Array.isArray(M)&&Array.isArray(f)){if(M.every((J)=>typeof J==="string"||typeof J==="number")){M.push(...f);continue}for(let J of f){if(!SJ(J))throw new Error(`Expected array delta entry to be an object but got: ${J}`);let F=J.index;if(F==null)throw console.error(J),new Error("Expected array delta entry to have an `index` property");if(typeof F!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${F}`);let W=M[F];if(W==null)M.push(J);else M[F]=this.accumulateDelta(W,J)}continue}else throw Error(`Unhandled record type: ${$}, deltaValue: ${f}, accValue: ${M}`);T[$]=M}return T}_addRun(T){return T}async _threadAssistantStream(T,S,$){return await this._createThreadAssistantStream(S,T,$)}async _runAssistantStream(T,S,$,f){return await this._createAssistantStream(S,T,$,f)}async _runToolAssistantStream(T,S,$,f,M){return await this._createToolAssistantStream($,T,S,f,M)}}RJ=function T(S){if(this.ended)return;switch(CS(this,tF,S,"f"),u(this,$S,"m",cX).call(this,S),S.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":u(this,$S,"m",pX).call(this,S);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":u(this,$S,"m",nX).call(this,S);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":u(this,$S,"m",PX).call(this,S);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},OJ=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");if(!u(this,Rf,"f"))throw Error("Final run has not been received");return u(this,Rf,"f")},PX=function T(S){let[$,f]=u(this,$S,"m",gX).call(this,S,u(this,S$,"f"));CS(this,S$,$,"f"),u(this,gF,"f")[$.id]=$;for(let M of f){let J=$.content[M.index];if(J?.type=="text")this._emit("textCreated",J.text)}switch(S.event){case"thread.message.created":this._emit("messageCreated",S.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",S.data.delta,$),S.data.delta.content)for(let M of S.data.delta.content){if(M.type=="text"&&M.text){let J=M.text,F=$.content[M.index];if(F&&F.type=="text")this._emit("textDelta",J,F.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(M.index!=u(this,JM,"f")){if(u(this,Yf,"f"))switch(u(this,Yf,"f").type){case"text":this._emit("textDone",u(this,Yf,"f").text,u(this,S$,"f"));break;case"image_file":this._emit("imageFileDone",u(this,Yf,"f").image_file,u(this,S$,"f"));break}CS(this,JM,M.index,"f")}CS(this,Yf,$.content[M.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,JM,"f")!==void 0){let M=S.data.content[u(this,JM,"f")];if(M)switch(M.type){case"image_file":this._emit("imageFileDone",M.image_file,u(this,S$,"f"));break;case"text":this._emit("textDone",M.text,u(this,S$,"f"));break}}if(u(this,S$,"f"))this._emit("messageDone",S.data);CS(this,S$,void 0,"f")}},nX=function T(S){let $=u(this,$S,"m",oX).call(this,S);switch(CS(this,GJ,$,"f"),S.event){case"thread.run.step.created":this._emit("runStepCreated",S.data);break;case"thread.run.step.delta":let f=S.data.delta;if(f.step_details&&f.step_details.type=="tool_calls"&&f.step_details.tool_calls&&$.step_details.type=="tool_calls")for(let J of f.step_details.tool_calls)if(J.index==u(this,iF,"f"))this._emit("toolCallDelta",J,$.step_details.tool_calls[J.index]);else{if(u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f"));if(CS(this,iF,J.index,"f"),CS(this,xS,$.step_details.tool_calls[J.index],"f"),u(this,xS,"f"))this._emit("toolCallCreated",u(this,xS,"f"))}this._emit("runStepDelta",S.data.delta,$);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(CS(this,GJ,void 0,"f"),S.data.step_details.type=="tool_calls"){if(u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f")),CS(this,xS,void 0,"f")}this._emit("runStepDone",S.data,$);break;case"thread.run.step.in_progress":break}},cX=function T(S){u(this,s0,"f").push(S),this._emit("event",S)},oX=function T(S){switch(S.event){case"thread.run.step.created":return u(this,K$,"f")[S.data.id]=S.data,S.data;case"thread.run.step.delta":let $=u(this,K$,"f")[S.data.id];if(!$)throw Error("Received a RunStepDelta before creation of a snapshot");let f=S.data;if(f.delta){let M=jS.accumulateDelta($,f.delta);u(this,K$,"f")[S.data.id]=M}return u(this,K$,"f")[S.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,K$,"f")[S.data.id]=S.data;break}if(u(this,K$,"f")[S.data.id])return u(this,K$,"f")[S.data.id];throw new Error("No snapshot available")},gX=function T(S,$){let f=[];switch(S.event){case"thread.message.created":return[S.data,f];case"thread.message.delta":if(!$)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let M=S.data;if(M.delta.content)for(let J of M.delta.content)if(J.index in $.content){let F=$.content[J.index];$.content[J.index]=u(this,$S,"m",tX).call(this,J,F)}else $.content[J.index]=J,f.push(J);return[$,f];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if($)return[$,f];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},tX=function T(S,$){return jS.accumulateDelta($,S)},pX=function T(S){switch(CS(this,pF,S.data,"f"),S.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":if(CS(this,Rf,S.data,"f"),u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f")),CS(this,xS,void 0,"f");break;case"thread.run.cancelling":break}};class FM extends i{create(T,S,$){return this._client.post(`/threads/${T}/messages`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/messages/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/messages`,zJ,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class zJ extends PT{}FM.MessagesPage=zJ;class WM extends i{retrieve(T,S,$,f={},M){if(LT(f))return this.retrieve(T,S,$,{},f);return this._client.get(`/threads/${T}/runs/${S}/steps/${$}`,{query:f,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers}})}list(T,S,$={},f){if(LT($))return this.list(T,S,{},$);return this._client.getAPIList(`/threads/${T}/runs/${S}/steps`,_J,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}}class _J extends PT{}WM.RunStepsPage=_J;class i$ extends i{constructor(){super(...arguments);this.steps=new WM(this._client)}create(T,S,$){let{include:f,...M}=S;return this._client.post(`/threads/${T}/runs`,{query:{include:f},body:M,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:S.stream??!1})}retrieve(T,S,$){return this._client.get(`/threads/${T}/runs/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/runs`,HJ,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/threads/${T}/runs/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S,$);return await this.poll(T,f.id,$)}createAndStream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:M,response:J}=await this.retrieve(T,S,{...$,headers:{...$?.headers,...f}}).withResponse();switch(M.status){case"queued":case"in_progress":case"cancelling":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=J.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return M}}}stream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}submitToolOutputs(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}/submit_tool_outputs`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers},stream:$.stream??!1})}async submitToolOutputsAndPoll(T,S,$,f){let M=await this.submitToolOutputs(T,S,$,f);return await this.poll(T,M.id,f)}submitToolOutputsStream(T,S,$,f){return jS.createToolAssistantStream(T,S,this._client.beta.threads.runs,$,f)}}class HJ extends PT{}i$.RunsPage=HJ;i$.Steps=WM;i$.RunStepsPage=_J;class V$ extends i{constructor(){super(...arguments);this.runs=new i$(this._client),this.messages=new FM(this._client)}create(T={},S){if(LT(T))return this.create({},T);return this._client.post("/threads",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/threads/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S){return this._client.delete(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}createAndRun(T,S){return this._client.post("/threads/runs",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers},stream:T.stream??!1})}async createAndRunPoll(T,S){let $=await this.createAndRun(T,S);return await this.runs.poll($.thread_id,$.id,S)}createAndRunStream(T,S){return jS.createThreadAssistantStream(T,this._client.beta.threads,S)}}V$.Runs=i$;V$.RunsPage=HJ;V$.Messages=FM;V$.MessagesPage=zJ;var iX=async(T)=>{let S=await Promise.allSettled(T),$=S.filter((M)=>M.status==="rejected");if($.length){for(let M of $)console.error(M.reason);throw new Error(`${$.length} promise(s) failed - see the above errors`)}let f=[];for(let M of S)if(M.status==="fulfilled")f.push(M.value);return f};class AM extends i{create(T,S,$){return this._client.post(`/vector_stores/${T}/files`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/vector_stores/${T}/files`,Of,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S,$);return await this.poll(T,f.id,$)}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let M=await this.retrieve(T,S,{...$,headers:f}).withResponse(),J=M.data;switch(J.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=M.response.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"failed":case"completed":return J}}}async upload(T,S,$){let f=await this._client.files.create({file:S,purpose:"assistants"},$);return this.create(T,{file_id:f.id},$)}async uploadAndPoll(T,S,$){let f=await this.upload(T,S,$);return await this.poll(T,f.id,$)}}class Of extends PT{}AM.VectorStoreFilesPage=Of;class DJ extends i{create(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/file_batches/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S);return await this.poll(T,f.id,$)}listFiles(T,S,$={},f){if(LT($))return this.listFiles(T,S,{},$);return this._client.getAPIList(`/vector_stores/${T}/file_batches/${S}/files`,Of,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:M,response:J}=await this.retrieve(T,S,{...$,headers:f}).withResponse();switch(M.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=J.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"failed":case"cancelled":case"completed":return M}}}async uploadAndPoll(T,{files:S,fileIds:$=[]},f){if(S==null||S.length==0)throw new Error("No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead");let M=f?.maxConcurrency??5,J=Math.min(M,S.length),F=this._client,W=S.values(),A=[...$];async function k(y){for(let K of y){let G=await F.files.create({file:K,purpose:"assistants"},f);A.push(G.id)}}let X=Array(J).fill(W).map(k);return await iX(X),await this.createAndPoll(T,{file_ids:A})}}class B$ extends i{constructor(){super(...arguments);this.files=new AM(this._client),this.fileBatches=new DJ(this._client)}create(T,S){return this._client.post("/vector_stores",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/vector_stores/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/vector_stores",EJ,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class EJ extends PT{}B$.VectorStoresPage=EJ;B$.Files=AM;B$.VectorStoreFilesPage=Of;B$.FileBatches=DJ;class $$ extends i{constructor(){super(...arguments);this.vectorStores=new B$(this._client),this.chat=new YJ(this._client),this.assistants=new TM(this._client),this.threads=new V$(this._client)}}$$.VectorStores=B$;$$.VectorStoresPage=EJ;$$.Assistants=TM;$$.AssistantsPage=FJ;$$.Threads=V$;class kM extends i{create(T,S){return this._client.post("/completions",{body:T,...S,stream:T.stream??!1})}}class XM extends i{create(T,S){return this._client.post("/embeddings",{body:T,...S})}}class Gf extends i{create(T,S){return this._client.post("/files",vS({body:T,...S}))}retrieve(T,S){return this._client.get(`/files/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/files",yM,{query:T,...S})}del(T,S){return this._client.delete(`/files/${T}`,S)}content(T,S){return this._client.get(`/files/${T}/content`,{...S,__binaryResponse:!0})}retrieveContent(T,S){return this._client.get(`/files/${T}/content`,{...S,headers:{Accept:"application/json",...S?.headers}})}async waitForProcessing(T,{pollInterval:S=5000,maxWait:$=1800000}={}){let f=new Set(["processed","error","deleted"]),M=Date.now(),J=await this.retrieve(T);while(!J.status||!f.has(J.status))if(await D$(S),J=await this.retrieve(T),Date.now()-M>$)throw new Wf({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class yM extends PT{}Gf.FileObjectsPage=yM;class KM extends i{list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/checkpoints`,QJ,{query:S,...$})}}class QJ extends PT{}KM.FineTuningJobCheckpointsPage=QJ;class L$ extends i{constructor(){super(...arguments);this.checkpoints=new KM(this._client)}create(T,S){return this._client.post("/fine_tuning/jobs",{body:T,...S})}retrieve(T,S){return this._client.get(`/fine_tuning/jobs/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/fine_tuning/jobs",UJ,{query:T,...S})}cancel(T,S){return this._client.post(`/fine_tuning/jobs/${T}/cancel`,S)}listEvents(T,S={},$){if(LT(S))return this.listEvents(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/events`,VJ,{query:S,...$})}}class UJ extends PT{}class VJ extends PT{}L$.FineTuningJobsPage=UJ;L$.FineTuningJobEventsPage=VJ;L$.Checkpoints=KM;L$.FineTuningJobCheckpointsPage=QJ;class N$ extends i{constructor(){super(...arguments);this.jobs=new L$(this._client)}}N$.Jobs=L$;N$.FineTuningJobsPage=UJ;N$.FineTuningJobEventsPage=VJ;class wM extends i{createVariation(T,S){return this._client.post("/images/variations",vS({body:T,...S}))}edit(T,S){return this._client.post("/images/edits",vS({body:T,...S}))}generate(T,S){return this._client.post("/images/generations",{body:T,...S})}}class zf extends i{retrieve(T,S){return this._client.get(`/models/${T}`,S)}list(T){return this._client.getAPIList("/models",YM,T)}del(T,S){return this._client.delete(`/models/${T}`,S)}}class YM extends Z0{}zf.ModelsPage=YM;class RM extends i{create(T,S){return this._client.post("/moderations",{body:T,...S})}}class BJ extends i{create(T,S,$){return this._client.post(`/uploads/${T}/parts`,vS({body:S,...$}))}}class _f extends i{constructor(){super(...arguments);this.parts=new BJ(this._client)}create(T,S){return this._client.post("/uploads",{body:T,...S})}cancel(T,S){return this._client.post(`/uploads/${T}/cancel`,S)}complete(T,S,$){return this._client.post(`/uploads/${T}/complete`,{body:S,...$})}}_f.Parts=BJ;var lX;class RT extends q0{constructor({baseURL:T=TJ("OPENAI_BASE_URL"),apiKey:S=TJ("OPENAI_API_KEY"),organization:$=TJ("OPENAI_ORG_ID")??null,project:f=TJ("OPENAI_PROJECT_ID")??null,...M}={}){if(S===void 0)throw new $T("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let J={apiKey:S,organization:$,project:f,...M,baseURL:T||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&LX())throw new $T("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new kM(this),this.chat=new kf(this),this.embeddings=new XM(this),this.files=new Gf(this),this.images=new wM(this),this.audio=new E$(this),this.moderations=new RM(this),this.models=new zf(this),this.fineTuning=new N$(this),this.beta=new $$(this),this.batches=new Xf(this),this.uploads=new _f(this),this._options=J,this.apiKey=S,this.organization=$,this.project=f}defaultQuery(){return this._options.defaultQuery}defaultHeaders(T){return{...super.defaultHeaders(T),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(T){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(T){return D0(T,{arrayFormat:"brackets"})}}lX=RT;RT.OpenAI=lX;RT.DEFAULT_TIMEOUT=600000;RT.OpenAIError=$T;RT.APIError=gT;RT.APIConnectionError=Ff;RT.APIConnectionTimeoutError=Wf;RT.APIUserAbortError=SS;RT.NotFoundError=UF;RT.ConflictError=VF;RT.RateLimitError=LF;RT.BadRequestError=DF;RT.AuthenticationError=EF;RT.InternalServerError=NF;RT.PermissionDeniedError=QF;RT.UnprocessableEntityError=BF;RT.toFile=j0;RT.fileFromPath=HF;RT.Completions=kM;RT.Chat=kf;RT.Embeddings=XM;RT.Files=Gf;RT.FileObjectsPage=yM;RT.Images=wM;RT.Audio=E$;RT.Moderations=RM;RT.Models=zf;RT.ModelsPage=YM;RT.FineTuning=N$;RT.Beta=$$;RT.Batches=Xf;RT.BatchesPage=sf;RT.Uploads=_f;var uX=RT;import{createHash as l6}from"crypto";import*as aT from"fs";import*as C$ from"path";function u6(T){let S=T.replace(d6,"-");if(S.length<=64)return S;let $=l6("sha256").update(T).digest("hex");return S.slice(-64)+"+"+$}var d6=/[^a-zA-Z0-9\-._]/g;class T1{mode;baseDir;filenameCache=new Map;filesTouched=new Map;constructor(T="off",S=C$.join(process.cwd(),".varmint")){this.mode=T,this.baseDir=S}read(T,S,$){let f=C$.join(this.baseDir,`${T}/${S}.input.json`);if(!aT.existsSync(f))throw new Error(`Squirrel: input file for key "${T}" does not exist`);let M=aT.readFileSync(f,"utf-8"),J=JSON.stringify($,null,"\t");if(J!==M)throw new Error(`Squirrel: the content of the cached input file ${f} does not match the input provided.\n\nProvided:\n${J}\n\nCached:\n${M}`);let F=C$.join(this.baseDir,`${T}/${S}.output.json`);return JSON.parse(aT.readFileSync(F,"utf-8"))}async write(T,S,$,f){let M=C$.join(this.baseDir,T),J=C$.join(M,`${S}.input.json`),F=C$.join(M,`${S}.output.json`),W=JSON.stringify($,null,"\t");if(!aT.existsSync(this.baseDir))aT.mkdirSync(this.baseDir);if(!aT.existsSync(M))aT.mkdirSync(M);if(aT.writeFileSync(J,W),aT.existsSync(F))aT.unlinkSync(F);let A=await f(...$);return aT.writeFileSync(F,JSON.stringify(A,null,"\t")),A}add(T,S){return{flush:()=>{this.flush(T)},for:($)=>{if(this.mode!=="off"&&!this.filesTouched.has(T))this.filesTouched.set(T,new Set);return{get:async(...f)=>{let M=$;if(this.mode!=="off"){let J=this.filenameCache.get($);if(!J)J=u6($),this.filenameCache.set($,M),M=J;this.filesTouched.get(T)?.add(M)}switch(this.mode){case"off":return S(...f);case"read":return this.read(T,M,f);case"write":return this.write(T,M,f,S);case"read-write":try{return this.read(T,M,f)}catch(J){if(J instanceof Error)return this.write(T,M,f,S);throw J}}}}}}}flush(...T){for(let[S,$]of this.filesTouched.entries())if(T.length===0||T.includes(S)){let f=C$.join(this.baseDir,S),M=aT.readdirSync(f);for(let J of M){let F=J.replace(".input.json","").replace(".output.json","");if(!$.has(F))console.log(`\uD83D\uDCA5 Flushing ${F}`),aT.unlinkSync(C$.join(f,J))}}}}function a6(T,...S){let[$,f,M,J]=S,F=[{role:"user",content:SX(f)},{role:"user",content:$}],W=J.at(-1);if(W)F.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(W.response,null,2),"Here's the error message:",W.error.toString()].join(`
12
- `)});return{model:T,messages:F}}var S1={"gpt-4o":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-08-06":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-05-13":{promptPricePerToken:0.000005,promptPricePerTokenCached:0.000005,completionPricePerToken:0.000014999999999999999},"gpt-4o-mini":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"gpt-4o-mini-2024-07-18":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"o1-preview":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995},"o1-preview-2024-09-12":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995}},dX=new Map;function e6(T="NO_API_KEY_PROVIDED"){let S=r6("sha256").update(T).digest("hex");return async function $(f,M){let J=dX.get(S);if(!J)J=new uX({apiKey:T,dangerouslyAllowBrowser:!1}),dX.set(S,J);let F=await J.chat.completions.create({...f,stream:!1,response_format:{type:"json_object"}},M),W=F.choices[0].message?.content,{usage:A}=F;if(W&&A){let k=A.prompt_tokens,X=A.prompt_tokens_details?.cached_tokens??0,y=k-X,K=A.completion_tokens,G=k*S1[f.model].promptPricePerToken+y*S1[f.model].promptPricePerTokenCached+K*S1[f.model].completionPricePerToken;return{data:JSON.parse(W),usdPrice:G}}if(!W&&!A)throw new Error("No content or usage found in completion");if(!W)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var rX=class{usdFloor;usdBudget;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;constructor({model:T,usdBudget:S,usdMinimum:$,apiKey:f,cachingMode:M,logger:J}){this.usdBudget=S,this.usdFloor=$,this.squirrel=new T1(M),this.getUnknownJsonFromOpenAi=e6(f),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add("openai-safegen",this.getUnknownJsonFromOpenAi),this.from=TX(async(...F)=>{if(this.usdBudget<this.usdFloor)return J?.warn("SafeGen budget exhausted"),F[1];let W=a6(T,...F),A=F[0],k=F[3],X=await this.getUnknownJsonFromOpenAiSquirreled.for(`${A.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${k.length}`).get(W);return this.usdBudget-=X.usdPrice,X.data})}from};import{exec as A7}from"child_process";import{existsSync as k7}from"fs";import{readFile as X7,writeFile as y7}from"fs/promises";import{resolve as K7}from"path";var $1=(T)=>{let S=_S(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let $=new Map;for(let[f,M]of T.atoms)if(!f.includes("\uD83D\uDD0D")){let J=kS(M);if(M.family){let F=$.get(M.family.key);if(!F||!("familyMembers"in F))F={key:M.family.key,familyMembers:new Map},$.set(M.family.key,F);F.familyMembers.set(M.family.subKey,J)}else $.set(f,J)}return $},effects:[({setSelf:$})=>{T.on.atomCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},M.set(J,W);W.familyMembers.set(F,f)}else M.set(f.key,f);return M})}),T.on.atomDisposal.subscribe("introspection",(f)=>{$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)M.delete(J)}}else M.delete(f.key);return M})})}]},void 0);return pS(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:$})=>$(S)})};var f1=(T)=>{let S=_S(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let $=new Map;for(let f of[T.readonlySelectors,T.selectors])for(let[M,J]of f)if(!M.includes("\uD83D\uDD0D")){let F=kS(J);if(J.family){let W=$.get(J.family.key);if(!W||!("familyMembers"in W))W={key:J.family.key,familyMembers:new Map},$.set(J.family.key,W);W.familyMembers.set(J.family.subKey,F)}else $.set(M,F)}return $},effects:[({setSelf:$})=>{T.on.selectorCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},M.set(J,W);W.familyMembers.set(F,f)}else M.set(f.key,f);return M})}),T.on.selectorDisposal.subscribe("introspection",(f)=>{$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)M.delete(J)}}else M.delete(f.key);return M})})}]},void 0);return pS(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:$})=>$(S)})};class lF{supported;constructor(T){this.supported=T}refine(T){for(let[S,$]of Object.entries(this.supported))try{if($(T)===!0&&$!==Boolean)return{type:S,data:T}}catch(f){try{if(T instanceof $)return{type:S,data:T}}catch(M){}}return null}}var M1=new lF({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function J1(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var F1=new lF({object:J1,array:(T)=>Array.isArray(T)}),s6=new lF({...M1.supported,...F1.supported}),OM=(T)=>{if(T===void 0)return"undefined";let S=s6.refine(T);if(S)return S.type;return Object.getPrototypeOf(T).constructor.name};class aX{T;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=XT.STORE){this.store=T;this.atomIndex=$1(this.store),this.selectorIndex=f1(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=aX.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let S=nW(this.atomIndex),$=nW(this.selectorIndex),f=[...S.values()].filter((W)=>("familyMembers"in W)),M=[...$.values()].filter((W)=>("familyMembers"in W)),J=performance.now(),F=[];if(T.atomFamilies)for(let W of f){let A=W.familyMembers.values();for(let k of A){let y=this.statesCreatedAt.get(k.key)??this.auditorCreatedAt,K=J-y;F.push([k,K])}}if(T.selectorFamilies)for(let W of M){let A=W.familyMembers.values();for(let k of A){let y=this.statesCreatedAt.get(k.key)??this.auditorCreatedAt,K=J-y;F.push([k,K])}}return F}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var W1=(T,S)=>{let $=(f,M)=>{let F=((A,k)=>{let X=S(A,k);if(X)return X;return null})(f,M);if(F?.jobComplete??F?.pathComplete)return F;let W=Array.isArray(M)?M.map((A,k)=>[k,A]):J1(M)?Object.entries(M):[];for(let[A,k]of W){let X=$([...f,A],k);if(X?.jobComplete)return X}return{}};$([],T)};function TY(T,S){return{summary:`${T<S?"+":"-"}${Math.abs(T-S)} (${T} \u2192 ${S})`}}function SY(T,S){return{summary:`${T.length<S.length?"+":"-"}${Math.abs(T.length-S.length)} ("${T}" \u2192 "${S}")`}}function $Y(T,S){return{summary:`${T} \u2192 ${S}`}}function eX(T,S,$){let f="",M=[],J=[],F=[];return W1(T,(W,A)=>{let k;for(k of W){let X=S[k];if(X===void 0)J.push([k,JSON.stringify(A)]);else{let y=$(A,X);if(y.summary!=="No Change")F.push([k,y])}}}),W1(S,(W,A)=>{let k;for(k of W)if(T[k]===void 0)M.push([k,JSON.stringify(A)])}),f=`\uFF5E${F.length} \uFF0B${M.length} \uFF0D${J.length}`,{summary:f,added:M,removed:J,changed:F}}function fY(T,S,$){return eX(T,S,$)}class sX{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,S,$){this.leafRefinery=T,this.treeRefinery=S,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(T.supported)){let M=$[f];this.leafDiffers[f]=M}for(let f of Object.keys(S.supported)){let M=$[f];this.treeDiffers[f]=M}}diff(T,S){if(T===S)return{summary:"No Change"};let $=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),f=this.leafRefinery.refine(S)??this.treeRefinery.refine(S);if($!==null&&f!==null){if($.type===f.type){if($.type in this.leafDiffers)return this.leafDiffers[$.type]($.data,f.data);if($.type in this.treeDiffers)return this.treeDiffers[$.type]($.data,f.data,(W,A)=>this.diff(W,A))}}let M=OM(T),J=OM(S);if(M===J)return{summary:`${M} \u2192 ${J}`};return{summary:`Type change: ${M} \u2192 ${J}`}}}var xN=new sX(M1,F1,{number:TY,string:SY,boolean:$Y,null:()=>({summary:"No Change"}),object:eX,array:fY});var Y=Symbol.for("drizzle:entityKind"),vN=Symbol.for("drizzle:hasOwnEntityKind");function V(T,S){if(!T||typeof T!=="object")return!1;if(T instanceof S)return!0;if(!Object.prototype.hasOwnProperty.call(S,Y))throw new Error(`Class "${S.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 $=Object.getPrototypeOf(T).constructor;if($)while($){if(Y in $&&$[Y]===S[Y])return!0;$=Object.getPrototypeOf($)}return!1}class NT{constructor(T,S){this.table=T,this.config=S,this.name=S.name,this.keyAsName=S.keyAsName,this.notNull=S.notNull,this.default=S.default,this.defaultFn=S.defaultFn,this.onUpdateFn=S.onUpdateFn,this.hasDefault=S.hasDefault,this.primary=S.primaryKey,this.isUnique=S.isUnique,this.uniqueName=S.uniqueName,this.uniqueType=S.uniqueType,this.dataType=S.dataType,this.columnType=S.columnType,this.generated=S.generated,this.generatedIdentity=S.generatedIdentity}static[Y]="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(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class A1{static[Y]="ColumnBuilder";config;constructor(T,S,$){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:S,columnType:$,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var f$=Symbol.for("drizzle:Name");class k1{static[Y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,S){if(this.reference=()=>{let{name:$,columns:f,foreignColumns:M}=T();return{name:$,columns:f,foreignTable:M[0].table,foreignColumns:M}},S)this._onUpdate=S.onUpdate,this._onDelete=S.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new T2(T,this)}}class T2{constructor(T,S){this.table=T,this.reference=S.reference,this.onUpdate=S._onUpdate,this.onDelete=S._onDelete}static[Y]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:S,foreignColumns:$}=this.reference(),f=S.map((F)=>F.name),M=$.map((F)=>F.name),J=[this.table[f$],...f,$[0].table[f$],...M];return T??`${J.join("_")}_fk`}}function uF(T,...S){return T(...S)}function S2(T,S){return`${T[f$]}_${S.join("_")}_unique`}function $2(T,S,$){for(let f=S;f<T.length;f++){let M=T[f];if(M==="\\"){f++;continue}if(M==='"')return[T.slice(S,f).replace(/\\/g,""),f+1];if($)continue;if(M===","||M==="}")return[T.slice(S,f).replace(/\\/g,""),f]}return[T.slice(S).replace(/\\/g,""),T.length]}function f2(T,S=0){let $=[],f=S,M=!1;while(f<T.length){let J=T[f];if(J===","){if(M||f===S)$.push("");M=!0,f++;continue}if(M=!1,J==="\\"){f+=2;continue}if(J==='"'){let[A,k]=$2(T,f+1,!0);$.push(A),f=k;continue}if(J==="}")return[$,f+1];if(J==="{"){let[A,k]=f2(T,f+1);$.push(A),f=k;continue}let[F,W]=$2(T,f,!1);$.push(F),f=W}return[$,f]}function M2(T){let[S]=f2(T,1);return S}function X1(T){return`{${T.map((S)=>{if(Array.isArray(S))return X1(S);if(typeof S==="string")return`"${S.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${S}`}).join(",")}}`}class g extends A1{foreignKeyConfigs=[];static[Y]="PgColumnBuilder";array(T){return new F2(this.config.name,this,T)}references(T,S={}){return this.foreignKeyConfigs.push({ref:T,actions:S}),this}unique(T,S){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=S?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,S){return this.foreignKeyConfigs.map(({ref:$,actions:f})=>{return uF((M,J)=>{let F=new k1(()=>{let W=M();return{columns:[T],foreignColumns:[W]}});if(J.onUpdate)F.onUpdate(J.onUpdate);if(J.onDelete)F.onDelete(J.onDelete);return F.build(S)},$,f)})}buildExtraConfigColumn(T){return new J2(T,this.config)}}class q extends NT{constructor(T,S){if(!S.uniqueName)S.uniqueName=S2(T,[S.name]);super(T,S);this.table=T}static[Y]="PgColumn"}class J2 extends q{static[Y]="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(T){return this.indexConfig.opClass=T,this}}class LJ{static[Y]="IndexedColumn";constructor(T,S,$,f){this.name=T,this.keyAsName=S,this.type=$,this.indexConfig=f}name;keyAsName;type;indexConfig}class F2 extends g{static[Y]="PgArrayBuilder";constructor(T,S,$){super(T,"array","PgArray");this.config.baseBuilder=S,this.config.size=$}build(T){let S=this.config.baseBuilder.build(T);return new y1(T,this.config,S)}}class y1 extends q{constructor(T,S,$,f){super(T,S);this.baseColumn=$,this.range=f,this.size=S.size}size;static[Y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=M2(T);return T.map((S)=>this.baseColumn.mapFromDriverValue(S))}mapToDriverValue(T,S=!1){let $=T.map((f)=>f===null?null:V(this.baseColumn,y1)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(S)return $;return X1($)}}var K1=Symbol.for("drizzle:isPgEnum");function W2(T){return!!T&&typeof T==="function"&&K1 in T&&T[K1]===!0}class A2 extends g{static[Y]="PgEnumColumnBuilder";constructor(T,S){super(T,"string","PgEnumColumn");this.config.enum=S}build(T){return new k2(T,this.config)}}class k2 extends q{static[Y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,S){super(T,S);this.enum=S.enum}getSQLType(){return this.enum.enumName}}function dF(T,S){return MY(T,S,void 0)}function MY(T,S,$){let f=Object.assign((M)=>new A2(M??"",f),{enumName:T,enumValues:S,schema:$,[K1]:!0});return f}class fS{static[Y]="Subquery";constructor(T,S,$,f=!1){this._={brand:"Subquery",sql:T,selectedFields:S,alias:$,isWith:f}}}class NJ extends fS{static[Y]="WithSubquery"}var X2="0.36.1";var w1,Y1,QT={startActiveSpan(T,S){if(!w1)return S();if(!Y1)Y1=w1.trace.getTracer("drizzle-orm",X2);return uF(($,f)=>f.startActiveSpan(T,(M)=>{try{return S(M)}catch(J){throw M.setStatus({code:$.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{M.end()}}),w1,Y1)}};var hT=Symbol.for("drizzle:ViewBaseConfig");var rF=Symbol.for("drizzle:Schema"),y2=Symbol.for("drizzle:Columns"),K2=Symbol.for("drizzle:ExtraConfigColumns"),R1=Symbol.for("drizzle:OriginalName"),O1=Symbol.for("drizzle:BaseName"),w2=Symbol.for("drizzle:IsAlias"),Y2=Symbol.for("drizzle:ExtraConfigBuilder"),JY=Symbol.for("drizzle:IsDrizzleTable");class c{static[Y]="Table";static Symbol={Name:f$,Schema:rF,OriginalName:R1,Columns:y2,ExtraConfigColumns:K2,BaseName:O1,IsAlias:w2,ExtraConfigBuilder:Y2};[f$];[R1];[rF];[y2];[K2];[O1];[w2]=!1;[JY]=!0;[Y2]=void 0;constructor(T,S,$){this[f$]=this[R1]=T,this[rF]=S,this[O1]=$}}function PS(T){return T[f$]}function Hf(T){return`${T[rF]??"public"}.${T[f$]}`}function G1(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function FY(T){let S={sql:"",params:[]};for(let $ of T)if(S.sql+=$.sql,S.params.push(...$.params),$.typings?.length){if(!S.typings)S.typings=[];S.typings.push(...$.typings)}return S}class eT{static[Y]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new t([this])}}class t{constructor(T){this.queryChunks=T}static[Y]="SQL";decoder=O2;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return QT.startActiveSpan("drizzle.buildSQL",(S)=>{let $=this.buildQueryFromSourceParams(this.queryChunks,T);return S?.setAttributes({"drizzle.query.text":$.sql,"drizzle.query.params":JSON.stringify($.params)}),$})}buildQueryFromSourceParams(T,S){let $=Object.assign({},S,{inlineParams:S.inlineParams||this.shouldInlineParams,paramStartIndex:S.paramStartIndex||{value:0}}),{casing:f,escapeName:M,escapeParam:J,prepareTyping:F,inlineParams:W,paramStartIndex:A}=$;return FY(T.map((k)=>{if(V(k,eT))return{sql:k.value.join(""),params:[]};if(V(k,aF))return{sql:M(k.value),params:[]};if(k===void 0)return{sql:"",params:[]};if(Array.isArray(k)){let X=[new eT("(")];for(let[y,K]of k.entries())if(X.push(K),y<k.length-1)X.push(new eT(", "));return X.push(new eT(")")),this.buildQueryFromSourceParams(X,$)}if(V(k,t))return this.buildQueryFromSourceParams(k.queryChunks,{...$,inlineParams:W||k.shouldInlineParams});if(V(k,c)){let X=k[c.Symbol.Schema],y=k[c.Symbol.Name];return{sql:X===void 0?M(y):M(X)+"."+M(y),params:[]}}if(V(k,NT)){let X=f.getColumnCasing(k);if(S.invokeSource==="indexes")return{sql:M(X),params:[]};return{sql:M(k.table[c.Symbol.Name])+"."+M(X),params:[]}}if(V(k,ES)){let X=k[hT].schema,y=k[hT].name;return{sql:X===void 0?M(y):M(X)+"."+M(y),params:[]}}if(V(k,IS)){if(V(k.value,l$))return{sql:J(A.value++,k),params:[k],typings:["none"]};let X=k.value===null?null:k.encoder.mapToDriverValue(k.value);if(V(X,t))return this.buildQueryFromSourceParams([X],$);if(W)return{sql:this.mapInlineParam(X,$),params:[]};let y=["none"];if(F)y=[F(k.encoder)];return{sql:J(A.value++,X),params:[X],typings:y}}if(V(k,l$))return{sql:J(A.value++,k),params:[k],typings:["none"]};if(V(k,t.Aliased)&&k.fieldAlias!==void 0)return{sql:M(k.fieldAlias),params:[]};if(V(k,fS)){if(k._.isWith)return{sql:M(k._.alias),params:[]};return this.buildQueryFromSourceParams([new eT("("),k._.sql,new eT(") "),new aF(k._.alias)],$)}if(W2(k)){if(k.schema)return{sql:M(k.schema)+"."+M(k.enumName),params:[]};return{sql:M(k.enumName),params:[]}}if(G1(k)){if(k.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([k.getSQL()],$);return this.buildQueryFromSourceParams([new eT("("),k.getSQL(),new eT(")")],$)}if(W)return{sql:this.mapInlineParam(k,$),params:[]};return{sql:J(A.value++,k),params:[k],typings:["none"]}}))}mapInlineParam(T,{escapeString:S}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return S(T);if(typeof T==="object"){let $=T.toString();if($==="[object Object]")return S(JSON.stringify(T));return S($)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new t.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class aF{constructor(T){this.value=T}static[Y]="Name";brand;getSQL(){return new t([this])}}function R2(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var O2={mapFromDriverValue:(T)=>T},G2={mapToDriverValue:(T)=>T},BC={...O2,...G2};class IS{constructor(T,S=G2){this.value=T,this.encoder=S}static[Y]="Param";brand;getSQL(){return new t([this])}}function R(T,...S){let $=[];if(S.length>0||T.length>0&&T[0]!=="")$.push(new eT(T[0]));for(let[f,M]of S.entries())$.push(M,new eT(T[f+1]));return new t($)}((T)=>{function S(){return new t([])}T.empty=S;function $(A){return new t(A)}T.fromList=$;function f(A){return new t([new eT(A)])}T.raw=f;function M(A,k){let X=[];for(let[y,K]of A.entries()){if(y>0&&k!==void 0)X.push(k);X.push(K)}return new t(X)}T.join=M;function J(A){return new aF(A)}T.identifier=J;function F(A){return new l$(A)}T.placeholder=F;function W(A,k){return new IS(A,k)}T.param=W})(R||(R={}));((T)=>{class S{constructor($,f){this.sql=$,this.fieldAlias=f}static[Y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new S(this.sql,this.fieldAlias)}}T.Aliased=S})(t||(t={}));class l${constructor(T){this.name=T}static[Y]="Placeholder";getSQL(){return new t([this])}}function z1(T,S){return T.map(($)=>{if(V($,l$)){if(!($.name in S))throw new Error(`No value for placeholder "${$.name}" was provided`);return S[$.name]}if(V($,IS)&&V($.value,l$)){if(!($.value.name in S))throw new Error(`No value for placeholder "${$.value.name}" was provided`);return $.encoder.mapToDriverValue(S[$.value.name])}return $})}class ES{static[Y]="View";[hT];constructor({name:T,schema:S,selectedFields:$,query:f}){this[hT]={name:T,originalName:T,schema:S,selectedFields:$,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new t([this])}}NT.prototype.getSQL=function(){return new t([this])};c.prototype.getSQL=function(){return new t([this])};fS.prototype.getSQL=function(){return new t([this])};class GM{constructor(T){this.table=T}static[Y]="ColumnAliasProxyHandler";get(T,S){if(S==="table")return this.table;return T[S]}}class CJ{constructor(T,S){this.alias=T,this.replaceOriginalName=S}static[Y]="TableAliasProxyHandler";get(T,S){if(S===c.Symbol.IsAlias)return!0;if(S===c.Symbol.Name)return this.alias;if(this.replaceOriginalName&&S===c.Symbol.OriginalName)return this.alias;if(S===hT)return{...T[hT],name:this.alias,isAlias:!0};if(S===c.Symbol.Columns){let f=T[c.Symbol.Columns];if(!f)return f;let M={};return Object.keys(f).map((J)=>{M[J]=new Proxy(f[J],new GM(new Proxy(T,this)))}),M}let $=T[S];if(V($,NT))return new Proxy($,new GM(new Proxy(T,this)));return $}}function eF(T,S){return new Proxy(T,new CJ(S,!1))}function w$(T,S){return new Proxy(T,new GM(new Proxy(T.table,new CJ(S,!1))))}function _1(T,S){return new t.Aliased(xJ(T.sql,S),T.fieldAlias)}function xJ(T,S){return R.join(T.queryChunks.map(($)=>{if(V($,NT))return w$($,S);if(V($,t))return xJ($,S);if(V($,t.Aliased))return _1($,S);return $}))}class sF extends Error{static[Y]="DrizzleError";constructor({message:T,cause:S}){super(T);this.name="DrizzleError",this.cause=S}}class H1 extends sF{static[Y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function QS(T,S){if(R2(S)&&!G1(T)&&!V(T,IS)&&!V(T,l$)&&!V(T,NT)&&!V(T,c)&&!V(T,ES))return new IS(T,S);return T}var TW=(T,S)=>{return R`${T} = ${QS(S,T)}`},z2=(T,S)=>{return R`${T} <> ${QS(S,T)}`};function jJ(...T){let S=T.filter(($)=>$!==void 0);if(S.length===0)return;if(S.length===1)return new t(S);return new t([new eT("("),R.join(S,new eT(" and ")),new eT(")")])}function _2(...T){let S=T.filter(($)=>$!==void 0);if(S.length===0)return;if(S.length===1)return new t(S);return new t([new eT("("),R.join(S,new eT(" or ")),new eT(")")])}function H2(T){return R`not ${T}`}var SW=(T,S)=>{return R`${T} > ${QS(S,T)}`},D2=(T,S)=>{return R`${T} >= ${QS(S,T)}`},E2=(T,S)=>{return R`${T} < ${QS(S,T)}`},Q2=(T,S)=>{return R`${T} <= ${QS(S,T)}`};function U2(T,S){if(Array.isArray(S)){if(S.length===0)return R`false`;return R`${T} in ${S.map(($)=>QS($,T))}`}return R`${T} in ${QS(S,T)}`}function V2(T,S){if(Array.isArray(S)){if(S.length===0)return R`true`;return R`${T} not in ${S.map(($)=>QS($,T))}`}return R`${T} not in ${QS(S,T)}`}function B2(T){return R`${T} is null`}function L2(T){return R`${T} is not null`}function N2(T){return R`exists ${T}`}function C2(T){return R`not exists ${T}`}function x2(T,S,$){return R`${T} between ${QS(S,T)} and ${QS($,T)}`}function j2(T,S,$){return R`${T} not between ${QS(S,T)} and ${QS($,T)}`}function I2(T,S){return R`${T} like ${S}`}function b2(T,S){return R`${T} not like ${S}`}function q2(T,S){return R`${T} ilike ${S}`}function Z2(T,S){return R`${T} not ilike ${S}`}function m2(T){return R`${T} asc`}function h2(T){return R`${T} desc`}class v2{static[Y]="ConsoleLogWriter";write(T){console.log(T)}}class D1{static[Y]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new v2}logQuery(T,S){let $=S.map((M)=>{try{return JSON.stringify(M)}catch{return String(M)}}),f=$.length?` -- params: [${$.join(", ")}]`:"";this.writer.write(`Query: ${T}${f}`)}}class E1{static[Y]="NoopLogger";logQuery(){}}class GS{static[Y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}then(T,S){return this.execute().then(T,S)}}function P2(T,S,$){let f={},M=T.reduce((J,{path:F,field:W},A)=>{let k;if(V(W,NT))k=W;else if(V(W,t))k=W.decoder;else k=W.sql.decoder;let X=J;for(let[y,K]of F.entries())if(y<F.length-1){if(!(K in X))X[K]={};X=X[K]}else{let G=S[A],z=X[K]=G===null?null:k.mapFromDriverValue(G);if($&&V(W,NT)&&F.length===2){let Q=F[0];if(!(Q in f))f[Q]=z===null?PS(W.table):!1;else if(typeof f[Q]==="string"&&f[Q]!==PS(W.table))f[Q]=!1}}return J},{});if($&&Object.keys(f).length>0){for(let[J,F]of Object.entries(f))if(typeof F==="string"&&!$[F])M[J]=null}return M}function nS(T,S){return Object.entries(T).reduce(($,[f,M])=>{if(typeof f!=="string")return $;let J=S?[...S,f]:[f];if(V(M,NT)||V(M,t)||V(M,t.Aliased))$.push({path:J,field:M});else if(V(M,c))$.push(...nS(M[c.Symbol.Columns],J));else $.push(...nS(M,J));return $},[])}function Q1(T,S){let $=Object.keys(T),f=Object.keys(S);if($.length!==f.length)return!1;for(let[M,J]of $.entries())if(J!==f[M])return!1;return!0}function $W(T,S){let $=Object.entries(S).filter(([,f])=>f!==void 0).map(([f,M])=>{if(V(M,t))return[f,M];else return[f,new IS(M,T[c.Symbol.Columns][f])]});if($.length===0)throw new Error("No values to set");return Object.fromEntries($)}function n2(T,S){for(let $ of S)for(let f of Object.getOwnPropertyNames($.prototype)){if(f==="constructor")continue;Object.defineProperty(T.prototype,f,Object.getOwnPropertyDescriptor($.prototype,f)||Object.create(null))}}function c2(T){return T[c.Symbol.Columns]}function U1(T){return V(T,fS)?T._.alias:V(T,ES)?T[hT].name:V(T,t)?void 0:T[c.Symbol.IsAlias]?T[c.Symbol.Name]:T[c.Symbol.BaseName]}function yT(T,S){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:S}}function o2(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let S=typeof T.logger;if(S!=="boolean"&&(S!=="object"||typeof T.logger.logQuery!=="function")&&S!=="undefined")return!1;return!0}if("schema"in T){let S=typeof T.logger;if(S!=="object"&&S!=="undefined")return!1;return!0}if("casing"in T){let S=typeof T.logger;if(S!=="string"&&S!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let S=typeof T.connection;if(S!=="string"&&S!=="object"&&S!=="undefined")return!1;return!0}if("client"in T){let S=typeof T.client;if(S!=="object"&&S!=="function"&&S!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class u$ extends g{static[Y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:S,...$}=T;this.config.generatedIdentity={type:"always",sequenceName:S,sequenceOptions:$}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:S,...$}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:S,sequenceOptions:$}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class g2 extends u${static[Y]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new t2(T,this.config)}}class t2 extends q{static[Y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class p2 extends u${static[Y]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new i2(T,this.config)}}class i2 extends q{static[Y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function l2(T,S){let{name:$,config:f}=yT(T,S);if(f.mode==="number")return new g2($);return new p2($)}class u2 extends g{static[Y]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new d2(T,this.config)}}class d2 extends q{static[Y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class r2 extends g{static[Y]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new a2(T,this.config)}}class a2 extends q{static[Y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function e2(T,S){let{name:$,config:f}=yT(T,S);if(f.mode==="number")return new u2($);return new r2($)}class s2 extends g{static[Y]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new Ty(T,this.config)}}class Ty extends q{static[Y]="PgBoolean";getSQLType(){return"boolean"}}function IJ(T){return new s2(T??"")}class Sy extends g{static[Y]="PgCharBuilder";constructor(T,S){super(T,"string","PgChar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new $y(T,this.config)}}class $y extends q{static[Y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function fy(T,S={}){let{name:$,config:f}=yT(T,S);return new Sy($,f)}class My extends g{static[Y]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new Jy(T,this.config)}}class Jy extends q{static[Y]="PgCidr";getSQLType(){return"cidr"}}function Fy(T){return new My(T??"")}class Wy extends g{static[Y]="PgCustomColumnBuilder";constructor(T,S,$){super(T,"custom","PgCustomColumn");this.config.fieldConfig=S,this.config.customTypeParams=$}build(T){return new Ay(T,this.config)}}class Ay extends q{static[Y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,S){super(T,S);this.sqlName=S.customTypeParams.dataType(S.fieldConfig),this.mapTo=S.customTypeParams.toDriver,this.mapFrom=S.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function ky(T){return(S,$)=>{let{name:f,config:M}=yT(S,$);return new Wy(f,M,T)}}class x$ extends g{static[Y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class Xy extends x${static[Y]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new fW(T,this.config)}}class fW extends q{static[Y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class yy extends x${static[Y]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new MW(T,this.config)}}class MW extends q{static[Y]="PgDateString";getSQLType(){return"date"}}function Ky(T,S){let{name:$,config:f}=yT(T,S);if(f?.mode==="date")return new Xy($);return new yy($)}class wy extends g{static[Y]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new Yy(T,this.config)}}class Yy extends q{static[Y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function Ry(T){return new wy(T??"")}class Oy extends g{static[Y]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new Gy(T,this.config)}}class Gy extends q{static[Y]="PgInet";getSQLType(){return"inet"}}function zy(T){return new Oy(T??"")}class _y extends u${static[Y]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new Hy(T,this.config)}}class Hy extends q{static[Y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function JW(T){return new _y(T??"")}class Dy extends g{static[Y]="PgIntervalBuilder";constructor(T,S){super(T,"string","PgInterval");this.config.intervalConfig=S}build(T){return new Ey(T,this.config)}}class Ey extends q{static[Y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",S=this.precision?`(${this.precision})`:"";return`interval${T}${S}`}}function Qy(T,S={}){let{name:$,config:f}=yT(T,S);return new Dy($,f)}class Uy extends g{static[Y]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new FW(T,this.config)}}class FW extends q{static[Y]="PgJson";constructor(T,S){super(T,S)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function Vy(T){return new Uy(T??"")}class By extends g{static[Y]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new WW(T,this.config)}}class WW extends q{static[Y]="PgJsonb";constructor(T,S){super(T,S)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function Ly(T){return new By(T??"")}class Ny extends g{static[Y]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new Cy(T,this.config)}}class Cy extends q{static[Y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[S,$,f]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($),Number.parseFloat(f)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class xy extends g{static[Y]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new jy(T,this.config)}}class jy extends q{static[Y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[S,$,f]=T.slice(1,-1).split(",");return{a:Number.parseFloat(S),b:Number.parseFloat($),c:Number.parseFloat(f)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function Iy(T,S){let{name:$,config:f}=yT(T,S);if(!f?.mode||f.mode==="tuple")return new Ny($);return new xy($)}class by extends g{static[Y]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new qy(T,this.config)}}class qy extends q{static[Y]="PgMacaddr";getSQLType(){return"macaddr"}}function Zy(T){return new by(T??"")}class my extends g{static[Y]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new hy(T,this.config)}}class hy extends q{static[Y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function vy(T){return new my(T??"")}class Py extends g{static[Y]="PgNumericBuilder";constructor(T,S,$){super(T,"string","PgNumeric");this.config.precision=S,this.config.scale=$}build(T){return new AW(T,this.config)}}class AW extends q{static[Y]="PgNumeric";precision;scale;constructor(T,S){super(T,S);this.precision=S.precision,this.scale=S.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function ny(T,S){let{name:$,config:f}=yT(T,S);return new Py($,f?.precision,f?.scale)}class cy extends g{static[Y]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new oy(T,this.config)}}class oy extends q{static[Y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[S,$]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class gy extends g{static[Y]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new ty(T,this.config)}}class ty extends q{static[Y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[S,$]=T.slice(1,-1).split(",");return{x:Number.parseFloat(S),y:Number.parseFloat($)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function py(T,S){let{name:$,config:f}=yT(T,S);if(!f?.mode||f.mode==="tuple")return new cy($);return new gy($)}function WY(T){let S=[];for(let $=0;$<T.length;$+=2)S.push(Number.parseInt(T.slice($,$+2),16));return new Uint8Array(S)}function iy(T,S){let $=new ArrayBuffer(8),f=new DataView($);for(let M=0;M<8;M++)f.setUint8(M,T[S+M]);return f.getFloat64(0,!0)}function V1(T){let S=WY(T),$=0,f=S[$];$+=1;let M=new DataView(S.buffer),J=M.getUint32($,f===1);$+=4;let F;if(J&536870912)F=M.getUint32($,f===1),$+=4;if((J&65535)===1){let W=iy(S,$);$+=8;let A=iy(S,$);return $+=8,[W,A]}throw new Error("Unsupported geometry type")}class ly extends g{static[Y]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new uy(T,this.config)}}class uy extends q{static[Y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return V1(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class dy extends g{static[Y]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new ry(T,this.config)}}class ry extends q{static[Y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let S=V1(T);return{x:S[0],y:S[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function ay(T,S){let{name:$,config:f}=yT(T,S);if(!f?.mode||f.mode==="tuple")return new ly($);return new dy($)}class ey extends g{static[Y]="PgRealBuilder";constructor(T,S){super(T,"number","PgReal");this.config.length=S}build(T){return new sy(T,this.config)}}class sy extends q{static[Y]="PgReal";constructor(T,S){super(T,S)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function T8(T){return new ey(T??"")}class S8 extends g{static[Y]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new $8(T,this.config)}}class $8 extends q{static[Y]="PgSerial";getSQLType(){return"serial"}}function f8(T){return new S8(T??"")}class M8 extends u${static[Y]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new J8(T,this.config)}}class J8 extends q{static[Y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function F8(T){return new M8(T??"")}class W8 extends g{static[Y]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new A8(T,this.config)}}class A8 extends q{static[Y]="PgSmallSerial";getSQLType(){return"smallserial"}}function k8(T){return new W8(T??"")}class X8 extends g{static[Y]="PgTextBuilder";constructor(T,S){super(T,"string","PgText");this.config.enumValues=S.enum}build(T){return new y8(T,this.config)}}class y8 extends q{static[Y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function K8(T,S={}){let{name:$,config:f}=yT(T,S);return new X8($,f)}class w8 extends x${constructor(T,S,$){super(T,"string","PgTime");this.withTimezone=S,this.precision=$,this.config.withTimezone=S,this.config.precision=$}static[Y]="PgTimeBuilder";build(T){return new kW(T,this.config)}}class kW extends q{static[Y]="PgTime";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function Y8(T,S={}){let{name:$,config:f}=yT(T,S);return new w8($,f.withTimezone??!1,f.precision)}class R8 extends x${static[Y]="PgTimestampBuilder";constructor(T,S,$){super(T,"date","PgTimestamp");this.config.withTimezone=S,this.config.precision=$}build(T){return new XW(T,this.config)}}class XW extends q{static[Y]="PgTimestamp";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class O8 extends x${static[Y]="PgTimestampStringBuilder";constructor(T,S,$){super(T,"string","PgTimestampString");this.config.withTimezone=S,this.config.precision=$}build(T){return new yW(T,this.config)}}class yW extends q{static[Y]="PgTimestampString";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function M$(T,S={}){let{name:$,config:f}=yT(T,S);if(f?.mode==="string")return new O8($,f.withTimezone??!1,f.precision);return new R8($,f?.withTimezone??!1,f?.precision)}class G8 extends g{static[Y]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(T){return new KW(T,this.config)}}class KW extends q{static[Y]="PgUUID";getSQLType(){return"uuid"}}function bS(T){return new G8(T??"")}class z8 extends g{static[Y]="PgVarcharBuilder";constructor(T,S){super(T,"string","PgVarchar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new _8(T,this.config)}}class _8 extends q{static[Y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function MS(T,S={}){let{name:$,config:f}=yT(T,S);return new z8($,f)}class H8 extends g{static[Y]="PgBinaryVectorBuilder";constructor(T,S){super(T,"string","PgBinaryVector");this.config.dimensions=S.dimensions}build(T){return new D8(T,this.config)}}class D8 extends q{static[Y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function E8(T,S){let{name:$,config:f}=yT(T,S);return new H8($,f)}class Q8 extends g{static[Y]="PgHalfVectorBuilder";constructor(T,S){super(T,"array","PgHalfVector");this.config.dimensions=S.dimensions}build(T){return new U8(T,this.config)}}class U8 extends q{static[Y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function V8(T,S){let{name:$,config:f}=yT(T,S);return new Q8($,f)}class B8 extends g{static[Y]="PgSparseVectorBuilder";constructor(T,S){super(T,"string","PgSparseVector");this.config.dimensions=S.dimensions}build(T){return new L8(T,this.config)}}class L8 extends q{static[Y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function N8(T,S){let{name:$,config:f}=yT(T,S);return new B8($,f)}class C8 extends g{static[Y]="PgVectorBuilder";constructor(T,S){super(T,"array","PgVector");this.config.dimensions=S.dimensions}build(T){return new x8(T,this.config)}}class x8 extends q{static[Y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function j8(T,S){let{name:$,config:f}=yT(T,S);return new C8($,f)}function I8(){return{bigint:l2,bigserial:e2,boolean:IJ,char:fy,cidr:Fy,customType:ky,date:Ky,doublePrecision:Ry,inet:zy,integer:JW,interval:Qy,json:Vy,jsonb:Ly,line:Iy,macaddr:Zy,macaddr8:vy,numeric:ny,point:py,geometry:ay,real:T8,serial:f8,smallint:F8,smallserial:k8,text:K8,time:Y8,timestamp:M$,uuid:bS,varchar:MS,bit:E8,halfvec:V8,sparsevec:N8,vector:j8}}var B1=Symbol.for("drizzle:PgInlineForeignKeys"),b8=Symbol.for("drizzle:EnableRLS");class cS extends c{static[Y]="PgTable";static Symbol=Object.assign({},c.Symbol,{InlineForeignKeys:B1,EnableRLS:b8});[B1]=[];[b8]=!1;[c.Symbol.ExtraConfigBuilder]=void 0}function AY(T,S,$,f,M=T){let J=new cS(T,f,M),F=typeof S==="function"?S(I8()):S,W=Object.fromEntries(Object.entries(F).map(([X,y])=>{let K=y;K.setName(X);let G=K.build(J);return J[B1].push(...K.buildForeignKeys(G,J)),[X,G]})),A=Object.fromEntries(Object.entries(F).map(([X,y])=>{let K=y;K.setName(X);let G=K.buildExtraConfigColumn(J);return[X,G]})),k=Object.assign(J,W);if(k[c.Symbol.Columns]=W,k[c.Symbol.ExtraConfigColumns]=A,$)k[cS.Symbol.ExtraConfigBuilder]=$;return Object.assign(k,{enableRLS:()=>{return k[cS.Symbol.EnableRLS]=!0,k}})}var d$=(T,S,$)=>{return AY(T,S,$,void 0)};function q8(...T){if(T[0].columns)return new bJ(T[0].columns,T[0].name);return new bJ(T)}class bJ{static[Y]="PgPrimaryKeyBuilder";columns;name;constructor(T,S){this.columns=T,this.name=S}build(T){return new Z8(T,this.columns,this.name)}}class Z8{constructor(T,S,$){this.table=T,this.columns=S,this.name=$}static[Y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[cS.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class L1{constructor(T,S,$){this.sourceTable=T,this.referencedTable=S,this.relationName=$,this.referencedTableName=S[c.Symbol.Name]}static[Y]="Relation";referencedTableName;fieldName}class m8{constructor(T,S){this.table=T,this.config=S}static[Y]="Relations"}class r$ extends L1{constructor(T,S,$,f){super(T,S,$?.relationName);this.config=$,this.isNullable=f}static[Y]="One";withFieldName(T){let S=new r$(this.sourceTable,this.referencedTable,this.config,this.isNullable);return S.fieldName=T,S}}class qJ extends L1{constructor(T,S,$){super(T,S,$?.relationName);this.config=$}static[Y]="Many";withFieldName(T){let S=new qJ(this.sourceTable,this.referencedTable,this.config);return S.fieldName=T,S}}function h8(){return{and:jJ,between:x2,eq:TW,exists:N2,gt:SW,gte:D2,ilike:q2,inArray:U2,isNull:B2,isNotNull:L2,like:I2,lt:E2,lte:Q2,ne:z2,not:H2,notBetween:j2,notExists:C2,notLike:b2,notIlike:Z2,notInArray:V2,or:_2,sql:R}}function v8(){return{sql:R,asc:m2,desc:h2}}function P8(T,S){if(Object.keys(T).length===1&&"default"in T&&!V(T.default,c))T=T.default;let $={},f={},M={};for(let[J,F]of Object.entries(T))if(V(F,c)){let W=Hf(F),A=f[W];$[W]=J,M[J]={tsName:J,dbName:F[c.Symbol.Name],schema:F[c.Symbol.Schema],columns:F[c.Symbol.Columns],relations:A?.relations??{},primaryKey:A?.primaryKey??[]};for(let X of Object.values(F[c.Symbol.Columns]))if(X.primary)M[J].primaryKey.push(X);let k=F[c.Symbol.ExtraConfigBuilder]?.(F[c.Symbol.ExtraConfigColumns]);if(k){for(let X of Object.values(k))if(V(X,bJ))M[J].primaryKey.push(...X.columns)}}else if(V(F,m8)){let W=Hf(F.table),A=$[W],k=F.config(S(F.table)),X;for(let[y,K]of Object.entries(k))if(A){let G=M[A];if(G.relations[y]=K,X)G.primaryKey.push(...X)}else{if(!(W in f))f[W]={relations:{},primaryKey:X};f[W].relations[y]=K}}return{tables:M,tableNamesMap:$}}function kY(T){return function S($,f){return new r$(T,$,f,f?.fields.reduce((M,J)=>M&&J.notNull,!0)??!1)}}function XY(T){return function S($,f){return new qJ(T,$,f)}}function n8(T,S,$){if(V($,r$)&&$.config)return{fields:$.config.fields,references:$.config.references};let f=S[Hf($.referencedTable)];if(!f)throw new Error(`Table "${$.referencedTable[c.Symbol.Name]}" not found in schema`);let M=T[f];if(!M)throw new Error(`Table "${f}" not found in schema`);let J=$.sourceTable,F=S[Hf(J)];if(!F)throw new Error(`Table "${J[c.Symbol.Name]}" not found in schema`);let W=[];for(let A of Object.values(M.relations))if($.relationName&&$!==A&&A.relationName===$.relationName||!$.relationName&&A.referencedTable===$.sourceTable)W.push(A);if(W.length>1)throw $.relationName?new Error(`There are multiple relations with name "${$.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${$.sourceTable[c.Symbol.Name]}". Please specify relation name`);if(W[0]&&V(W[0],r$)&&W[0].config)return{fields:W[0].config.references,references:W[0].config.fields};throw new Error(`There is not enough information to infer relation "${F}.${$.fieldName}"`)}function c8(T){return{one:kY(T),many:XY(T)}}function wW(T,S,$,f,M=(J)=>J){let J={};for(let[F,W]of f.entries())if(W.isJson){let A=S.relations[W.tsKey],k=$[F],X=typeof k==="string"?JSON.parse(k):k;J[W.tsKey]=V(A,r$)?X&&wW(T,T[W.relationTableTsKey],X,W.selection,M):X.map((y)=>wW(T,T[W.relationTableTsKey],y,W.selection,M))}else{let A=M($[F]),k=W.field,X;if(V(k,NT))X=k;else if(V(k,t))X=k.decoder;else X=k.sql.decoder;J[W.tsKey]=A===null?null:X.mapFromDriverValue(A)}return J}import J7 from"path";import qY from"os";import ZY from"fs";var YW=new Map,N1=new Map,C1=Symbol("OriginError"),zM={};class oS extends Promise{constructor(T,S,$,f,M={}){let J,F;super((W,A)=>{J=W,F=A});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=S,this.handler=$,this.canceller=f,this.options=M,this.state=null,this.statement=null,this.resolve=(W)=>(this.active=!1,J(W)),this.reject=(W)=>(this.active=!1,F(W)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[C1]=this.handler.debug?new Error:this.tagged&&yY(this.strings)}get origin(){return(this.handler.debug?this[C1].stack:this.tagged&&N1.has(this.strings)?N1.get(this.strings):N1.set(this.strings,this[C1].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,S){if(this.options.simple=!1,typeof T==="function")S=T,T=1;if(this.cursorRows=T,typeof S==="function")return this.cursorFn=S,this;let $;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};$&&$();let f=new Promise((M,J)=>{this.cursorFn=(F)=>{return M({value:F,done:!1}),new Promise((W)=>$=W)},this.resolve=()=>(this.active=!1,M({done:!0})),this.reject=(F)=>(this.active=!1,J(F))});return this.execute(),f},return(){return $&&$(zM),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function yY(T){if(YW.has(T))return YW.get(T);let S=Error.stackTraceLimit;return Error.stackTraceLimit=4,YW.set(T,new Error),Error.stackTraceLimit=S,YW.get(T)}class _M extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var tT={connection:o8,postgres:g8,generic:t8,notSupported:p8};function o8(T,S,$){let{host:f,port:M}=$||S,J=Object.assign(new Error("write "+T+" "+(S.path||f+":"+M)),{code:T,errno:T,address:S.path||f},S.path?{}:{port:M});return Error.captureStackTrace(J,o8),J}function g8(T){let S=new _M(T);return Error.captureStackTrace(S,g8),S}function t8(T,S){let $=Object.assign(new Error(T+": "+S),{code:T});return Error.captureStackTrace($,t8),$}function p8(T){let S=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(S,p8),S}var KY={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class GW{then(){x1()}catch(){x1()}finally(){x1()}}class vJ extends GW{constructor(T){super();this.value=HW(T)}}class Y$ extends GW{constructor(T,S,$){super();this.value=T,this.type=S,this.array=$}}class zW extends GW{constructor(T,S){super();this.first=T,this.rest=S}build(T,S,$,f){let M=wY.map(([J,F])=>({fn:F,i:T.search(J)})).sort((J,F)=>J.i-F.i).pop();return M.i===-1?Z1(this.first,f):M.fn(this.first,this.rest,S,$,f)}}function _W(T,S,$,f){let M=T instanceof Y$?T.value:T;if(M===void 0){if(T instanceof Y$?T.value=f.transform.undefined:M=T=f.transform.undefined,M===void 0)throw tT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+$.push(T instanceof Y$?(S.push(T.value),T.array?T.array[T.type||OW(T.value)]||T.type||d8(T.value):T.type):(S.push(T),OW(T)))}var l8=a8(KY);function b1(T,S,$,f,M,J){for(let F=1;F<T.strings.length;F++)S+=q1(S,$,f,M,J)+T.strings[F],$=T.args[F];return S}function q1(T,S,$,f,M){return S instanceof zW?S.build(T,$,f,M):S instanceof oS?I1(S,$,f,M):S instanceof vJ?S.value:S&&S[0]instanceof oS?S.reduce((J,F)=>J+" "+I1(F,$,f,M),""):_W(S,$,f,M)}function I1(T,S,$,f){return T.fragment=!0,b1(T,T.strings[0],T.args[0],S,$,f)}function u8(T,S,$,f,M){return T.map((J)=>"("+f.map((F)=>q1("values",J[F],S,$,M)).join(",")+")").join(",")}function i8(T,S,$,f,M){let J=Array.isArray(T[0]),F=S.length?S.flat():Object.keys(J?T[0]:T);return u8(J?T:[T],$,f,F,M)}function RW(T,S,$,f,M){if(typeof T==="string"&&(T=[T].concat(S)),Array.isArray(T))return Z1(T,M);let J;return(S.length?S.flat():Object.keys(T)).map((W)=>{return J=T[W],(J instanceof oS?I1(J,$,f,M):J instanceof vJ?J.value:_W(J,$,f,M))+" as "+HW(M.transform.column.to?M.transform.column.to(W):W)}).join(",")}var wY=Object.entries({values:i8,in:(...T)=>{let S=i8(...T);return S==="()"?"(null)":S},select:RW,as:RW,returning:RW,"\\(":RW,update(T,S,$,f,M){return(S.length?S.flat():Object.keys(T)).map((J)=>HW(M.transform.column.to?M.transform.column.to(J):J)+"="+q1("values",T[J],$,f,M))},insert(T,S,$,f,M){let J=S.length?S.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+Z1(J,M)+")values"+u8(Array.isArray(T)?T:[T],$,f,J,M)}}).map(([T,S])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),S]);function x1(){throw tT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:YY,parsers:RY}=l8;function d8(T){if(Array.isArray(T))return d8(T[0]);return typeof T==="string"?1009:0}var r8=function(T){let S=a8(T||{});return{serializers:Object.assign({},YY,S.serializers),parsers:Object.assign({},RY,S.parsers)}};function a8(T){return Object.keys(T).reduce((S,$)=>{if(T[$].from&&[].concat(T[$].from).forEach((f)=>S.parsers[f]=T[$].parse),T[$].serialize)S.serializers[T[$].to]=T[$].serialize,T[$].from&&[].concat(T[$].from).forEach((f)=>S.serializers[f]=T[$].serialize);return S},{parsers:{},serializers:{}})}function Z1(T,{transform:{column:S}}){return T.map(($)=>HW(S.to?S.to($):$)).join(",")}var HW=function T(S){return'"'+S.replace(/"/g,'""').replace(/\./g,'"."')+'"'},OW=function T(S){return S instanceof Y$?S.type:S instanceof Date?1184:S instanceof Uint8Array?17:S===!0||S===!1?16:typeof S==="bigint"?20:Array.isArray(S)?T(S[0]):0},OY=/\\/g,GY=/"/g;function zY(T){return T.replace(OY,"\\\\").replace(GY,'\\"')}var e8=function T(S,$,f,M){if(Array.isArray(S)===!1)return S;if(!S.length)return"{}";let J=S[0],F=M===1020?";":",";if(Array.isArray(J)&&!J.type)return"{"+S.map((W)=>T(W,$,f,M)).join(F)+"}";return"{"+S.map((W)=>{if(W===void 0){if(W=f.transform.undefined,W===void 0)throw tT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return W===null?"null":'"'+zY($?$(W.type?W.value:W):""+W)+'"'}).join(F)+"}"},j1={i:0,char:null,str:"",quoted:!1,last:0},s8=function T(S,$,f){return j1.i=j1.last=0,TK(j1,S,$,f)};function TK(T,S,$,f){let M=[],J=f===1020?";":",";for(;T.i<S.length;T.i++){if(T.char=S[T.i],T.quoted)if(T.char==="\\")T.str+=S[++T.i];else if(T.char==='"')M.push($?$(T.str):T.str),T.str="",T.quoted=S[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,M.push(TK(T,S,$,f));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&M.push($?$(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===J&&T.p!=="}"&&T.p!=='"')M.push($?$(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&M.push($?$(S.slice(T.last,T.i+1)):S.slice(T.last,T.i+1)),M}var Df=(T)=>{let S=T[0];for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Ef=(T)=>{let S=T[0].toUpperCase();for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Qf=(T)=>T.replace(/_/g,"-"),ZJ=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),mJ=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),hJ=(T)=>T.replace(/-/g,"_");function m1(T){return function S($,f){return typeof $==="object"&&$!==null&&(f.type===114||f.type===3802)?Array.isArray($)?$.map((M)=>S(M,f)):Object.entries($).reduce((M,[J,F])=>Object.assign(M,{[T(J)]:S(F,f)}),{}):$}}Df.column={from:Df};Df.value={from:m1(Df)};ZJ.column={to:ZJ};var h1={...Df};h1.column.to=ZJ;Ef.column={from:Ef};Ef.value={from:m1(Ef)};mJ.column={to:mJ};var v1={...Ef};v1.column.to=mJ;Qf.column={from:Qf};Qf.value={from:m1(Qf)};hJ.column={to:hJ};var P1={...Qf};P1.column.to=hJ;import SK from"net";import EY from"tls";import PJ from"crypto";import n1 from"stream";import{performance as $K}from"perf_hooks";class Uf extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var qS=_Y;function _Y(T=[]){let S=T.slice(),$=0;return{get length(){return S.length-$},remove:(f)=>{let M=S.indexOf(f);return M===-1?null:(S.splice(M,1),f)},push:(f)=>(S.push(f),f),shift:()=>{let f=S[$++];if($===S.length)$=0,S=[];else S[$-1]=void 0;return f}}}var wS=Buffer.allocUnsafe(256),HY="BCcDdEFfHPpQSX".split("").reduce((T,S)=>{let $=S.charCodeAt(0);return T[S]=()=>{return wS[0]=$,ET.i=5,ET},T},{}),ET=Object.assign(DY,HY,{N:String.fromCharCode(0),i:0,inc(T){return ET.i+=T,ET},str(T){let S=Buffer.byteLength(T);return DW(S),ET.i+=wS.write(T,ET.i,S,"utf8"),ET},i16(T){return DW(2),wS.writeUInt16BE(T,ET.i),ET.i+=2,ET},i32(T,S){if(S||S===0)return wS.writeUInt32BE(T,S),ET;return DW(4),wS.writeUInt32BE(T,ET.i),ET.i+=4,ET},z(T){return DW(T),wS.fill(0,ET.i,ET.i+T),ET.i+=T,ET},raw(T){return wS=Buffer.concat([wS.subarray(0,ET.i),T]),ET.i=wS.length,ET},end(T=1){wS.writeUInt32BE(ET.i-T,T);let S=wS.subarray(0,ET.i);return ET.i=0,wS=Buffer.allocUnsafe(256),S}}),d=ET;function DW(T){if(wS.length-ET.i<T){let S=wS,$=S.length;wS=Buffer.allocUnsafe($+($>>1)+T),S.copy(wS)}}function DY(){return ET.i=0,ET}var g1=JK,QY=1,a$=d().S().end(),fK=d().H().end(),UY=d().i32(8).i32(80877103).end(8),VY=Buffer.concat([d().E().str(d.N).i32(0).end(),a$]),BY=d().D().str("S").str(d.N).end(),HM=()=>{},LY=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),NY={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function JK(T,S={},{onopen:$=HM,onend:f=HM,onclose:M=HM}={}){let{ssl:J,max:F,user:W,host:A,port:k,database:X,parsers:y,transform:K,onnotice:G,onnotify:z,onparameter:Q,max_pipeline:E,keep_alive:B,backoff:L,target_session_attrs:b}=T,C=qS(),D=QY++,H={pid:null,secret:null},U=o1(ZW,T.idle_timeout),Z=o1(ZW,T.max_lifetime),h=o1(jK,T.connect_timeout),O=null,o,P=new Uf,a=Buffer.alloc(0),MT=T.fetch_types,fT={},UT={},VS=Math.random().toString(36).slice(2),N=1,p=0,kT=0,_T=0,pT=0,AT=0,VT=0,oT=0,bT=null,CT=null,JS=!1,BT=null,gS=null,FS=null,b$=null,iT=null,xT=null,tS=null,J$=null,m=null,UM=null,WS={queue:S.closed,idleTimer:U,connect(w){FS=w||!0,wA()},terminate:BM,execute:VM,cancel:LK,end:ZW,count:0,id:D};return S.closed&&S.closed.push(WS),WS;async function BK(){let w;try{w=T.socket?await Promise.resolve(T.socket(T)):new SK.Socket}catch(_){Nf(_);return}return w.on("error",Nf),w.on("close",YA),w.on("drain",yA),w}async function LK({pid:w,secret:_},r,zT){try{o=d().i32(16).i32(80877102).i32(w).i32(_).end(16),await KA(),O.once("error",zT),O.once("close",r)}catch(vT){zT(vT)}}function VM(w){if(JS)return pJ(w,tT.connection("CONNECTION_DESTROYED",T));if(w.cancelled)return;try{return w.state=H,m?C.push(w):(m=w,m.active=!0),xK(w),TS(NK(w))&&!w.describeFirst&&!w.cursorFn&&C.length<E&&(!w.options.onexecute||w.options.onexecute(WS))}catch(_){return C.length===0&&TS(a$),F$(_),!0}}function NK(w){if(w.parameters.length>=65534)throw tT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return w.options.simple?d().Q().str(w.statement.string+d.N).end():w.describeFirst?Buffer.concat([AA(w),fK]):w.prepare?w.prepared?tJ(w):Buffer.concat([AA(w),tJ(w)]):CK(w)}function AA(w){return Buffer.concat([OA(w.statement.string,w.parameters,w.statement.types,w.statement.name),R4("S",w.statement.name)])}function tJ(w){return Buffer.concat([Y4(w.parameters,w.statement.types,w.statement.name,w.cursorName),w.cursorFn?GA("",w.cursorRows):VY])}function CK(w){return Buffer.concat([OA(w.statement.string,w.parameters,w.statement.types),BY,tJ(w)])}function xK(w){let _=[],r=[],zT=b1(w,w.strings[0],w.args[0],_,r,T);!w.tagged&&w.args.forEach((vT)=>_W(vT,_,r,T)),w.prepare=T.prepare&&("prepare"in w.options?w.options.prepare:!0),w.string=zT,w.signature=w.prepare&&r+zT,w.onlyDescribe&&delete UT[w.signature],w.parameters=w.parameters||_,w.prepared=w.prepare&&w.signature in UT,w.describeFirst=w.onlyDescribe||_.length&&!w.prepared,w.statement=w.prepared?UT[w.signature]:{string:zT,types:r,name:w.prepare?VS+N++:""},typeof T.debug==="function"&&T.debug(D,zT,_,r)}function TS(w,_){if(xT=xT?Buffer.concat([xT,w]):Buffer.from(w),_||xT.length>=1024)return kA(_);return CT===null&&(CT=setImmediate(kA)),!0}function kA(w){let _=O.write(xT,w);return CT!==null&&clearImmediate(CT),xT=CT=null,_}function jK(){F$(tT.connection("CONNECT_TIMEOUT",T,O)),O.destroy()}async function XA(){if(TS(UY),!await new Promise((_)=>O.once("data",(r)=>_(r[0]===83)))&&J==="prefer")return Lf();O.removeAllListeners(),O=EY.connect({socket:O,servername:SK.isIP(O.host)?void 0:O.host,...J==="require"||J==="allow"||J==="prefer"?{rejectUnauthorized:!1}:J==="verify-full"?{}:typeof J==="object"?J:{}}),O.on("secureConnect",Lf),O.on("error",Nf),O.on("close",YA),O.on("drain",yA)}function yA(){!m&&$(WS)}function qW(w){if(BT){if(BT.push(w),kT-=w.length,kT>=0)return}a=BT?Buffer.concat(BT,AT-kT):a.length===0?w:Buffer.concat([a,w],a.length+w.length);while(a.length>4){if(AT=a.readUInt32BE(1),AT>=a.length){kT=AT-a.length,BT=[a];break}try{IK(a.subarray(0,AT+1))}catch(_){m&&(m.cursorFn||m.describeFirst)&&TS(a$),F$(_)}a=a.subarray(AT+1),kT=0,BT=null}}async function KA(){if(JS=!1,fT={},O||(O=await BK()),!O)return;if(h.start(),T.socket)return J?XA():Lf();if(O.on("connect",J?XA:Lf),T.path)return O.connect(T.path);O.ssl=J,O.connect(k[_T],A[_T]),O.host=A[_T],O.port=k[_T],_T=(_T+1)%k.length}function wA(){setTimeout(KA,p?p+VT-$K.now():0)}function Lf(){try{UT={},MT=T.fetch_types,VS=Math.random().toString(36).slice(2),N=1,Z.start(),O.on("data",qW),B&&O.setKeepAlive&&O.setKeepAlive(!0,1000*B);let w=G4();TS(w)}catch(w){Nf(w)}}function Nf(w){if(WS.queue===S.connecting&&T.host[pT+1])return;F$(w);while(C.length)pJ(C.shift(),w)}function F$(w){iT&&(iT.destroy(w),iT=null),m&&pJ(m,w),FS&&(pJ(FS,w),FS=null)}function pJ(w,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+w.origin.replace(/.*\n/,"\n"),enumerable:T.debug},query:{value:w.string,enumerable:T.debug},parameters:{value:w.parameters,enumerable:T.debug},args:{value:w.args,enumerable:T.debug},types:{value:w.statement&&w.statement.types,enumerable:T.debug}}),w.reject(_)}function ZW(){return b$||(!WS.reserved&&f(WS),!WS.reserved&&!FS&&!m&&C.length===0?(BM(),new Promise((w)=>O&&O.readyState!=="closed"?O.once("close",w):w())):b$=new Promise((w)=>tS=w))}function BM(){if(JS=!0,iT||m||FS||C.length)Nf(tT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(CT),O)O.removeListener("data",qW),O.removeListener("connect",Lf),O.readyState==="open"&&O.end(d().X().end());tS&&(tS(),b$=tS=null)}async function YA(w){if(a=Buffer.alloc(0),kT=0,BT=null,clearImmediate(CT),O.removeListener("data",qW),O.removeListener("connect",Lf),U.cancel(),Z.cancel(),h.cancel(),O.removeAllListeners(),O=null,FS)return wA();!w&&(m||C.length)&&Nf(tT.connection("CONNECTION_CLOSED",T,O)),p=$K.now(),w&&T.shared.retries++,VT=(typeof L==="function"?L(T.shared.retries):L)*1000,M(WS,tT.connection("CONNECTION_CLOSED",T,O))}function IK(w,_=w[0]){(_===68?bK:_===100?F4:_===65?T4:_===83?qK:_===90?ZK:_===67?mK:_===50?RA:_===49?hK:_===116?vK:_===84?PK:_===82?nK:_===110?iK:_===75?lK:_===69?eK:_===115?S4:_===51?$4:_===71?f4:_===78?A4:_===72?M4:_===99?W4:_===73?k4:_===86?X4:_===118?y4:_===87?J4:K4)(w)}function bK(w){let _=7,r,zT,vT,AS=m.isRaw?new Array(m.statement.columns.length):{};for(let YS=0;YS<m.statement.columns.length;YS++)zT=m.statement.columns[YS],r=w.readInt32BE(_),_+=4,vT=r===-1?null:m.isRaw===!0?w.subarray(_,_+=r):zT.parser===void 0?w.toString("utf8",_,_+=r):zT.parser.array===!0?zT.parser(w.toString("utf8",_+1,_+=r)):zT.parser(w.toString("utf8",_,_+=r)),m.isRaw?AS[YS]=m.isRaw===!0?vT:K.value.from?K.value.from(vT,zT):vT:AS[zT.name]=K.value.from?K.value.from(vT,zT):vT;m.forEachFn?m.forEachFn(K.row.from?K.row.from(AS):AS,P):P[oT++]=K.row.from?K.row.from(AS):AS}function qK(w){let[_,r]=w.toString("utf8",5,w.length-1).split(d.N);if(fT[_]=r,T.parameters[_]!==r)T.parameters[_]=r,Q&&Q(_,r)}function ZK(w){if(m&&m.options.simple&&m.resolve(gS||P),m=gS=null,P=new Uf,h.cancel(),FS){if(b){if(!fT.in_hot_standby||!fT.default_transaction_read_only)return aK();else if(rK(b,fT))return BM()}if(MT)return FS===!0&&(FS=null),uK();FS!==!0&&VM(FS),T.shared.retries=pT=0,FS=null;return}while(C.length&&(m=C.shift())&&(m.active=!0,m.cancelled))JK(T).cancel(m.state,m.cancelled.resolve,m.cancelled.reject);if(m)return;WS.reserved?!WS.reserved.release&&w[5]===73?b$?BM():(WS.reserved=null,$(WS)):WS.reserved():b$?BM():$(WS)}function mK(w){oT=0;for(let _=w.length-1;_>0;_--){if(w[_]===32&&w[_+1]<58&&P.count===null)P.count=+w.toString("utf8",_+1,w.length-1);if(w[_-1]>=65){P.command=w.toString("utf8",5,_),P.state=H;break}}if(UM&&(UM(),UM=null),P.command==="BEGIN"&&F!==1&&!WS.reserved)return F$(tT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(m.options.simple)return RA();if(m.cursorFn)P.count&&m.cursorFn(P),TS(a$);m.resolve(P)}function hK(){m.parsing=!1}function RA(){!P.statement&&(P.statement=m.statement),P.columns=m.statement.columns}function vK(w){let _=w.readUInt16BE(5);for(let r=0;r<_;++r)!m.statement.types[r]&&(m.statement.types[r]=w.readUInt32BE(7+r*4));m.prepare&&(UT[m.signature]=m.statement),m.describeFirst&&!m.onlyDescribe&&(TS(tJ(m)),m.describeFirst=!1)}function PK(w){if(P.command)gS=gS||[P],gS.push(P=new Uf),P.count=null,m.statement.columns=null;let _=w.readUInt16BE(5),r=7,zT;m.statement.columns=Array(_);for(let vT=0;vT<_;++vT){zT=r;while(w[r++]!==0);let AS=w.readUInt32BE(r),YS=w.readUInt16BE(r+4),q$=w.readUInt32BE(r+6);m.statement.columns[vT]={name:K.column.from?K.column.from(w.toString("utf8",zT,r-1)):w.toString("utf8",zT,r-1),parser:y[q$],table:AS,number:YS,type:q$},r+=18}if(P.statement=m.statement,m.onlyDescribe)return m.resolve(m.statement),TS(a$)}async function nK(w,_=w.readUInt32BE(5)){(_===3?cK:_===5?oK:_===10?gK:_===11?tK:_===12?pK:_!==0?w4:HM)(w,_)}async function cK(){let w=await mW();TS(d().p().str(w).z(1).end())}async function oK(w){let _="md5"+await MK(Buffer.concat([Buffer.from(await MK(await mW()+W)),w.subarray(9)]));TS(d().p().str(_).z(1).end())}async function gK(){J$=(await PJ.randomBytes(18)).toString("base64"),d().p().str("SCRAM-SHA-256"+d.N);let w=d.i;TS(d.inc(4).str("n,,n=*,r="+J$).i32(d.i-w-4,w).end())}async function tK(w){let _=w.toString("utf8",9).split(",").reduce((YS,q$)=>(YS[q$[0]]=q$.slice(2),YS),{}),r=await PJ.pbkdf2Sync(await mW(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),zT=await EW(r,"Client Key"),vT="n=*,r="+J$+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;bT=(await EW(await EW(r,"Server Key"),vT)).toString("base64");let AS="c=biws,r="+_.r+",p="+xY(zT,Buffer.from(await EW(await CY(zT),vT))).toString("base64");TS(d().p().str(AS).end())}function pK(w){if(w.toString("utf8",9).split(d.N,1)[0].slice(2)===bT)return;F$(tT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),O.destroy()}function mW(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function iK(){if(P.statement=m.statement,P.statement.columns=[],m.onlyDescribe)return m.resolve(m.statement),TS(a$)}function lK(w){H.pid=w.readUInt32BE(5),H.secret=w.readUInt32BE(9)}async function uK(){MT=!1,(await new oS([`
17
+ `,w.error.toString()),X.push({response:k,error:w.error})}return S?.error(`safegen was unable to generate well-formed data after ${A} failed attempts.`),M}}}function MX(T){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(T,null,2)].join(`
18
+ `)}import{createHash as gY}from"crypto";import*as uT from"fs";import*as E$ from"path";function oY(T){let S=T.replace(tY,"-");if(S.length<=64)return S;let $=gY("sha256").update(T).digest("hex");return S.slice(-64)+"+"+$}var tY=/[^a-zA-Z0-9\-._]/g;class Q0{mode;baseDir;filenameCache=new Map;filesTouched=new Map;constructor(T="off",S=E$.join(process.cwd(),".varmint")){this.mode=T,this.baseDir=S}read(T,S,$){let f=E$.join(this.baseDir,`${T}/${S}.input.json`);if(!uT.existsSync(f))throw new Error(`Squirrel: input file for key "${T}" does not exist`);let M=uT.readFileSync(f,"utf-8"),J=JSON.stringify($,null,"\t");if(J!==M)throw new Error(`Squirrel: the content of the cached input file ${f} does not match the input provided.
19
+
20
+ Provided:
21
+ ${J}
22
+
23
+ Cached:
24
+ ${M}`);let F=E$.join(this.baseDir,`${T}/${S}.output.json`);return JSON.parse(uT.readFileSync(F,"utf-8"))}async write(T,S,$,f){let M=E$.join(this.baseDir,T),J=E$.join(M,`${S}.input.json`),F=E$.join(M,`${S}.output.json`),W=JSON.stringify($,null,"\t");if(!uT.existsSync(this.baseDir))uT.mkdirSync(this.baseDir);if(!uT.existsSync(M))uT.mkdirSync(M);if(uT.writeFileSync(J,W),uT.existsSync(F))uT.unlinkSync(F);let A=await f(...$);return uT.writeFileSync(F,JSON.stringify(A,null,"\t")),A}add(T,S){return{flush:()=>{this.flush(T)},for:($)=>{if(this.mode!=="off"&&!this.filesTouched.has(T))this.filesTouched.set(T,new Set);return{get:async(...f)=>{let M=$;if(this.mode!=="off"){let J=this.filenameCache.get($);if(!J)J=oY($),this.filenameCache.set($,M),M=J;this.filesTouched.get(T)?.add(M)}switch(this.mode){case"off":return S(...f);case"read":return this.read(T,M,f);case"write":return this.write(T,M,f,S);case"read-write":try{return this.read(T,M,f)}catch(J){if(J instanceof Error)return this.write(T,M,f,S);throw J}}}}}}}flush(...T){for(let[S,$]of this.filesTouched.entries())if(T.length===0||T.includes(S)){let f=E$.join(this.baseDir,S),M=uT.readdirSync(f);for(let J of M){let F=J.replace(".input.json","").replace(".output.json","");if(!$.has(F))console.log(`\uD83D\uDCA5 Flushing ${F}`),uT.unlinkSync(E$.join(f,J))}}}}import{createHash as r6}from"crypto";var HF="RFC3986",EF={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},JX="RFC1738";var pY=Array.isArray,k$=(()=>{let T=[];for(let S=0;S<256;++S)T.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return T})();var U0=1024,FX=(T,S,$,f,M)=>{if(T.length===0)return T;let J=T;if(typeof T==="symbol")J=Symbol.prototype.toString.call(T);else if(typeof T!=="string")J=String(T);if($==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(W){return"%26%23"+parseInt(W.slice(2),16)+"%3B"});let F="";for(let W=0;W<J.length;W+=U0){let A=J.length>=U0?J.slice(W,W+U0):J,k=[];for(let X=0;X<A.length;++X){let w=A.charCodeAt(X);if(w===45||w===46||w===95||w===126||w>=48&&w<=57||w>=65&&w<=90||w>=97&&w<=122||M===JX&&(w===40||w===41)){k[k.length]=A.charAt(X);continue}if(w<128){k[k.length]=k$[w];continue}if(w<2048){k[k.length]=k$[192|w>>6]+k$[128|w&63];continue}if(w<55296||w>=57344){k[k.length]=k$[224|w>>12]+k$[128|w>>6&63]+k$[128|w&63];continue}X+=1,w=65536+((w&1023)<<10|A.charCodeAt(X)&1023),k[k.length]=k$[240|w>>18]+k$[128|w>>12&63]+k$[128|w>>6&63]+k$[128|w&63]}F+=k.join("")}return F};function WX(T){if(!T||typeof T!=="object")return!1;return!!(T.constructor&&T.constructor.isBuffer&&T.constructor.isBuffer(T))}function V0(T,S){if(pY(T)){let $=[];for(let f=0;f<T.length;f+=1)$.push(S(T[f]));return $}return S(T)}var iY=Object.prototype.hasOwnProperty,AX={brackets(T){return String(T)+"[]"},comma:"comma",indices(T,S){return String(T)+"["+S+"]"},repeat(T){return String(T)}},X$=Array.isArray,dY=Array.prototype.push,kX=function(T,S){dY.apply(T,X$(S)?S:[S])},uY=Date.prototype.toISOString,lT={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:FX,encodeValuesOnly:!1,format:HF,formatter:EF[HF],indices:!1,serializeDate(T){return uY.call(T)},skipNulls:!1,strictNullHandling:!1};function lY(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}var B0={};function XX(T,S,$,f,M,J,F,W,A,k,X,w,K,G,z,U,D,B){let L=T,Z=B,j=0,E=!1;while((Z=Z.get(B0))!==void 0&&!E){let R=Z.get(T);if(j+=1,typeof R!=="undefined")if(R===j)throw new RangeError("Cyclic object value");else E=!0;if(typeof Z.get(B0)==="undefined")j=0}if(typeof k==="function")L=k(S,L);else if(L instanceof Date)L=K?.(L);else if($==="comma"&&X$(L))L=V0(L,function(R){if(R instanceof Date)return K?.(R);return R});if(L===null){if(J)return A&&!U?A(S,lT.encoder,D,"key",G):S;L=""}if(lY(L)||WX(L)){if(A){let R=U?S:A(S,lT.encoder,D,"key",G);return[z?.(R)+"="+z?.(A(L,lT.encoder,D,"value",G))]}return[z?.(S)+"="+z?.(String(L))]}let _=[];if(typeof L==="undefined")return _;let Q;if($==="comma"&&X$(L)){if(U&&A)L=V0(L,A);Q=[{value:L.length>0?L.join(",")||null:void 0}]}else if(X$(k))Q=k;else{let R=Object.keys(L);Q=X?R.sort(X):R}let b=W?String(S).replace(/\./g,"%2E"):String(S),h=f&&X$(L)&&L.length===1?b+"[]":b;if(M&&X$(L)&&L.length===0)return h+"[]";for(let R=0;R<Q.length;++R){let g=Q[R],n=typeof g==="object"&&typeof g.value!=="undefined"?g.value:L[g];if(F&&n===null)continue;let p=w&&W?g.replace(/\./g,"%2E"):g,OT=X$(L)?typeof $==="function"?$(h,p):h:h+(w?"."+p:"["+p+"]");B.set(T,j);let _T=new WeakMap;_T.set(B0,B),kX(_,XX(n,OT,$,f,M,J,F,W,$==="comma"&&U&&X$(L)?null:A,k,X,w,K,G,z,U,D,_T))}return _}function rY(T=lT){if(typeof T.allowEmptyArrays!=="undefined"&&typeof T.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof T.encodeDotInKeys!=="undefined"&&typeof T.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(T.encoder!==null&&typeof T.encoder!=="undefined"&&typeof T.encoder!=="function")throw new TypeError("Encoder has to be a function.");let S=T.charset||lT.charset;if(typeof T.charset!=="undefined"&&T.charset!=="utf-8"&&T.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let $=HF;if(typeof T.format!=="undefined"){if(!iY.call(EF,T.format))throw new TypeError("Unknown format option provided.");$=T.format}let f=EF[$],M=lT.filter;if(typeof T.filter==="function"||X$(T.filter))M=T.filter;let J;if(T.arrayFormat&&T.arrayFormat in AX)J=T.arrayFormat;else if("indices"in T)J=T.indices?"indices":"repeat";else J=lT.arrayFormat;if("commaRoundTrip"in T&&typeof T.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let F=typeof T.allowDots==="undefined"?!!T.encodeDotInKeys===!0?!0:lT.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:lT.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:lT.allowEmptyArrays,arrayFormat:J,charset:S,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:lT.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?lT.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:lT.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:lT.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:lT.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:lT.encodeValuesOnly,filter:M,format:$,formatter:f,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:lT.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:lT.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:lT.strictNullHandling}}function L0(T,S={}){let $=T,f=rY(S),M,J;if(typeof f.filter==="function")J=f.filter,$=J("",$);else if(X$(f.filter))J=f.filter,M=J;let F=[];if(typeof $!=="object"||$===null)return"";let W=AX[f.arrayFormat],A=W==="comma"&&f.commaRoundTrip;if(!M)M=Object.keys($);if(f.sort)M.sort(f.sort);let k=new WeakMap;for(let K=0;K<M.length;++K){let G=M[K];if(f.skipNulls&&$[G]===null)continue;kX(F,XX($[G],G,W,A,f.allowEmptyArrays,f.strictNullHandling,f.skipNulls,f.encodeDotInKeys,f.encode?f.encoder:null,f.filter,f.sort,f.allowDots,f.serializeDate,f.format,f.formatter,f.encodeValuesOnly,f.charset,k))}let X=F.join(f.delimiter),w=f.addQueryPrefix===!0?"?":"";if(f.charsetSentinel)if(f.charset==="iso-8859-1")w+="utf8=%26%2310003%3B&";else w+="utf8=%E2%9C%93&";return X.length>0?w+X:""}var Jf="4.76.0";var wX=!1,Ff=void 0,N0=void 0,eY=void 0,sY=void 0,T6=void 0,C0=void 0,S6=void 0,DF=void 0,x0=void 0,j0=void 0,I0=void 0,QF=void 0,b0=void 0;function KX(T,S={auto:!1}){if(wX)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(Ff)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${Ff}'\``);wX=S.auto,Ff=T.kind,N0=T.fetch,eY=T.Request,sY=T.Response,T6=T.Headers,C0=T.FormData,S6=T.Blob,DF=T.File,x0=T.ReadableStream,j0=T.getMultipartRequestOptions,I0=T.getDefaultAgent,QF=T.fileFromPath,b0=T.isFsReadStream}class Z0{constructor(T){this.body=T}get[Symbol.toStringTag](){return"MultipartBody"}}function YX({manuallyImported:T}={}){let S=T?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",$,f,M,J;try{$=fetch,f=Request,M=Response,J=Headers}catch(F){throw new Error(`this environment is missing the following Web Fetch API type: ${F.message}. ${S}`)}return{kind:"web",fetch:$,Request:f,Response:M,Headers:J,FormData:typeof FormData!=="undefined"?FormData:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${S}`)}},Blob:typeof Blob!=="undefined"?Blob:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${S}`)}},File:typeof File!=="undefined"?File:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${S}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class F{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${S}`)}},getMultipartRequestOptions:async(F,W)=>({...W,body:new Z0(F)}),getDefaultAgent:(F)=>{return},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(F)=>!1}}import{ReadStream as f6}from"fs";function yX(){let T=YX();function S($){return $ instanceof f6}return{...T,isFsReadStream:S}}if(!Ff)KX(yX(),{auto:!0});class $T extends Error{}class gT extends $T{constructor(T,S,$,f){super(`${gT.makeMessage(T,S,$)}`);this.status=T,this.headers=f,this.request_id=f?.["x-request-id"];let M=S;this.error=M,this.code=M?.code,this.param=M?.param,this.type=M?.type}static makeMessage(T,S,$){let f=S?.message?typeof S.message==="string"?S.message:JSON.stringify(S.message):S?JSON.stringify(S):$;if(T&&f)return`${T} ${f}`;if(T)return`${T} status code (no body)`;if(f)return f;return"(no status code or body)"}static generate(T,S,$,f){if(!T)return new Wf({message:$,cause:IF(S)});let M=S?.error;if(T===400)return new UF(T,M,$,f);if(T===401)return new VF(T,M,$,f);if(T===403)return new BF(T,M,$,f);if(T===404)return new LF(T,M,$,f);if(T===409)return new NF(T,M,$,f);if(T===422)return new CF(T,M,$,f);if(T===429)return new xF(T,M,$,f);if(T>=500)return new jF(T,M,$,f);return new gT(T,M,$,f)}}class SS extends gT{constructor({message:T}={}){super(void 0,void 0,T||"Request was aborted.",void 0);this.status=void 0}}class Wf extends gT{constructor({message:T,cause:S}){super(void 0,void 0,T||"Connection error.",void 0);if(this.status=void 0,S)this.cause=S}}class Af extends Wf{constructor({message:T}={}){super({message:T??"Request timed out."})}}class UF extends gT{constructor(){super(...arguments);this.status=400}}class VF extends gT{constructor(){super(...arguments);this.status=401}}class BF extends gT{constructor(){super(...arguments);this.status=403}}class LF extends gT{constructor(){super(...arguments);this.status=404}}class NF extends gT{constructor(){super(...arguments);this.status=409}}class CF extends gT{constructor(){super(...arguments);this.status=422}}class xF extends gT{constructor(){super(...arguments);this.status=429}}class jF extends gT{}class eM extends $T{constructor(){super("Could not parse response content as the length limit was reached")}}class sM extends $T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class t${constructor(){this.buffer=[],this.trailingCR=!1}decode(T){let S=this.decodeText(T);if(this.trailingCR)S="\r"+S,this.trailingCR=!1;if(S.endsWith("\r"))this.trailingCR=!0,S=S.slice(0,-1);if(!S)return[];let $=t$.NEWLINE_CHARS.has(S[S.length-1]||""),f=S.split(t$.NEWLINE_REGEXP);if($)f.pop();if(f.length===1&&!$)return this.buffer.push(f[0]),[];if(this.buffer.length>0)f=[this.buffer.join("")+f[0],...f.slice(1)],this.buffer=[];if(!$)this.buffer=[f.pop()||""];return f}decodeText(T){if(T==null)return"";if(typeof T==="string")return T;if(typeof Buffer!=="undefined"){if(T instanceof Buffer)return T.toString();if(T instanceof Uint8Array)return Buffer.from(T).toString();throw new $T(`Unexpected: received non-Uint8Array (${T.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder!=="undefined"){if(T instanceof Uint8Array||T instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(T);throw new $T(`Unexpected: received non-Uint8Array/ArrayBuffer (${T.constructor.name}) in a web platform. Please report this error.`)}throw new $T("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let T=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,T}}t$.NEWLINE_CHARS=new Set([`
25
+ `,"\r"]);t$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class NS{constructor(T,S){this.iterator=T,this.controller=S}static fromSSEResponse(T,S){let $=!1;async function*f(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let M=!1;try{for await(let J of J6(T,S)){if(M)continue;if(J.data.startsWith("[DONE]")){M=!0;continue}if(J.event===null){let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(F&&F.error)throw new gT(void 0,F.error,void 0,void 0);yield F}else{let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(J.event=="error")throw new gT(void 0,F.error,F.message,void 0);yield{event:J.event,data:F}}}M=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!M)S.abort()}}return new NS(f,S)}static fromReadableStream(T,S){let $=!1;async function*f(){let J=new t$,F=RX(T);for await(let W of F)for(let A of J.decode(W))yield A;for(let W of J.flush())yield W}async function*M(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let J=!1;try{for await(let F of f()){if(J)continue;if(F)yield JSON.parse(F)}J=!0}catch(F){if(F instanceof Error&&F.name==="AbortError")return;throw F}finally{if(!J)S.abort()}}return new NS(M,S)}[Symbol.asyncIterator](){return this.iterator()}tee(){let T=[],S=[],$=this.iterator(),f=(M)=>{return{next:()=>{if(M.length===0){let J=$.next();T.push(J),S.push(J)}return M.shift()}}};return[new NS(()=>f(T),this.controller),new NS(()=>f(S),this.controller)]}toReadableStream(){let T=this,S,$=new TextEncoder;return new x0({async start(){S=T[Symbol.asyncIterator]()},async pull(f){try{let{value:M,done:J}=await S.next();if(J)return f.close();let F=$.encode(JSON.stringify(M)+`
26
+ `);f.enqueue(F)}catch(M){f.error(M)}},async cancel(){await S.return?.()}})}}async function*J6(T,S){if(!T.body)throw S.abort(),new $T("Attempted to iterate over a response with no body");let $=new OX,f=new t$,M=RX(T.body);for await(let J of F6(M))for(let F of f.decode(J)){let W=$.decode(F);if(W)yield W}for(let J of f.flush()){let F=$.decode(J);if(F)yield F}}async function*F6(T){let S=new Uint8Array;for await(let $ of T){if($==null)continue;let f=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,M=new Uint8Array(S.length+f.length);M.set(S),M.set(f,S.length),S=M;let J;while((J=W6(S))!==-1)yield S.slice(0,J),S=S.slice(J)}if(S.length>0)yield S}function W6(T){for(let f=0;f<T.length-2;f++){if(T[f]===10&&T[f+1]===10)return f+2;if(T[f]===13&&T[f+1]===13)return f+2;if(T[f]===13&&T[f+1]===10&&f+3<T.length&&T[f+2]===13&&T[f+3]===10)return f+4}return-1}class OX{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(T){if(T.endsWith("\r"))T=T.substring(0,T.length-1);if(!T){if(!this.event&&!this.data.length)return null;let M={event:this.event,data:this.data.join(`
27
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],M}if(this.chunks.push(T),T.startsWith(":"))return null;let[S,$,f]=A6(T,":");if(f.startsWith(" "))f=f.substring(1);if(S==="event")this.event=f;else if(S==="data")this.data.push(f);return null}}function A6(T,S){let $=T.indexOf(S);if($!==-1)return[T.substring(0,$),S,T.substring($+S.length)];return[T,"",""]}function RX(T){if(T[Symbol.asyncIterator])return T;let S=T.getReader();return{async next(){try{let $=await S.read();if($?.done)S.releaseLock();return $}catch($){throw S.releaseLock(),$}},async return(){let $=S.cancel();return S.releaseLock(),await $,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var GX=(T)=>T!=null&&typeof T==="object"&&typeof T.url==="string"&&typeof T.blob==="function",zX=(T)=>T!=null&&typeof T==="object"&&typeof T.name==="string"&&typeof T.lastModified==="number"&&TJ(T),TJ=(T)=>T!=null&&typeof T==="object"&&typeof T.size==="number"&&typeof T.type==="string"&&typeof T.text==="function"&&typeof T.slice==="function"&&typeof T.arrayBuffer==="function",k6=(T)=>{return zX(T)||GX(T)||b0(T)};async function h0(T,S,$){if(T=await T,zX(T))return T;if(GX(T)){let M=await T.blob();S||(S=new URL(T.url).pathname.split(/[\\/]/).pop()??"unknown_file");let J=TJ(M)?[await M.arrayBuffer()]:[M];return new DF(J,S,$)}let f=await X6(T);if(S||(S=K6(T)??"unknown_file"),!$?.type){let M=f[0]?.type;if(typeof M==="string")$={...$,type:M}}return new DF(f,S,$)}async function X6(T){let S=[];if(typeof T==="string"||ArrayBuffer.isView(T)||T instanceof ArrayBuffer)S.push(T);else if(TJ(T))S.push(await T.arrayBuffer());else if(Y6(T))for await(let $ of T)S.push($);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${w6(T)}`);return S}function w6(T){return`[${Object.getOwnPropertyNames(T).map(($)=>`"${$}"`).join(", ")}]`}function K6(T){return q0(T.name)||q0(T.filename)||q0(T.path)?.split(/[\\/]/).pop()}var q0=(T)=>{if(typeof T==="string")return T;if(typeof Buffer!=="undefined"&&T instanceof Buffer)return String(T);return},Y6=(T)=>T!=null&&typeof T==="object"&&typeof T[Symbol.asyncIterator]==="function",v0=(T)=>T&&typeof T==="object"&&T.body&&T[Symbol.toStringTag]==="MultipartBody";var vS=async(T)=>{let S=await _X(T.body);return j0(S,T)},_X=async(T)=>{let S=new C0;return await Promise.all(Object.entries(T||{}).map(([$,f])=>m0(S,$,f))),S};var m0=async(T,S,$)=>{if($===void 0)return;if($==null)throw new TypeError(`Received null for "${S}"; to pass null in FormData, you must use the string 'null'`);if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")T.append(S,String($));else if(k6($)){let f=await h0($);T.append(S,f)}else if(Array.isArray($))await Promise.all($.map((f)=>m0(T,S+"[]",f)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([f,M])=>m0(T,`${S}[${f}]`,M)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};var O6=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},R6=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},bF;async function VX(T){let{response:S}=T;if(T.options.stream){if(sf("response",S.status,S.url,S.headers,S.body),T.options.__streamClass)return T.options.__streamClass.fromSSEResponse(S,T.controller);return NS.fromSSEResponse(S,T.controller)}if(S.status===204)return null;if(T.options.__binaryResponse)return S;let $=S.headers.get("content-type");if($?.includes("application/json")||$?.includes("application/vnd.api+json")){let J=await S.json();return sf("response",S.status,S.url,S.headers,J),BX(J,S)}let M=await S.text();return sf("response",S.status,S.url,S.headers,M),M}function BX(T,S){if(!T||typeof T!=="object"||Array.isArray(T))return T;return Object.defineProperty(T,"_request_id",{value:S.headers.get("x-request-id"),enumerable:!1})}class ZF extends Promise{constructor(T,S=VX){super(($)=>{$(null)});this.responsePromise=T,this.parseResponse=S}_thenUnwrap(T){return new ZF(this.responsePromise,async(S)=>BX(T(await this.parseResponse(S),S),S.response))}asResponse(){return this.responsePromise.then((T)=>T.response)}async withResponse(){let[T,S]=await Promise.all([this.parse(),this.asResponse()]);return{data:T,response:S,request_id:S.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(T,S){return this.parse().then(T,S)}catch(T){return this.parse().catch(T)}finally(T){return this.parse().finally(T)}}class n0{constructor({baseURL:T,maxRetries:S=2,timeout:$=600000,httpAgent:f,fetch:M}){this.baseURL=T,this.maxRetries=P0("maxRetries",S),this.timeout=P0("timeout",$),this.httpAgent=f,this.fetch=M??N0}authHeaders(T){return{}}defaultHeaders(T){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...E6(),...this.authHeaders(T)}}validateHeaders(T,S){}defaultIdempotencyKey(){return`stainless-node-retry-${V6()}`}get(T,S){return this.methodRequest("get",T,S)}post(T,S){return this.methodRequest("post",T,S)}patch(T,S){return this.methodRequest("patch",T,S)}put(T,S){return this.methodRequest("put",T,S)}delete(T,S){return this.methodRequest("delete",T,S)}methodRequest(T,S,$){return this.request(Promise.resolve($).then(async(f)=>{let M=f&&TJ(f?.body)?new DataView(await f.body.arrayBuffer()):f?.body instanceof DataView?f.body:f?.body instanceof ArrayBuffer?new DataView(f.body):f&&ArrayBuffer.isView(f?.body)?new DataView(f.body.buffer):f?.body;return{method:T,path:S,...f,body:M}}))}getAPIList(T,S,$){return this.requestAPIList(S,{method:"get",path:T,...$})}calculateContentLength(T){if(typeof T==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(T,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(T).length.toString()}else if(ArrayBuffer.isView(T))return T.byteLength.toString();return null}buildRequest(T,{retryCount:S=0}={}){let{method:$,path:f,query:M,headers:J={}}=T,F=ArrayBuffer.isView(T.body)||T.__binaryRequest&&typeof T.body==="string"?T.body:v0(T.body)?T.body.body:T.body?JSON.stringify(T.body,null,2):null,W=this.calculateContentLength(F),A=this.buildURL(f,M);if("timeout"in T)P0("timeout",T.timeout);let k=T.timeout??this.timeout,X=T.httpAgent??this.httpAgent??I0(A),w=k+1000;if(typeof X?.options?.timeout==="number"&&w>(X.options.timeout??0))X.options.timeout=w;if(this.idempotencyHeader&&$!=="get"){if(!T.idempotencyKey)T.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=T.idempotencyKey}let K=this.buildHeaders({options:T,headers:J,contentLength:W,retryCount:S});return{req:{method:$,...F&&{body:F},headers:K,...X&&{agent:X},signal:T.signal??null},url:A,timeout:k}}buildHeaders({options:T,headers:S,contentLength:$,retryCount:f}){let M={};if($)M["content-length"]=$;let J=this.defaultHeaders(T);if(QX(M,J),QX(M,S),v0(T.body)&&Ff!=="node")delete M["content-type"];if(UX(J,"x-stainless-retry-count")===void 0&&UX(S,"x-stainless-retry-count")===void 0)M["x-stainless-retry-count"]=String(f);return this.validateHeaders(M,S),M}async prepareOptions(T){}async prepareRequest(T,{url:S,options:$}){}parseHeaders(T){return!T?{}:(Symbol.iterator in T)?Object.fromEntries(Array.from(T).map((S)=>[...S])):{...T}}makeStatusError(T,S,$,f){return gT.generate(T,S,$,f)}request(T,S=null){return new ZF(this.makeRequest(T,S))}async makeRequest(T,S){let $=await T,f=$.maxRetries??this.maxRetries;if(S==null)S=f;await this.prepareOptions($);let{req:M,url:J,timeout:F}=this.buildRequest($,{retryCount:f-S});if(await this.prepareRequest(M,{url:J,options:$}),sf("request",J,$,M.headers),$.signal?.aborted)throw new SS;let W=new AbortController,A=await this.fetchWithTimeout(J,M,F,W).catch(IF);if(A instanceof Error){if($.signal?.aborted)throw new SS;if(S)return this.retryRequest($,S);if(A.name==="AbortError")throw new Af;throw new Wf({cause:A})}let k=G6(A.headers);if(!A.ok){if(S&&this.shouldRetry(A)){let U=`retrying, ${S} attempts remaining`;return sf(`response (error; ${U})`,A.status,J,k),this.retryRequest($,S,k)}let X=await A.text().catch((U)=>IF(U).message),w=D6(X),K=w?void 0:X;throw sf(`response (error; ${S?"(error; no more retries left)":"(error; not retryable)"})`,A.status,J,k,K),this.makeStatusError(A.status,w,K,k)}return{response:A,options:$,controller:W}}requestAPIList(T,S){let $=this.makeRequest(S,null);return new LX(this,$,T)}buildURL(T,S){let $=U6(T)?new URL(T):new URL(this.baseURL+(this.baseURL.endsWith("/")&&T.startsWith("/")?T.slice(1):T)),f=this.defaultQuery();if(!NX(f))S={...f,...S};if(typeof S==="object"&&S&&!Array.isArray(S))$.search=this.stringifyQuery(S);return $.toString()}stringifyQuery(T){return Object.entries(T).filter(([S,$])=>typeof $!=="undefined").map(([S,$])=>{if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return`${encodeURIComponent(S)}=${encodeURIComponent($)}`;if($===null)return`${encodeURIComponent(S)}=`;throw new $T(`Cannot stringify type ${typeof $}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(T,S,$,f){let{signal:M,...J}=S||{};if(M)M.addEventListener("abort",()=>f.abort());let F=setTimeout(()=>f.abort(),$);return this.getRequestClient().fetch.call(void 0,T,{signal:f.signal,...J}).finally(()=>{clearTimeout(F)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(T){let S=T.headers.get("x-should-retry");if(S==="true")return!0;if(S==="false")return!1;if(T.status===408)return!0;if(T.status===409)return!0;if(T.status===429)return!0;if(T.status>=500)return!0;return!1}async retryRequest(T,S,$){let f,M=$?.["retry-after-ms"];if(M){let F=parseFloat(M);if(!Number.isNaN(F))f=F}let J=$?.["retry-after"];if(J&&!f){let F=parseFloat(J);if(!Number.isNaN(F))f=F*1000;else f=Date.parse(J)-Date.now()}if(!(f&&0<=f&&f<60000)){let F=T.maxRetries??this.maxRetries;f=this.calculateDefaultRetryTimeoutMillis(S,F)}return await D$(f),this.makeRequest(T,S-1)}calculateDefaultRetryTimeoutMillis(T,S){let M=S-T,J=Math.min(0.5*Math.pow(2,M),8),F=1-Math.random()*0.25;return J*F*1000}getUserAgent(){return`${this.constructor.name}/JS ${Jf}`}}class qF{constructor(T,S,$,f){bF.set(this,void 0),O6(this,bF,T,"f"),this.options=f,this.response=S,this.body=$}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let T=this.nextPageInfo();if(!T)throw new $T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let S={...this.options};if("params"in T&&typeof S.query==="object")S.query={...S.query,...T.params};else if("url"in T){let $=[...Object.entries(S.query||{}),...T.url.searchParams.entries()];for(let[f,M]of $)T.url.searchParams.set(f,M);S.query=void 0,S.path=T.url.toString()}return await R6(this,bF,"f").requestAPIList(this.constructor,S)}async*iterPages(){let T=this;yield T;while(T.hasNextPage())T=await T.getNextPage(),yield T}async*[(bF=new WeakMap,Symbol.asyncIterator)](){for await(let T of this.iterPages())for(let S of T.getPaginatedItems())yield S}}class LX extends ZF{constructor(T,S,$){super(S,async(f)=>new $(T,f.response,await VX(f),f.options))}async*[Symbol.asyncIterator](){let T=await this;for await(let S of T)yield S}}var G6=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get(S,$){let f=$.toString();return S[f.toLowerCase()]||S[f]}})},z6={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},BT=(T)=>{return typeof T==="object"&&T!==null&&!NX(T)&&Object.keys(T).every((S)=>CX(z6,S))},_6=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jf,"X-Stainless-OS":EX(Deno.build.os),"X-Stainless-Arch":HX(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime!=="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process!=="undefined"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jf,"X-Stainless-OS":EX(process.platform),"X-Stainless-Arch":HX(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let T=H6();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${T.browser}`,"X-Stainless-Runtime-Version":T.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function H6(){if(typeof navigator==="undefined"||!navigator)return null;let T=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:S,pattern:$}of T){let f=$.exec(navigator.userAgent);if(f){let M=f[1]||0,J=f[2]||0,F=f[3]||0;return{browser:S,version:`${M}.${J}.${F}`}}}return null}var HX=(T)=>{if(T==="x32")return"x32";if(T==="x86_64"||T==="x64")return"x64";if(T==="arm")return"arm";if(T==="aarch64"||T==="arm64")return"arm64";if(T)return`other:${T}`;return"unknown"},EX=(T)=>{if(T=T.toLowerCase(),T.includes("ios"))return"iOS";if(T==="android")return"Android";if(T==="darwin")return"MacOS";if(T==="win32")return"Windows";if(T==="freebsd")return"FreeBSD";if(T==="openbsd")return"OpenBSD";if(T==="linux")return"Linux";if(T)return`Other:${T}`;return"Unknown"},DX,E6=()=>{return DX??(DX=_6())},D6=(T)=>{try{return JSON.parse(T)}catch(S){return}},Q6=new RegExp("^(?:[a-z]+:)?//","i"),U6=(T)=>{return Q6.test(T)},D$=(T)=>new Promise((S)=>setTimeout(S,T)),P0=(T,S)=>{if(typeof S!=="number"||!Number.isInteger(S))throw new $T(`${T} must be an integer`);if(S<0)throw new $T(`${T} must be a positive integer`);return S},IF=(T)=>{if(T instanceof Error)return T;if(typeof T==="object"&&T!==null)try{return new Error(JSON.stringify(T))}catch{}return new Error(T)};var SJ=(T)=>{if(typeof process!=="undefined")return process.env?.[T]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(T)?.trim();return};function NX(T){if(!T)return!0;for(let S in T)return!1;return!0}function CX(T,S){return Object.prototype.hasOwnProperty.call(T,S)}function QX(T,S){for(let $ in S){if(!CX(S,$))continue;let f=$.toLowerCase();if(!f)continue;let M=S[$];if(M===null)delete T[f];else if(M!==void 0)T[f]=M}}function sf(T,...S){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true")console.log(`OpenAI:DEBUG:${T}`,...S)}var V6=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(T)=>{let S=Math.random()*16|0;return(T==="x"?S:S&3|8).toString(16)})},xX=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},B6=(T)=>{return typeof T?.get==="function"};var UX=(T,S)=>{let $=S.toLowerCase();if(B6(T)){let f=S[0]?.toUpperCase()+S.substring(1).replace(/([^\w])(\w)/g,(M,J,F)=>J+F.toUpperCase());for(let M of[S,$,S.toUpperCase(),f]){let J=T.get(M);if(J)return J}}for(let[f,M]of Object.entries(T))if(f.toLowerCase()===$){if(Array.isArray(M)){if(M.length<=1)return M[0];return console.warn(`Received ${M.length} entries for the ${S} header, using the first entry.`),M[0]}return M}return};function $J(T){return T!=null&&typeof T==="object"&&!Array.isArray(T)}class c0 extends qF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[],this.object=$.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class vT extends qF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){let T=this.nextPageInfo();if(!T)return null;if("params"in T)return T.params;let S=Object.fromEntries(T.url.searchParams);if(!Object.keys(S).length)return null;return S}nextPageInfo(){let T=this.getPaginatedItems();if(!T.length)return null;let S=T[T.length-1]?.id;if(!S)return null;return{params:{after:S}}}}class i{constructor(T){this._client=T}}class fJ extends i{create(T,S){return this._client.post("/chat/completions",{body:T,...S,stream:T.stream??!1})}}class Xf extends i{constructor(){super(...arguments);this.completions=new fJ(this._client)}}Xf.Completions=fJ;class MJ extends i{create(T,S){return this._client.post("/audio/speech",{body:T,...S,__binaryResponse:!0})}}class JJ extends i{create(T,S){return this._client.post("/audio/transcriptions",vS({body:T,...S}))}}class FJ extends i{create(T,S){return this._client.post("/audio/translations",vS({body:T,...S}))}}class Q$ extends i{constructor(){super(...arguments);this.transcriptions=new JJ(this._client),this.translations=new FJ(this._client),this.speech=new MJ(this._client)}}Q$.Transcriptions=JJ;Q$.Translations=FJ;Q$.Speech=MJ;class wf extends i{create(T,S){return this._client.post("/batches",{body:T,...S})}retrieve(T,S){return this._client.get(`/batches/${T}`,S)}list(T={},S){if(BT(T))return this.list({},T);return this._client.getAPIList("/batches",TM,{query:T,...S})}cancel(T,S){return this._client.post(`/batches/${T}/cancel`,S)}}class TM extends vT{}wf.BatchesPage=TM;class SM extends i{create(T,S){return this._client.post("/assistants",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/assistants/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(BT(T))return this.list({},T);return this._client.getAPIList("/assistants",WJ,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class WJ extends vT{}SM.AssistantsPage=WJ;function g0(T){return typeof T.parse==="function"}var p$=(T)=>{return T?.role==="assistant"},o0=(T)=>{return T?.role==="function"},t0=(T)=>{return T?.role==="tool"};var sS=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},mT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},p0,mF,hF,AJ,kJ,vF,XJ,U$,wJ,PF,nF,$M,jX;class KJ{constructor(){p0.add(this),this.controller=new AbortController,mF.set(this,void 0),hF.set(this,()=>{}),AJ.set(this,()=>{}),kJ.set(this,void 0),vF.set(this,()=>{}),XJ.set(this,()=>{}),U$.set(this,{}),wJ.set(this,!1),PF.set(this,!1),nF.set(this,!1),$M.set(this,!1),sS(this,mF,new Promise((T,S)=>{sS(this,hF,T,"f"),sS(this,AJ,S,"f")}),"f"),sS(this,kJ,new Promise((T,S)=>{sS(this,vF,T,"f"),sS(this,XJ,S,"f")}),"f"),mT(this,mF,"f").catch(()=>{}),mT(this,kJ,"f").catch(()=>{})}_run(T){setTimeout(()=>{T().then(()=>{this._emitFinal(),this._emit("end")},mT(this,p0,"m",jX).bind(this))},0)}_connected(){if(this.ended)return;mT(this,hF,"f").call(this),this._emit("connect")}get ended(){return mT(this,wJ,"f")}get errored(){return mT(this,PF,"f")}get aborted(){return mT(this,nF,"f")}abort(){this.controller.abort()}on(T,S){return(mT(this,U$,"f")[T]||(mT(this,U$,"f")[T]=[])).push({listener:S}),this}off(T,S){let $=mT(this,U$,"f")[T];if(!$)return this;let f=$.findIndex((M)=>M.listener===S);if(f>=0)$.splice(f,1);return this}once(T,S){return(mT(this,U$,"f")[T]||(mT(this,U$,"f")[T]=[])).push({listener:S,once:!0}),this}emitted(T){return new Promise((S,$)=>{if(sS(this,$M,!0,"f"),T!=="error")this.once("error",$);this.once(T,S)})}async done(){sS(this,$M,!0,"f"),await mT(this,kJ,"f")}_emit(T,...S){if(mT(this,wJ,"f"))return;if(T==="end")sS(this,wJ,!0,"f"),mT(this,vF,"f").call(this);let $=mT(this,U$,"f")[T];if($)mT(this,U$,"f")[T]=$.filter((f)=>!f.once),$.forEach(({listener:f})=>f(...S));if(T==="abort"){let f=S[0];if(!mT(this,$M,"f")&&!$?.length)Promise.reject(f);mT(this,AJ,"f").call(this,f),mT(this,XJ,"f").call(this,f),this._emit("end");return}if(T==="error"){let f=S[0];if(!mT(this,$M,"f")&&!$?.length)Promise.reject(f);mT(this,AJ,"f").call(this,f),mT(this,XJ,"f").call(this,f),this._emit("end")}}_emitFinal(){}}mF=new WeakMap,hF=new WeakMap,AJ=new WeakMap,kJ=new WeakMap,vF=new WeakMap,XJ=new WeakMap,U$=new WeakMap,wJ=new WeakMap,PF=new WeakMap,nF=new WeakMap,$M=new WeakMap,p0=new WeakSet,jX=function T(S){if(sS(this,PF,!0,"f"),S instanceof Error&&S.name==="AbortError")S=new SS;if(S instanceof SS)return sS(this,nF,!0,"f"),this._emit("abort",S);if(S instanceof $T)return this._emit("error",S);if(S instanceof Error){let $=new $T(S.message);return $.cause=S,this._emit("error",$)}return this._emit("error",new $T(String(S)))};function i0(T){return T?.$brand==="auto-parseable-response-format"}function Kf(T){return T?.$brand==="auto-parseable-tool"}function IX(T,S){if(!S||!d0(S))return{...T,choices:T.choices.map(($)=>({...$,message:{...$.message,parsed:null,tool_calls:$.message.tool_calls??[]}}))};return YJ(T,S)}function YJ(T,S){let $=T.choices.map((f)=>{if(f.finish_reason==="length")throw new eM;if(f.finish_reason==="content_filter")throw new sM;return{...f,message:{...f.message,tool_calls:f.message.tool_calls?.map((M)=>b6(S,M))??[],parsed:f.message.content&&!f.message.refusal?I6(S,f.message.content):null}}});return{...T,choices:$}}function I6(T,S){if(T.response_format?.type!=="json_schema")return null;if(T.response_format?.type==="json_schema"){if("$parseRaw"in T.response_format)return T.response_format.$parseRaw(S);return JSON.parse(S)}return null}function b6(T,S){let $=T.tools?.find((f)=>f.function?.name===S.function.name);return{...S,function:{...S.function,parsed_arguments:Kf($)?$.$parseRaw(S.function.arguments):$?.function.strict?JSON.parse(S.function.arguments):null}}}function bX(T,S){if(!T)return!1;let $=T.tools?.find((f)=>f.function?.name===S.function.name);return Kf($)||$?.function.strict||!1}function d0(T){if(i0(T.response_format))return!0;return T.tools?.some((S)=>Kf(S)||S.type==="function"&&S.function.strict===!0)??!1}function ZX(T){for(let S of T??[]){if(S.type!=="function")throw new $T(`Currently only \`function\` tool types support auto-parsing; Received \`${S.type}\``);if(S.function.strict!==!0)throw new $T(`The \`${S.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var QS=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},YS,u0,cF,l0,r0,a0,mX,e0,qX=10;class yJ extends KJ{constructor(){super(...arguments);YS.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(T){this._chatCompletions.push(T),this._emit("chatCompletion",T);let S=T.choices[0]?.message;if(S)this._addMessage(S);return T}_addMessage(T,S=!0){if(!("content"in T))T.content=null;if(this.messages.push(T),S){if(this._emit("message",T),(o0(T)||t0(T))&&T.content)this._emit("functionCallResult",T.content);else if(p$(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(p$(T)&&T.tool_calls){for(let $ of T.tool_calls)if($.type==="function")this._emit("functionCall",$.function)}}}async finalChatCompletion(){await this.done();let T=this._chatCompletions[this._chatCompletions.length-1];if(!T)throw new $T("stream ended without producing a ChatCompletion");return T}async finalContent(){return await this.done(),QS(this,YS,"m",u0).call(this)}async finalMessage(){return await this.done(),QS(this,YS,"m",cF).call(this)}async finalFunctionCall(){return await this.done(),QS(this,YS,"m",l0).call(this)}async finalFunctionCallResult(){return await this.done(),QS(this,YS,"m",r0).call(this)}async totalUsage(){return await this.done(),QS(this,YS,"m",a0).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let T=this._chatCompletions[this._chatCompletions.length-1];if(T)this._emit("finalChatCompletion",T);let S=QS(this,YS,"m",cF).call(this);if(S)this._emit("finalMessage",S);let $=QS(this,YS,"m",u0).call(this);if($)this._emit("finalContent",$);let f=QS(this,YS,"m",l0).call(this);if(f)this._emit("finalFunctionCall",f);let M=QS(this,YS,"m",r0).call(this);if(M!=null)this._emit("finalFunctionCallResult",M);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",QS(this,YS,"m",a0).call(this))}async _createChatCompletion(T,S,$){let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}QS(this,YS,"m",mX).call(this,S);let M=await T.chat.completions.create({...S,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(YJ(M,S))}async _runChatCompletion(T,S,$){for(let f of S.messages)this._addMessage(f,!1);return await this._createChatCompletion(T,S,$)}async _runFunctions(T,S,$){let{function_call:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.name,{maxChatCompletions:A=qX}=$||{},k={};for(let w of S.functions)k[w.name||w.function.name]=w;let X=S.functions.map((w)=>({name:w.name||w.function.name,parameters:w.parameters,description:w.description}));for(let w of S.messages)this._addMessage(w,!1);for(let w=0;w<A;++w){let G=(await this._createChatCompletion(T,{...F,function_call:M,functions:X,messages:[...this.messages]},$)).choices[0]?.message;if(!G)throw new $T("missing message in ChatCompletion response");if(!G.function_call)return;let{name:z,arguments:U}=G.function_call,D=k[z];if(!D){let j=`Invalid function_call: ${JSON.stringify(z)}. Available options are: ${X.map((E)=>JSON.stringify(E.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:z,content:j});continue}else if(W&&W!==z){let j=`Invalid function_call: ${JSON.stringify(z)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"function",name:z,content:j});continue}let B;try{B=g0(D)?await D.parse(U):U}catch(j){this._addMessage({role:"function",name:z,content:j instanceof Error?j.message:String(j)});continue}let L=await D.function(B,this),Z=QS(this,YS,"m",e0).call(this,L);if(this._addMessage({role:"function",name:z,content:Z}),W)return}}async _runTools(T,S,$){let{tool_choice:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.function?.name,{maxChatCompletions:A=qX}=$||{},k=S.tools.map((K)=>{if(Kf(K)){if(!K.$callback)throw new $T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:K.$callback,name:K.function.name,description:K.function.description||"",parameters:K.function.parameters,parse:K.$parseRaw,strict:!0}}}return K}),X={};for(let K of k)if(K.type==="function")X[K.function.name||K.function.function.name]=K.function;let w="tools"in S?k.map((K)=>K.type==="function"?{type:"function",function:{name:K.function.name||K.function.function.name,parameters:K.function.parameters,description:K.function.description,strict:K.function.strict}}:K):void 0;for(let K of S.messages)this._addMessage(K,!1);for(let K=0;K<A;++K){let z=(await this._createChatCompletion(T,{...F,tool_choice:M,tools:w,messages:[...this.messages]},$)).choices[0]?.message;if(!z)throw new $T("missing message in ChatCompletion response");if(!z.tool_calls?.length)return;for(let U of z.tool_calls){if(U.type!=="function")continue;let D=U.id,{name:B,arguments:L}=U.function,Z=X[B];if(!Z){let Q=`Invalid tool_call: ${JSON.stringify(B)}. Available options are: ${Object.keys(X).map((b)=>JSON.stringify(b)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:D,content:Q});continue}else if(W&&W!==B){let Q=`Invalid tool_call: ${JSON.stringify(B)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:D,content:Q});continue}let j;try{j=g0(Z)?await Z.parse(L):L}catch(Q){let b=Q instanceof Error?Q.message:String(Q);this._addMessage({role:"tool",tool_call_id:D,content:b});continue}let E=await Z.function(j,this),_=QS(this,YS,"m",e0).call(this,E);if(this._addMessage({role:"tool",tool_call_id:D,content:_}),W)return}}return}}YS=new WeakSet,u0=function T(){return QS(this,YS,"m",cF).call(this).content??null},cF=function T(){let S=this.messages.length;while(S-- >0){let $=this.messages[S];if(p$($)){let{function_call:f,...M}=$,J={...M,content:$.content??null,refusal:$.refusal??null};if(f)J.function_call=f;return J}}throw new $T("stream ended without producing a ChatCompletionMessage with role=assistant")},l0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(p$($)&&$?.function_call)return $.function_call;if(p$($)&&$?.tool_calls?.length)return $.tool_calls.at(-1)?.function}return},r0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(o0($)&&$.content!=null)return $.content;if(t0($)&&$.content!=null&&typeof $.content==="string"&&this.messages.some((f)=>f.role==="assistant"&&f.tool_calls?.some((M)=>M.type==="function"&&M.id===$.tool_call_id)))return $.content}return},a0=function T(){let S={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:$}of this._chatCompletions)if($)S.completion_tokens+=$.completion_tokens,S.prompt_tokens+=$.prompt_tokens,S.total_tokens+=$.total_tokens;return S},mX=function T(S){if(S.n!=null&&S.n>1)throw new $T("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},e0=function T(S){return typeof S==="string"?S:S===void 0?"undefined":JSON.stringify(S)};class fM extends yJ{static runFunctions(T,S,$){let f=new fM,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){let f=new fM,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}_addMessage(T,S=!0){if(super._addMessage(T,S),p$(T)&&T.content)this._emit("content",T.content)}}var sT={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class hX extends Error{}class vX extends Error{}function Z6(T,S=sT.ALL){if(typeof T!=="string")throw new TypeError(`expecting str, got ${typeof T}`);if(!T.trim())throw new Error(`${T} is empty`);return q6(T.trim(),S)}var q6=(T,S)=>{let $=T.length,f=0,M=(K)=>{throw new hX(`${K} at position ${f}`)},J=(K)=>{throw new vX(`${K} at position ${f}`)},F=()=>{if(w(),f>=$)M("Unexpected end of input");if(T[f]==='"')return W();if(T[f]==="{")return A();if(T[f]==="[")return k();if(T.substring(f,f+4)==="null"||sT.NULL&S&&$-f<4&&"null".startsWith(T.substring(f)))return f+=4,null;if(T.substring(f,f+4)==="true"||sT.BOOL&S&&$-f<4&&"true".startsWith(T.substring(f)))return f+=4,!0;if(T.substring(f,f+5)==="false"||sT.BOOL&S&&$-f<5&&"false".startsWith(T.substring(f)))return f+=5,!1;if(T.substring(f,f+8)==="Infinity"||sT.INFINITY&S&&$-f<8&&"Infinity".startsWith(T.substring(f)))return f+=8,1/0;if(T.substring(f,f+9)==="-Infinity"||sT.MINUS_INFINITY&S&&1<$-f&&$-f<9&&"-Infinity".startsWith(T.substring(f)))return f+=9,-1/0;if(T.substring(f,f+3)==="NaN"||sT.NAN&S&&$-f<3&&"NaN".startsWith(T.substring(f)))return f+=3,NaN;return X()},W=()=>{let K=f,G=!1;f++;while(f<$&&(T[f]!=='"'||G&&T[f-1]==="\\"))G=T[f]==="\\"?!G:!1,f++;if(T.charAt(f)=='"')try{return JSON.parse(T.substring(K,++f-Number(G)))}catch(z){J(String(z))}else if(sT.STR&S)try{return JSON.parse(T.substring(K,f-Number(G))+'"')}catch(z){return JSON.parse(T.substring(K,T.lastIndexOf("\\"))+'"')}M("Unterminated string literal")},A=()=>{f++,w();let K={};try{while(T[f]!=="}"){if(w(),f>=$&&sT.OBJ&S)return K;let G=W();w(),f++;try{let z=F();Object.defineProperty(K,G,{value:z,writable:!0,enumerable:!0,configurable:!0})}catch(z){if(sT.OBJ&S)return K;else throw z}if(w(),T[f]===",")f++}}catch(G){if(sT.OBJ&S)return K;else M("Expected '}' at end of object")}return f++,K},k=()=>{f++;let K=[];try{while(T[f]!=="]")if(K.push(F()),w(),T[f]===",")f++}catch(G){if(sT.ARR&S)return K;M("Expected ']' at end of array")}return f++,K},X=()=>{if(f===0){if(T==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T)}catch(G){if(sT.NUM&S)try{if(T[T.length-1]===".")return JSON.parse(T.substring(0,T.lastIndexOf(".")));return JSON.parse(T.substring(0,T.lastIndexOf("e")))}catch(z){}J(String(G))}}let K=f;if(T[f]==="-")f++;while(T[f]&&!",]}".includes(T[f]))f++;if(f==$&&!(sT.NUM&S))M("Unterminated number literal");try{return JSON.parse(T.substring(K,f))}catch(G){if(T.substring(K,f)==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T.substring(K,T.lastIndexOf("e")))}catch(z){J(String(z))}}},w=()=>{while(f<$&&`
28
+ \r\t`.includes(T[f]))f++};return F()},s0=(T)=>Z6(T,sT.ALL^sT.NUM);var MM=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},HT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},rT,V$,JM,i$,T1,gF,S1,$1,f1,oF,M1,PX;class Yf extends yJ{constructor(T){super();rT.add(this),V$.set(this,void 0),JM.set(this,void 0),i$.set(this,void 0),MM(this,V$,T,"f"),MM(this,JM,[],"f")}get currentChatCompletionSnapshot(){return HT(this,i$,"f")}static fromReadableStream(T){let S=new Yf(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){let f=new Yf(S);return f._run(()=>f._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}async _createChatCompletion(T,S,$){super._createChatCompletion;let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}HT(this,rT,"m",T1).call(this);let M=await T.chat.completions.create({...S,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let J of M)HT(this,rT,"m",S1).call(this,J);if(M.controller.signal?.aborted)throw new SS;return this._addChatCompletion(HT(this,rT,"m",oF).call(this))}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}HT(this,rT,"m",T1).call(this),this._connected();let f=NS.fromReadableStream(T,this.controller),M;for await(let J of f){if(M&&M!==J.id)this._addChatCompletion(HT(this,rT,"m",oF).call(this));HT(this,rT,"m",S1).call(this,J),M=J.id}if(f.controller.signal?.aborted)throw new SS;return this._addChatCompletion(HT(this,rT,"m",oF).call(this))}[(V$=new WeakMap,JM=new WeakMap,i$=new WeakMap,rT=new WeakSet,T1=function T(){if(this.ended)return;MM(this,i$,void 0,"f")},gF=function T(S){let $=HT(this,JM,"f")[S.index];if($)return $;return $={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},HT(this,JM,"f")[S.index]=$,$},S1=function T(S){if(this.ended)return;let $=HT(this,rT,"m",PX).call(this,S);this._emit("chunk",S,$);for(let f of S.choices){let M=$.choices[f.index];if(f.delta.content!=null&&M.message?.role==="assistant"&&M.message?.content)this._emit("content",f.delta.content,M.message.content),this._emit("content.delta",{delta:f.delta.content,snapshot:M.message.content,parsed:M.message.parsed});if(f.delta.refusal!=null&&M.message?.role==="assistant"&&M.message?.refusal)this._emit("refusal.delta",{delta:f.delta.refusal,snapshot:M.message.refusal});if(f.logprobs?.content!=null&&M.message?.role==="assistant")this._emit("logprobs.content.delta",{content:f.logprobs?.content,snapshot:M.logprobs?.content??[]});if(f.logprobs?.refusal!=null&&M.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:f.logprobs?.refusal,snapshot:M.logprobs?.refusal??[]});let J=HT(this,rT,"m",gF).call(this,M);if(M.finish_reason){if(HT(this,rT,"m",f1).call(this,M),J.current_tool_call_index!=null)HT(this,rT,"m",$1).call(this,M,J.current_tool_call_index)}for(let F of f.delta.tool_calls??[]){if(J.current_tool_call_index!==F.index){if(HT(this,rT,"m",f1).call(this,M),J.current_tool_call_index!=null)HT(this,rT,"m",$1).call(this,M,J.current_tool_call_index)}J.current_tool_call_index=F.index}for(let F of f.delta.tool_calls??[]){let W=M.message.tool_calls?.[F.index];if(!W?.type)continue;if(W?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:W.function?.name,index:F.index,arguments:W.function.arguments,parsed_arguments:W.function.parsed_arguments,arguments_delta:F.function?.arguments??""});else cX(W?.type)}}},$1=function T(S,$){if(HT(this,rT,"m",gF).call(this,S).done_tool_calls.has($))return;let M=S.message.tool_calls?.[$];if(!M)throw new Error("no tool call snapshot");if(!M.type)throw new Error("tool call snapshot missing `type`");if(M.type==="function"){let J=HT(this,V$,"f")?.tools?.find((F)=>F.type==="function"&&F.function.name===M.function.name);this._emit("tool_calls.function.arguments.done",{name:M.function.name,index:$,arguments:M.function.arguments,parsed_arguments:Kf(J)?J.$parseRaw(M.function.arguments):J?.function.strict?JSON.parse(M.function.arguments):null})}else cX(M.type)},f1=function T(S){let $=HT(this,rT,"m",gF).call(this,S);if(S.message.content&&!$.content_done){$.content_done=!0;let f=HT(this,rT,"m",M1).call(this);this._emit("content.done",{content:S.message.content,parsed:f?f.$parseRaw(S.message.content):null})}if(S.message.refusal&&!$.refusal_done)$.refusal_done=!0,this._emit("refusal.done",{refusal:S.message.refusal});if(S.logprobs?.content&&!$.logprobs_content_done)$.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:S.logprobs.content});if(S.logprobs?.refusal&&!$.logprobs_refusal_done)$.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:S.logprobs.refusal})},oF=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");let S=HT(this,i$,"f");if(!S)throw new $T("request ended without sending any chunks");return MM(this,i$,void 0,"f"),MM(this,JM,[],"f"),m6(S,HT(this,V$,"f"))},M1=function T(){let S=HT(this,V$,"f")?.response_format;if(i0(S))return S;return null},PX=function T(S){var $,f,M,J;let F=HT(this,i$,"f"),{choices:W,...A}=S;if(!F)F=MM(this,i$,{...A,choices:[]},"f");else Object.assign(F,A);for(let{delta:k,finish_reason:X,index:w,logprobs:K=null,...G}of S.choices){let z=F.choices[w];if(!z)z=F.choices[w]={finish_reason:X,index:w,message:{},logprobs:K,...G};if(K)if(!z.logprobs)z.logprobs=Object.assign({},K);else{let{content:E,refusal:_,...Q}=K;if(nX(Q),Object.assign(z.logprobs,Q),E)($=z.logprobs).content??($.content=[]),z.logprobs.content.push(...E);if(_)(f=z.logprobs).refusal??(f.refusal=[]),z.logprobs.refusal.push(..._)}if(X){if(z.finish_reason=X,HT(this,V$,"f")&&d0(HT(this,V$,"f"))){if(X==="length")throw new eM;if(X==="content_filter")throw new sM}}if(Object.assign(z,G),!k)continue;let{content:U,refusal:D,function_call:B,role:L,tool_calls:Z,...j}=k;if(nX(j),Object.assign(z.message,j),D)z.message.refusal=(z.message.refusal||"")+D;if(L)z.message.role=L;if(B)if(!z.message.function_call)z.message.function_call=B;else{if(B.name)z.message.function_call.name=B.name;if(B.arguments)(M=z.message.function_call).arguments??(M.arguments=""),z.message.function_call.arguments+=B.arguments}if(U){if(z.message.content=(z.message.content||"")+U,!z.message.refusal&&HT(this,rT,"m",M1).call(this))z.message.parsed=s0(z.message.content)}if(Z){if(!z.message.tool_calls)z.message.tool_calls=[];for(let{index:E,id:_,type:Q,function:b,...h}of Z){let R=(J=z.message.tool_calls)[E]??(J[E]={});if(Object.assign(R,h),_)R.id=_;if(Q)R.type=Q;if(b)R.function??(R.function={name:b.name??"",arguments:""});if(b?.name)R.function.name=b.name;if(b?.arguments){if(R.function.arguments+=b.arguments,bX(HT(this,V$,"f"),R))R.function.parsed_arguments=s0(R.function.arguments)}}}}return F},Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("chunk",(f)=>{let M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function m6(T,S){let{id:$,choices:f,created:M,model:J,system_fingerprint:F,...W}=T,A={...W,id:$,choices:f.map(({message:k,finish_reason:X,index:w,logprobs:K,...G})=>{if(!X)throw new $T(`missing finish_reason for choice ${w}`);let{content:z=null,function_call:U,tool_calls:D,...B}=k,L=k.role;if(!L)throw new $T(`missing role for choice ${w}`);if(U){let{arguments:Z,name:j}=U;if(Z==null)throw new $T(`missing function_call.arguments for choice ${w}`);if(!j)throw new $T(`missing function_call.name for choice ${w}`);return{...G,message:{content:z,function_call:{arguments:Z,name:j},role:L,refusal:k.refusal??null},finish_reason:X,index:w,logprobs:K}}if(D)return{...G,index:w,finish_reason:X,logprobs:K,message:{...B,role:L,content:z,refusal:k.refusal??null,tool_calls:D.map((Z,j)=>{let{function:E,type:_,id:Q,...b}=Z,{arguments:h,name:R,...g}=E||{};if(Q==null)throw new $T(`missing choices[${w}].tool_calls[${j}].id
29
+ ${tF(T)}`);if(_==null)throw new $T(`missing choices[${w}].tool_calls[${j}].type
30
+ ${tF(T)}`);if(R==null)throw new $T(`missing choices[${w}].tool_calls[${j}].function.name
31
+ ${tF(T)}`);if(h==null)throw new $T(`missing choices[${w}].tool_calls[${j}].function.arguments
32
+ ${tF(T)}`);return{...b,id:Q,type:_,function:{...g,name:R,arguments:h}}})}};return{...G,message:{...B,content:z,role:L,refusal:k.refusal??null},finish_reason:X,index:w,logprobs:K}}),created:M,model:J,object:"chat.completion",...F?{system_fingerprint:F}:{}};return IX(A,S)}function tF(T){return JSON.stringify(T)}function nX(T){return}function cX(T){}class yf extends Yf{static fromReadableStream(T){let S=new yf(null);return S._run(()=>S._fromReadableStream(T)),S}static runFunctions(T,S,$){let f=new yf(null),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){let f=new yf(S),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}}class pF extends i{parse(T,S){return ZX(T.tools),this._client.chat.completions.create(T,{...S,headers:{...S?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(($)=>YJ($,T))}runFunctions(T,S){if(T.stream)return yf.runFunctions(this._client,T,S);return fM.runFunctions(this._client,T,S)}runTools(T,S){if(T.stream)return yf.runTools(this._client,T,S);return fM.runTools(this._client,T,S)}stream(T,S){return Yf.createChatCompletion(this._client,T,S)}}class OJ extends i{constructor(){super(...arguments);this.completions=new pF(this._client)}}(function(T){T.Completions=pF})(OJ||(OJ={}));var u=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},CS=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},$S,J1,w$,iF,T$,Rf,FM,Of,lF,xS,dF,uF,zJ,RJ,GJ,gX,oX,tX,pX,iX,dX,uX;class jS extends KJ{constructor(){super(...arguments);$S.add(this),J1.set(this,[]),w$.set(this,{}),iF.set(this,{}),T$.set(this,void 0),Rf.set(this,void 0),FM.set(this,void 0),Of.set(this,void 0),lF.set(this,void 0),xS.set(this,void 0),dF.set(this,void 0),uF.set(this,void 0),zJ.set(this,void 0)}[(J1=new WeakMap,w$=new WeakMap,iF=new WeakMap,T$=new WeakMap,Rf=new WeakMap,FM=new WeakMap,Of=new WeakMap,lF=new WeakMap,xS=new WeakMap,dF=new WeakMap,uF=new WeakMap,zJ=new WeakMap,$S=new WeakSet,Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("event",(f)=>{let M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(T){let S=new jS;return S._run(()=>S._fromReadableStream(T)),S}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}this._connected();let f=NS.fromReadableStream(T,this.controller);for await(let M of f)u(this,$S,"m",RJ).call(this,M);if(f.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",GJ).call(this))}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(T,S,$,f,M){let J=new jS;return J._run(()=>J._runToolAssistantStream(T,S,$,f,{...M,headers:{...M?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(T,S,$,f,M){let J=M?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let F={...f,stream:!0},W=await T.submitToolOutputs(S,$,F,{...M,signal:this.controller.signal});this._connected();for await(let A of W)u(this,$S,"m",RJ).call(this,A);if(W.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",GJ).call(this))}static createThreadAssistantStream(T,S,$){let f=new jS;return f._run(()=>f._threadAssistantStream(T,S,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}static createAssistantStream(T,S,$,f){let M=new jS;return M._run(()=>M._runAssistantStream(T,S,$,{...f,headers:{...f?.headers,"X-Stainless-Helper-Method":"stream"}})),M}currentEvent(){return u(this,dF,"f")}currentRun(){return u(this,uF,"f")}currentMessageSnapshot(){return u(this,T$,"f")}currentRunStepSnapshot(){return u(this,zJ,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,w$,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,iF,"f"))}async finalRun(){if(await this.done(),!u(this,Rf,"f"))throw Error("Final run was not received.");return u(this,Rf,"f")}async _createThreadAssistantStream(T,S,$){let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}let M={...S,stream:!0},J=await T.createAndRun(M,{...$,signal:this.controller.signal});this._connected();for await(let F of J)u(this,$S,"m",RJ).call(this,F);if(J.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",GJ).call(this))}async _createAssistantStream(T,S,$,f){let M=f?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}let J={...$,stream:!0},F=await T.create(S,J,{...f,signal:this.controller.signal});this._connected();for await(let W of F)u(this,$S,"m",RJ).call(this,W);if(F.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",GJ).call(this))}static accumulateDelta(T,S){for(let[$,f]of Object.entries(S)){if(!T.hasOwnProperty($)){T[$]=f;continue}let M=T[$];if(M===null||M===void 0){T[$]=f;continue}if($==="index"||$==="type"){T[$]=f;continue}if(typeof M==="string"&&typeof f==="string")M+=f;else if(typeof M==="number"&&typeof f==="number")M+=f;else if($J(M)&&$J(f))M=this.accumulateDelta(M,f);else if(Array.isArray(M)&&Array.isArray(f)){if(M.every((J)=>typeof J==="string"||typeof J==="number")){M.push(...f);continue}for(let J of f){if(!$J(J))throw new Error(`Expected array delta entry to be an object but got: ${J}`);let F=J.index;if(F==null)throw console.error(J),new Error("Expected array delta entry to have an `index` property");if(typeof F!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${F}`);let W=M[F];if(W==null)M.push(J);else M[F]=this.accumulateDelta(W,J)}continue}else throw Error(`Unhandled record type: ${$}, deltaValue: ${f}, accValue: ${M}`);T[$]=M}return T}_addRun(T){return T}async _threadAssistantStream(T,S,$){return await this._createThreadAssistantStream(S,T,$)}async _runAssistantStream(T,S,$,f){return await this._createAssistantStream(S,T,$,f)}async _runToolAssistantStream(T,S,$,f,M){return await this._createToolAssistantStream($,T,S,f,M)}}RJ=function T(S){if(this.ended)return;switch(CS(this,dF,S,"f"),u(this,$S,"m",tX).call(this,S),S.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":u(this,$S,"m",uX).call(this,S);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":u(this,$S,"m",oX).call(this,S);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":u(this,$S,"m",gX).call(this,S);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},GJ=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");if(!u(this,Rf,"f"))throw Error("Final run has not been received");return u(this,Rf,"f")},gX=function T(S){let[$,f]=u(this,$S,"m",iX).call(this,S,u(this,T$,"f"));CS(this,T$,$,"f"),u(this,iF,"f")[$.id]=$;for(let M of f){let J=$.content[M.index];if(J?.type=="text")this._emit("textCreated",J.text)}switch(S.event){case"thread.message.created":this._emit("messageCreated",S.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",S.data.delta,$),S.data.delta.content)for(let M of S.data.delta.content){if(M.type=="text"&&M.text){let J=M.text,F=$.content[M.index];if(F&&F.type=="text")this._emit("textDelta",J,F.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(M.index!=u(this,FM,"f")){if(u(this,Of,"f"))switch(u(this,Of,"f").type){case"text":this._emit("textDone",u(this,Of,"f").text,u(this,T$,"f"));break;case"image_file":this._emit("imageFileDone",u(this,Of,"f").image_file,u(this,T$,"f"));break}CS(this,FM,M.index,"f")}CS(this,Of,$.content[M.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,FM,"f")!==void 0){let M=S.data.content[u(this,FM,"f")];if(M)switch(M.type){case"image_file":this._emit("imageFileDone",M.image_file,u(this,T$,"f"));break;case"text":this._emit("textDone",M.text,u(this,T$,"f"));break}}if(u(this,T$,"f"))this._emit("messageDone",S.data);CS(this,T$,void 0,"f")}},oX=function T(S){let $=u(this,$S,"m",pX).call(this,S);switch(CS(this,zJ,$,"f"),S.event){case"thread.run.step.created":this._emit("runStepCreated",S.data);break;case"thread.run.step.delta":let f=S.data.delta;if(f.step_details&&f.step_details.type=="tool_calls"&&f.step_details.tool_calls&&$.step_details.type=="tool_calls")for(let J of f.step_details.tool_calls)if(J.index==u(this,lF,"f"))this._emit("toolCallDelta",J,$.step_details.tool_calls[J.index]);else{if(u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f"));if(CS(this,lF,J.index,"f"),CS(this,xS,$.step_details.tool_calls[J.index],"f"),u(this,xS,"f"))this._emit("toolCallCreated",u(this,xS,"f"))}this._emit("runStepDelta",S.data.delta,$);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(CS(this,zJ,void 0,"f"),S.data.step_details.type=="tool_calls"){if(u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f")),CS(this,xS,void 0,"f")}this._emit("runStepDone",S.data,$);break;case"thread.run.step.in_progress":break}},tX=function T(S){u(this,J1,"f").push(S),this._emit("event",S)},pX=function T(S){switch(S.event){case"thread.run.step.created":return u(this,w$,"f")[S.data.id]=S.data,S.data;case"thread.run.step.delta":let $=u(this,w$,"f")[S.data.id];if(!$)throw Error("Received a RunStepDelta before creation of a snapshot");let f=S.data;if(f.delta){let M=jS.accumulateDelta($,f.delta);u(this,w$,"f")[S.data.id]=M}return u(this,w$,"f")[S.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,w$,"f")[S.data.id]=S.data;break}if(u(this,w$,"f")[S.data.id])return u(this,w$,"f")[S.data.id];throw new Error("No snapshot available")},iX=function T(S,$){let f=[];switch(S.event){case"thread.message.created":return[S.data,f];case"thread.message.delta":if(!$)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let M=S.data;if(M.delta.content)for(let J of M.delta.content)if(J.index in $.content){let F=$.content[J.index];$.content[J.index]=u(this,$S,"m",dX).call(this,J,F)}else $.content[J.index]=J,f.push(J);return[$,f];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if($)return[$,f];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},dX=function T(S,$){return jS.accumulateDelta($,S)},uX=function T(S){switch(CS(this,uF,S.data,"f"),S.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":if(CS(this,Rf,S.data,"f"),u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f")),CS(this,xS,void 0,"f");break;case"thread.run.cancelling":break}};class WM extends i{create(T,S,$){return this._client.post(`/threads/${T}/messages`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/messages/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(BT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/messages`,_J,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class _J extends vT{}WM.MessagesPage=_J;class AM extends i{retrieve(T,S,$,f={},M){if(BT(f))return this.retrieve(T,S,$,{},f);return this._client.get(`/threads/${T}/runs/${S}/steps/${$}`,{query:f,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers}})}list(T,S,$={},f){if(BT($))return this.list(T,S,{},$);return this._client.getAPIList(`/threads/${T}/runs/${S}/steps`,HJ,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}}class HJ extends vT{}AM.RunStepsPage=HJ;class d$ extends i{constructor(){super(...arguments);this.steps=new AM(this._client)}create(T,S,$){let{include:f,...M}=S;return this._client.post(`/threads/${T}/runs`,{query:{include:f},body:M,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:S.stream??!1})}retrieve(T,S,$){return this._client.get(`/threads/${T}/runs/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(BT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/runs`,EJ,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/threads/${T}/runs/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S,$);return await this.poll(T,f.id,$)}createAndStream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:M,response:J}=await this.retrieve(T,S,{...$,headers:{...$?.headers,...f}}).withResponse();switch(M.status){case"queued":case"in_progress":case"cancelling":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=J.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return M}}}stream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}submitToolOutputs(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}/submit_tool_outputs`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers},stream:$.stream??!1})}async submitToolOutputsAndPoll(T,S,$,f){let M=await this.submitToolOutputs(T,S,$,f);return await this.poll(T,M.id,f)}submitToolOutputsStream(T,S,$,f){return jS.createToolAssistantStream(T,S,this._client.beta.threads.runs,$,f)}}class EJ extends vT{}d$.RunsPage=EJ;d$.Steps=AM;d$.RunStepsPage=HJ;class B$ extends i{constructor(){super(...arguments);this.runs=new d$(this._client),this.messages=new WM(this._client)}create(T={},S){if(BT(T))return this.create({},T);return this._client.post("/threads",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/threads/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S){return this._client.delete(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}createAndRun(T,S){return this._client.post("/threads/runs",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers},stream:T.stream??!1})}async createAndRunPoll(T,S){let $=await this.createAndRun(T,S);return await this.runs.poll($.thread_id,$.id,S)}createAndRunStream(T,S){return jS.createThreadAssistantStream(T,this._client.beta.threads,S)}}B$.Runs=d$;B$.RunsPage=EJ;B$.Messages=WM;B$.MessagesPage=_J;var lX=async(T)=>{let S=await Promise.allSettled(T),$=S.filter((M)=>M.status==="rejected");if($.length){for(let M of $)console.error(M.reason);throw new Error(`${$.length} promise(s) failed - see the above errors`)}let f=[];for(let M of S)if(M.status==="fulfilled")f.push(M.value);return f};class kM extends i{create(T,S,$){return this._client.post(`/vector_stores/${T}/files`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T,S={},$){if(BT(S))return this.list(T,{},S);return this._client.getAPIList(`/vector_stores/${T}/files`,Gf,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S,$);return await this.poll(T,f.id,$)}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let M=await this.retrieve(T,S,{...$,headers:f}).withResponse(),J=M.data;switch(J.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=M.response.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"failed":case"completed":return J}}}async upload(T,S,$){let f=await this._client.files.create({file:S,purpose:"assistants"},$);return this.create(T,{file_id:f.id},$)}async uploadAndPoll(T,S,$){let f=await this.upload(T,S,$);return await this.poll(T,f.id,$)}}class Gf extends vT{}kM.VectorStoreFilesPage=Gf;class DJ extends i{create(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/file_batches/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S);return await this.poll(T,f.id,$)}listFiles(T,S,$={},f){if(BT($))return this.listFiles(T,S,{},$);return this._client.getAPIList(`/vector_stores/${T}/file_batches/${S}/files`,Gf,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:M,response:J}=await this.retrieve(T,S,{...$,headers:f}).withResponse();switch(M.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=J.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"failed":case"cancelled":case"completed":return M}}}async uploadAndPoll(T,{files:S,fileIds:$=[]},f){if(S==null||S.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let M=f?.maxConcurrency??5,J=Math.min(M,S.length),F=this._client,W=S.values(),A=[...$];async function k(w){for(let K of w){let G=await F.files.create({file:K,purpose:"assistants"},f);A.push(G.id)}}let X=Array(J).fill(W).map(k);return await lX(X),await this.createAndPoll(T,{file_ids:A})}}class L$ extends i{constructor(){super(...arguments);this.files=new kM(this._client),this.fileBatches=new DJ(this._client)}create(T,S){return this._client.post("/vector_stores",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/vector_stores/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(BT(T))return this.list({},T);return this._client.getAPIList("/vector_stores",QJ,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class QJ extends vT{}L$.VectorStoresPage=QJ;L$.Files=kM;L$.VectorStoreFilesPage=Gf;L$.FileBatches=DJ;class S$ extends i{constructor(){super(...arguments);this.vectorStores=new L$(this._client),this.chat=new OJ(this._client),this.assistants=new SM(this._client),this.threads=new B$(this._client)}}S$.VectorStores=L$;S$.VectorStoresPage=QJ;S$.Assistants=SM;S$.AssistantsPage=WJ;S$.Threads=B$;class XM extends i{create(T,S){return this._client.post("/completions",{body:T,...S,stream:T.stream??!1})}}class wM extends i{create(T,S){return this._client.post("/embeddings",{body:T,...S})}}class zf extends i{create(T,S){return this._client.post("/files",vS({body:T,...S}))}retrieve(T,S){return this._client.get(`/files/${T}`,S)}list(T={},S){if(BT(T))return this.list({},T);return this._client.getAPIList("/files",KM,{query:T,...S})}del(T,S){return this._client.delete(`/files/${T}`,S)}content(T,S){return this._client.get(`/files/${T}/content`,{...S,__binaryResponse:!0})}retrieveContent(T,S){return this._client.get(`/files/${T}/content`,{...S,headers:{Accept:"application/json",...S?.headers}})}async waitForProcessing(T,{pollInterval:S=5000,maxWait:$=1800000}={}){let f=new Set(["processed","error","deleted"]),M=Date.now(),J=await this.retrieve(T);while(!J.status||!f.has(J.status))if(await D$(S),J=await this.retrieve(T),Date.now()-M>$)throw new Af({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class KM extends vT{}zf.FileObjectsPage=KM;class YM extends i{list(T,S={},$){if(BT(S))return this.list(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/checkpoints`,UJ,{query:S,...$})}}class UJ extends vT{}YM.FineTuningJobCheckpointsPage=UJ;class N$ extends i{constructor(){super(...arguments);this.checkpoints=new YM(this._client)}create(T,S){return this._client.post("/fine_tuning/jobs",{body:T,...S})}retrieve(T,S){return this._client.get(`/fine_tuning/jobs/${T}`,S)}list(T={},S){if(BT(T))return this.list({},T);return this._client.getAPIList("/fine_tuning/jobs",VJ,{query:T,...S})}cancel(T,S){return this._client.post(`/fine_tuning/jobs/${T}/cancel`,S)}listEvents(T,S={},$){if(BT(S))return this.listEvents(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/events`,BJ,{query:S,...$})}}class VJ extends vT{}class BJ extends vT{}N$.FineTuningJobsPage=VJ;N$.FineTuningJobEventsPage=BJ;N$.Checkpoints=YM;N$.FineTuningJobCheckpointsPage=UJ;class C$ extends i{constructor(){super(...arguments);this.jobs=new N$(this._client)}}C$.Jobs=N$;C$.FineTuningJobsPage=VJ;C$.FineTuningJobEventsPage=BJ;class yM extends i{createVariation(T,S){return this._client.post("/images/variations",vS({body:T,...S}))}edit(T,S){return this._client.post("/images/edits",vS({body:T,...S}))}generate(T,S){return this._client.post("/images/generations",{body:T,...S})}}class _f extends i{retrieve(T,S){return this._client.get(`/models/${T}`,S)}list(T){return this._client.getAPIList("/models",OM,T)}del(T,S){return this._client.delete(`/models/${T}`,S)}}class OM extends c0{}_f.ModelsPage=OM;class RM extends i{create(T,S){return this._client.post("/moderations",{body:T,...S})}}class LJ extends i{create(T,S,$){return this._client.post(`/uploads/${T}/parts`,vS({body:S,...$}))}}class Hf extends i{constructor(){super(...arguments);this.parts=new LJ(this._client)}create(T,S){return this._client.post("/uploads",{body:T,...S})}cancel(T,S){return this._client.post(`/uploads/${T}/cancel`,S)}complete(T,S,$){return this._client.post(`/uploads/${T}/complete`,{body:S,...$})}}Hf.Parts=LJ;var rX;class KT extends n0{constructor({baseURL:T=SJ("OPENAI_BASE_URL"),apiKey:S=SJ("OPENAI_API_KEY"),organization:$=SJ("OPENAI_ORG_ID")??null,project:f=SJ("OPENAI_PROJECT_ID")??null,...M}={}){if(S===void 0)throw new $T("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let J={apiKey:S,organization:$,project:f,...M,baseURL:T||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&xX())throw new $T(`It looks like you're running in a browser-like environment.
33
+
34
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
35
+ If you understand the risks and have appropriate mitigations in place,
36
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
37
+
38
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
39
+
40
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
41
+ `);super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new XM(this),this.chat=new Xf(this),this.embeddings=new wM(this),this.files=new zf(this),this.images=new yM(this),this.audio=new Q$(this),this.moderations=new RM(this),this.models=new _f(this),this.fineTuning=new C$(this),this.beta=new S$(this),this.batches=new wf(this),this.uploads=new Hf(this),this._options=J,this.apiKey=S,this.organization=$,this.project=f}defaultQuery(){return this._options.defaultQuery}defaultHeaders(T){return{...super.defaultHeaders(T),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(T){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(T){return L0(T,{arrayFormat:"brackets"})}}rX=KT;KT.OpenAI=rX;KT.DEFAULT_TIMEOUT=600000;KT.OpenAIError=$T;KT.APIError=gT;KT.APIConnectionError=Wf;KT.APIConnectionTimeoutError=Af;KT.APIUserAbortError=SS;KT.NotFoundError=LF;KT.ConflictError=NF;KT.RateLimitError=xF;KT.BadRequestError=UF;KT.AuthenticationError=VF;KT.InternalServerError=jF;KT.PermissionDeniedError=BF;KT.UnprocessableEntityError=CF;KT.toFile=h0;KT.fileFromPath=QF;KT.Completions=XM;KT.Chat=Xf;KT.Embeddings=wM;KT.Files=zf;KT.FileObjectsPage=KM;KT.Images=yM;KT.Audio=Q$;KT.Moderations=RM;KT.Models=_f;KT.ModelsPage=OM;KT.FineTuning=C$;KT.Beta=S$;KT.Batches=wf;KT.BatchesPage=TM;KT.Uploads=Hf;var aX=KT;function a6(T,...S){let[$,f,M,J]=S,F=[{role:"user",content:MX(f)},{role:"user",content:$}],W=J.at(-1);if(W)F.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(W.response,null,2),"Here's the error message:",W.error.toString()].join(`
42
+ `)});return{model:T,messages:F}}var F1={"gpt-4o":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-08-06":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-05-13":{promptPricePerToken:0.000005,promptPricePerTokenCached:0.000005,completionPricePerToken:0.000014999999999999999},"gpt-4o-mini":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"gpt-4o-mini-2024-07-18":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"o1-preview":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995},"o1-preview-2024-09-12":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995}},eX=new Map;function e6(T="NO_API_KEY_PROVIDED"){let S=r6("sha256").update(T).digest("hex");return async function $(f,M){let J=eX.get(S);if(!J)J=new aX({apiKey:T,dangerouslyAllowBrowser:!1}),eX.set(S,J);let F=await J.chat.completions.create({...f,stream:!1,response_format:{type:"json_object"}},M),W=F.choices[0].message?.content,{usage:A}=F;if(W&&A){let k=A.prompt_tokens,X=A.prompt_tokens_details?.cached_tokens??0,w=k-X,K=A.completion_tokens,G=k*F1[f.model].promptPricePerToken+w*F1[f.model].promptPricePerTokenCached+K*F1[f.model].completionPricePerToken;return{data:JSON.parse(W),usdPrice:G}}if(!W&&!A)throw new Error("No content or usage found in completion");if(!W)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var sX=class{usdBudget;usdMinimum;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;constructor({model:T,usdBudget:S,usdMinimum:$,apiKey:f,cachingMode:M,cacheKey:J="openai-safegen",logger:F}){this.usdBudget=S,this.usdMinimum=$,this.squirrel=new Q0(M),this.getUnknownJsonFromOpenAi=e6(f),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(J,this.getUnknownJsonFromOpenAi),this.from=fX(async(...W)=>{if(this.usdBudget<this.usdMinimum)return F?.warn("SafeGen budget exhausted"),W[1];let A=a6(T,...W),k=W[0],X=W[3],w=await this.getUnknownJsonFromOpenAiSquirreled.for(`${k.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${X.length}`).get(A);return this.usdBudget-=w.usdPrice,w.data})}from};import{exec as Ay}from"child_process";import{existsSync as ky}from"fs";import{readFile as Xy,writeFile as wy}from"fs/promises";import{resolve as Ky}from"path";var W1=(T)=>{let S=ES(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let $=new Map;for(let[f,M]of T.atoms)if(!f.includes("\uD83D\uDD0D")){let J=XS(M);if(M.family){let F=$.get(M.family.key);if(!F||!("familyMembers"in F))F={key:M.family.key,familyMembers:new Map},$.set(M.family.key,F);F.familyMembers.set(M.family.subKey,J)}else $.set(f,J)}return $},effects:[({setSelf:$})=>{T.on.atomCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},M.set(J,W);W.familyMembers.set(F,f)}else M.set(f.key,f);return M})}),T.on.atomDisposal.subscribe("introspection",(f)=>{$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)M.delete(J)}}else M.delete(f.key);return M})})}]},void 0);return tS(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:$})=>$(S)})};var A1=(T)=>{let S=ES(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let $=new Map;for(let f of[T.readonlySelectors,T.selectors])for(let[M,J]of f)if(!M.includes("\uD83D\uDD0D")){let F=XS(J);if(J.family){let W=$.get(J.family.key);if(!W||!("familyMembers"in W))W={key:J.family.key,familyMembers:new Map},$.set(J.family.key,W);W.familyMembers.set(J.family.subKey,F)}else $.set(M,F)}return $},effects:[({setSelf:$})=>{T.on.selectorCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},M.set(J,W);W.familyMembers.set(F,f)}else M.set(f.key,f);return M})}),T.on.selectorDisposal.subscribe("introspection",(f)=>{$((M)=>{if(f.family){let{key:J,subKey:F}=f.family,W=M.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)M.delete(J)}}else M.delete(f.key);return M})})}]},void 0);return tS(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:$})=>$(S)})};class rF{supported;constructor(T){this.supported=T}refine(T){for(let[S,$]of Object.entries(this.supported))try{if($(T)===!0&&$!==Boolean)return{type:S,data:T}}catch(f){try{if(T instanceof $)return{type:S,data:T}}catch(M){}}return null}}var k1=new rF({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function X1(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var w1=new rF({object:X1,array:(T)=>Array.isArray(T)}),s6=new rF({...k1.supported,...w1.supported}),GM=(T)=>{if(T===void 0)return"undefined";let S=s6.refine(T);if(S)return S.type;return Object.getPrototypeOf(T).constructor.name};class T2{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=WT.STORE){this.store=T;this.atomIndex=W1(this.store),this.selectorIndex=A1(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=T2.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let S=pW(this.atomIndex),$=pW(this.selectorIndex),f=[...S.values()].filter((W)=>("familyMembers"in W)),M=[...$.values()].filter((W)=>("familyMembers"in W)),J=performance.now(),F=[];if(T.atomFamilies)for(let W of f){let A=W.familyMembers.values();for(let k of A){let w=this.statesCreatedAt.get(k.key)??this.auditorCreatedAt,K=J-w;F.push([k,K])}}if(T.selectorFamilies)for(let W of M){let A=W.familyMembers.values();for(let k of A){let w=this.statesCreatedAt.get(k.key)??this.auditorCreatedAt,K=J-w;F.push([k,K])}}return F}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var K1=(T,S)=>{let $=(f,M)=>{let F=((A,k)=>{let X=S(A,k);if(X)return X;return null})(f,M);if(F?.jobComplete??F?.pathComplete)return F;let W=Array.isArray(M)?M.map((A,k)=>[k,A]):X1(M)?Object.entries(M):[];for(let[A,k]of W){let X=$([...f,A],k);if(X?.jobComplete)return X}return{}};$([],T)};function T7(T,S){return{summary:`${T<S?"+":"-"}${Math.abs(T-S)} (${T} \u2192 ${S})`}}function S7(T,S){return{summary:`${T.length<S.length?"+":"-"}${Math.abs(T.length-S.length)} ("${T}" \u2192 "${S}")`}}function $7(T,S){return{summary:`${T} \u2192 ${S}`}}function S2(T,S,$){let f="",M=[],J=[],F=[];return K1(T,(W,A)=>{let k;for(k of W){let X=S[k];if(X===void 0)J.push([k,JSON.stringify(A)]);else{let w=$(A,X);if(w.summary!=="No Change")F.push([k,w])}}}),K1(S,(W,A)=>{let k;for(k of W)if(T[k]===void 0)M.push([k,JSON.stringify(A)])}),f=`\uFF5E${F.length} \uFF0B${M.length} \uFF0D${J.length}`,{summary:f,added:M,removed:J,changed:F}}function f7(T,S,$){return S2(T,S,$)}class $2{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,S,$){this.leafRefinery=T,this.treeRefinery=S,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(T.supported)){let M=$[f];this.leafDiffers[f]=M}for(let f of Object.keys(S.supported)){let M=$[f];this.treeDiffers[f]=M}}diff(T,S){if(T===S)return{summary:"No Change"};let $=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),f=this.leafRefinery.refine(S)??this.treeRefinery.refine(S);if($!==null&&f!==null){if($.type===f.type){if($.type in this.leafDiffers)return this.leafDiffers[$.type]($.data,f.data);if($.type in this.treeDiffers)return this.treeDiffers[$.type]($.data,f.data,(W,A)=>this.diff(W,A))}}let M=GM(T),J=GM(S);if(M===J)return{summary:`${M} \u2192 ${J}`};return{summary:`Type change: ${M} \u2192 ${J}`}}}var xN=new $2(k1,w1,{number:T7,string:S7,boolean:$7,null:()=>({summary:"No Change"}),object:S2,array:f7});var y=Symbol.for("drizzle:entityKind"),vN=Symbol.for("drizzle:hasOwnEntityKind");function V(T,S){if(!T||typeof T!=="object")return!1;if(T instanceof S)return!0;if(!Object.prototype.hasOwnProperty.call(S,y))throw new Error(`Class "${S.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 $=Object.getPrototypeOf(T).constructor;if($)while($){if(y in $&&$[y]===S[y])return!0;$=Object.getPrototypeOf($)}return!1}class DT{constructor(T,S){this.table=T,this.config=S,this.name=S.name,this.keyAsName=S.keyAsName,this.notNull=S.notNull,this.default=S.default,this.defaultFn=S.defaultFn,this.onUpdateFn=S.onUpdateFn,this.hasDefault=S.hasDefault,this.primary=S.primaryKey,this.isUnique=S.isUnique,this.uniqueName=S.uniqueName,this.uniqueType=S.uniqueType,this.dataType=S.dataType,this.columnType=S.columnType,this.generated=S.generated,this.generatedIdentity=S.generatedIdentity}static[y]="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(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class Y1{static[y]="ColumnBuilder";config;constructor(T,S,$){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:S,columnType:$,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var $$=Symbol.for("drizzle:Name");class y1{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,S){if(this.reference=()=>{let{name:$,columns:f,foreignColumns:M}=T();return{name:$,columns:f,foreignTable:M[0].table,foreignColumns:M}},S)this._onUpdate=S.onUpdate,this._onDelete=S.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new f2(T,this)}}class f2{constructor(T,S){this.table=T,this.reference=S.reference,this.onUpdate=S._onUpdate,this.onDelete=S._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:S,foreignColumns:$}=this.reference(),f=S.map((F)=>F.name),M=$.map((F)=>F.name),J=[this.table[$$],...f,$[0].table[$$],...M];return T??`${J.join("_")}_fk`}}function aF(T,...S){return T(...S)}function M2(T,S){return`${T[$$]}_${S.join("_")}_unique`}function J2(T,S,$){for(let f=S;f<T.length;f++){let M=T[f];if(M==="\\"){f++;continue}if(M==='"')return[T.slice(S,f).replace(/\\/g,""),f+1];if($)continue;if(M===","||M==="}")return[T.slice(S,f).replace(/\\/g,""),f]}return[T.slice(S).replace(/\\/g,""),T.length]}function F2(T,S=0){let $=[],f=S,M=!1;while(f<T.length){let J=T[f];if(J===","){if(M||f===S)$.push("");M=!0,f++;continue}if(M=!1,J==="\\"){f+=2;continue}if(J==='"'){let[A,k]=J2(T,f+1,!0);$.push(A),f=k;continue}if(J==="}")return[$,f+1];if(J==="{"){let[A,k]=F2(T,f+1);$.push(A),f=k;continue}let[F,W]=J2(T,f,!1);$.push(F),f=W}return[$,f]}function W2(T){let[S]=F2(T,1);return S}function O1(T){return`{${T.map((S)=>{if(Array.isArray(S))return O1(S);if(typeof S==="string")return`"${S.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${S}`}).join(",")}}`}class t extends Y1{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(T){return new k2(this.config.name,this,T)}references(T,S={}){return this.foreignKeyConfigs.push({ref:T,actions:S}),this}unique(T,S){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=S?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,S){return this.foreignKeyConfigs.map(({ref:$,actions:f})=>{return aF((M,J)=>{let F=new y1(()=>{let W=M();return{columns:[T],foreignColumns:[W]}});if(J.onUpdate)F.onUpdate(J.onUpdate);if(J.onDelete)F.onDelete(J.onDelete);return F.build(S)},$,f)})}buildExtraConfigColumn(T){return new A2(T,this.config)}}class q extends DT{constructor(T,S){if(!S.uniqueName)S.uniqueName=M2(T,[S.name]);super(T,S);this.table=T}static[y]="PgColumn"}class A2 extends q{static[y]="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(T){return this.indexConfig.opClass=T,this}}class NJ{static[y]="IndexedColumn";constructor(T,S,$,f){this.name=T,this.keyAsName=S,this.type=$,this.indexConfig=f}name;keyAsName;type;indexConfig}class k2 extends t{static[y]="PgArrayBuilder";constructor(T,S,$){super(T,"array","PgArray");this.config.baseBuilder=S,this.config.size=$}build(T){let S=this.config.baseBuilder.build(T);return new R1(T,this.config,S)}}class R1 extends q{constructor(T,S,$,f){super(T,S);this.baseColumn=$,this.range=f,this.size=S.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=W2(T);return T.map((S)=>this.baseColumn.mapFromDriverValue(S))}mapToDriverValue(T,S=!1){let $=T.map((f)=>f===null?null:V(this.baseColumn,R1)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(S)return $;return O1($)}}var G1=Symbol.for("drizzle:isPgEnum");function X2(T){return!!T&&typeof T==="function"&&G1 in T&&T[G1]===!0}class w2 extends t{static[y]="PgEnumColumnBuilder";constructor(T,S){super(T,"string","PgEnumColumn");this.config.enum=S}build(T){return new K2(T,this.config)}}class K2 extends q{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,S){super(T,S);this.enum=S.enum}getSQLType(){return this.enum.enumName}}function eF(T,S){return M7(T,S,void 0)}function M7(T,S,$){let f=Object.assign((M)=>new w2(M??"",f),{enumName:T,enumValues:S,schema:$,[G1]:!0});return f}class aT{static[y]="Subquery";constructor(T,S,$,f=!1){this._={brand:"Subquery",sql:T,selectedFields:S,alias:$,isWith:f}}}class CJ extends aT{static[y]="WithSubquery"}var Y2="0.37.0";var z1,_1,QT={startActiveSpan(T,S){if(!z1)return S();if(!_1)_1=z1.trace.getTracer("drizzle-orm",Y2);return aF(($,f)=>f.startActiveSpan(T,(M)=>{try{return S(M)}catch(J){throw M.setStatus({code:$.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{M.end()}}),z1,_1)}};var xT=Symbol.for("drizzle:ViewBaseConfig");var sF=Symbol.for("drizzle:Schema"),TW=Symbol.for("drizzle:Columns"),y2=Symbol.for("drizzle:ExtraConfigColumns"),H1=Symbol.for("drizzle:OriginalName"),E1=Symbol.for("drizzle:BaseName"),SW=Symbol.for("drizzle:IsAlias"),O2=Symbol.for("drizzle:ExtraConfigBuilder"),J7=Symbol.for("drizzle:IsDrizzleTable");class v{static[y]="Table";static Symbol={Name:$$,Schema:sF,OriginalName:H1,Columns:TW,ExtraConfigColumns:y2,BaseName:E1,IsAlias:SW,ExtraConfigBuilder:O2};[$$];[H1];[sF];[TW];[y2];[E1];[SW]=!1;[J7]=!0;[O2]=void 0;constructor(T,S,$){this[$$]=this[H1]=T,this[sF]=S,this[E1]=$}}function PS(T){return T[$$]}function Ef(T){return`${T[sF]??"public"}.${T[$$]}`}function D1(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function F7(T){let S={sql:"",params:[]};for(let $ of T)if(S.sql+=$.sql,S.params.push(...$.params),$.typings?.length){if(!S.typings)S.typings=[];S.typings.push(...$.typings)}return S}class eT{static[y]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new c([this])}}class c{constructor(T){this.queryChunks=T}static[y]="SQL";decoder=G2;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return QT.startActiveSpan("drizzle.buildSQL",(S)=>{let $=this.buildQueryFromSourceParams(this.queryChunks,T);return S?.setAttributes({"drizzle.query.text":$.sql,"drizzle.query.params":JSON.stringify($.params)}),$})}buildQueryFromSourceParams(T,S){let $=Object.assign({},S,{inlineParams:S.inlineParams||this.shouldInlineParams,paramStartIndex:S.paramStartIndex||{value:0}}),{casing:f,escapeName:M,escapeParam:J,prepareTyping:F,inlineParams:W,paramStartIndex:A}=$;return F7(T.map((k)=>{if(V(k,eT))return{sql:k.value.join(""),params:[]};if(V(k,$W))return{sql:M(k.value),params:[]};if(k===void 0)return{sql:"",params:[]};if(Array.isArray(k)){let X=[new eT("(")];for(let[w,K]of k.entries())if(X.push(K),w<k.length-1)X.push(new eT(", "));return X.push(new eT(")")),this.buildQueryFromSourceParams(X,$)}if(V(k,c))return this.buildQueryFromSourceParams(k.queryChunks,{...$,inlineParams:W||k.shouldInlineParams});if(V(k,v)){let X=k[v.Symbol.Schema],w=k[v.Symbol.Name];return{sql:X===void 0?M(w):M(X)+"."+M(w),params:[]}}if(V(k,DT)){let X=f.getColumnCasing(k);if(S.invokeSource==="indexes")return{sql:M(X),params:[]};let w=k.table[v.Symbol.Schema];return{sql:k.table[SW]||w===void 0?M(k.table[v.Symbol.Name])+"."+M(X):M(w)+"."+M(k.table[v.Symbol.Name])+"."+M(X),params:[]}}if(V(k,US)){let X=k[xT].schema,w=k[xT].name;return{sql:X===void 0?M(w):M(X)+"."+M(w),params:[]}}if(V(k,IS)){if(V(k.value,u$))return{sql:J(A.value++,k),params:[k],typings:["none"]};let X=k.value===null?null:k.encoder.mapToDriverValue(k.value);if(V(X,c))return this.buildQueryFromSourceParams([X],$);if(W)return{sql:this.mapInlineParam(X,$),params:[]};let w=["none"];if(F)w=[F(k.encoder)];return{sql:J(A.value++,X),params:[X],typings:w}}if(V(k,u$))return{sql:J(A.value++,k),params:[k],typings:["none"]};if(V(k,c.Aliased)&&k.fieldAlias!==void 0)return{sql:M(k.fieldAlias),params:[]};if(V(k,aT)){if(k._.isWith)return{sql:M(k._.alias),params:[]};return this.buildQueryFromSourceParams([new eT("("),k._.sql,new eT(") "),new $W(k._.alias)],$)}if(X2(k)){if(k.schema)return{sql:M(k.schema)+"."+M(k.enumName),params:[]};return{sql:M(k.enumName),params:[]}}if(D1(k)){if(k.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([k.getSQL()],$);return this.buildQueryFromSourceParams([new eT("("),k.getSQL(),new eT(")")],$)}if(W)return{sql:this.mapInlineParam(k,$),params:[]};return{sql:J(A.value++,k),params:[k],typings:["none"]}}))}mapInlineParam(T,{escapeString:S}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return S(T);if(typeof T==="object"){let $=T.toString();if($==="[object Object]")return S(JSON.stringify(T));return S($)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new c.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class $W{constructor(T){this.value=T}static[y]="Name";brand;getSQL(){return new c([this])}}function R2(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var G2={mapFromDriverValue:(T)=>T},z2={mapToDriverValue:(T)=>T},BC={...G2,...z2};class IS{constructor(T,S=z2){this.value=T,this.encoder=S}static[y]="Param";brand;getSQL(){return new c([this])}}function O(T,...S){let $=[];if(S.length>0||T.length>0&&T[0]!=="")$.push(new eT(T[0]));for(let[f,M]of S.entries())$.push(M,new eT(T[f+1]));return new c($)}((T)=>{function S(){return new c([])}T.empty=S;function $(A){return new c(A)}T.fromList=$;function f(A){return new c([new eT(A)])}T.raw=f;function M(A,k){let X=[];for(let[w,K]of A.entries()){if(w>0&&k!==void 0)X.push(k);X.push(K)}return new c(X)}T.join=M;function J(A){return new $W(A)}T.identifier=J;function F(A){return new u$(A)}T.placeholder=F;function W(A,k){return new IS(A,k)}T.param=W})(O||(O={}));((T)=>{class S{constructor($,f){this.sql=$,this.fieldAlias=f}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new S(this.sql,this.fieldAlias)}}T.Aliased=S})(c||(c={}));class u${constructor(T){this.name=T}static[y]="Placeholder";getSQL(){return new c([this])}}function Q1(T,S){return T.map(($)=>{if(V($,u$)){if(!($.name in S))throw new Error(`No value for placeholder "${$.name}" was provided`);return S[$.name]}if(V($,IS)&&V($.value,u$)){if(!($.value.name in S))throw new Error(`No value for placeholder "${$.value.name}" was provided`);return $.encoder.mapToDriverValue(S[$.value.name])}return $})}class US{static[y]="View";[xT];constructor({name:T,schema:S,selectedFields:$,query:f}){this[xT]={name:T,originalName:T,schema:S,selectedFields:$,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new c([this])}}DT.prototype.getSQL=function(){return new c([this])};v.prototype.getSQL=function(){return new c([this])};aT.prototype.getSQL=function(){return new c([this])};class zM{constructor(T){this.table=T}static[y]="ColumnAliasProxyHandler";get(T,S){if(S==="table")return this.table;return T[S]}}class xJ{constructor(T,S){this.alias=T,this.replaceOriginalName=S}static[y]="TableAliasProxyHandler";get(T,S){if(S===v.Symbol.IsAlias)return!0;if(S===v.Symbol.Name)return this.alias;if(this.replaceOriginalName&&S===v.Symbol.OriginalName)return this.alias;if(S===xT)return{...T[xT],name:this.alias,isAlias:!0};if(S===v.Symbol.Columns){let f=T[v.Symbol.Columns];if(!f)return f;let M={};return Object.keys(f).map((J)=>{M[J]=new Proxy(f[J],new zM(new Proxy(T,this)))}),M}let $=T[S];if(V($,DT))return new Proxy($,new zM(new Proxy(T,this)));return $}}function fW(T,S){return new Proxy(T,new xJ(S,!1))}function K$(T,S){return new Proxy(T,new zM(new Proxy(T.table,new xJ(S,!1))))}function U1(T,S){return new c.Aliased(jJ(T.sql,S),T.fieldAlias)}function jJ(T,S){return O.join(T.queryChunks.map(($)=>{if(V($,DT))return K$($,S);if(V($,c))return jJ($,S);if(V($,c.Aliased))return U1($,S);return $}))}class MW extends Error{static[y]="DrizzleError";constructor({message:T,cause:S}){super(T);this.name="DrizzleError",this.cause=S}}class V1 extends MW{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function VS(T,S){if(R2(S)&&!D1(T)&&!V(T,IS)&&!V(T,u$)&&!V(T,DT)&&!V(T,v)&&!V(T,US))return new IS(T,S);return T}var JW=(T,S)=>{return O`${T} = ${VS(S,T)}`},_2=(T,S)=>{return O`${T} <> ${VS(S,T)}`};function IJ(...T){let S=T.filter(($)=>$!==void 0);if(S.length===0)return;if(S.length===1)return new c(S);return new c([new eT("("),O.join(S,new eT(" and ")),new eT(")")])}function H2(...T){let S=T.filter(($)=>$!==void 0);if(S.length===0)return;if(S.length===1)return new c(S);return new c([new eT("("),O.join(S,new eT(" or ")),new eT(")")])}function E2(T){return O`not ${T}`}var FW=(T,S)=>{return O`${T} > ${VS(S,T)}`},D2=(T,S)=>{return O`${T} >= ${VS(S,T)}`},Q2=(T,S)=>{return O`${T} < ${VS(S,T)}`},U2=(T,S)=>{return O`${T} <= ${VS(S,T)}`};function V2(T,S){if(Array.isArray(S)){if(S.length===0)return O`false`;return O`${T} in ${S.map(($)=>VS($,T))}`}return O`${T} in ${VS(S,T)}`}function B2(T,S){if(Array.isArray(S)){if(S.length===0)return O`true`;return O`${T} not in ${S.map(($)=>VS($,T))}`}return O`${T} not in ${VS(S,T)}`}function L2(T){return O`${T} is null`}function N2(T){return O`${T} is not null`}function C2(T){return O`exists ${T}`}function x2(T){return O`not exists ${T}`}function j2(T,S,$){return O`${T} between ${VS(S,T)} and ${VS($,T)}`}function I2(T,S,$){return O`${T} not between ${VS(S,T)} and ${VS($,T)}`}function b2(T,S){return O`${T} like ${S}`}function Z2(T,S){return O`${T} not like ${S}`}function q2(T,S){return O`${T} ilike ${S}`}function m2(T,S){return O`${T} not ilike ${S}`}function h2(T){return O`${T} asc`}function v2(T){return O`${T} desc`}class P2{static[y]="ConsoleLogWriter";write(T){console.log(T)}}class B1{static[y]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new P2}logQuery(T,S){let $=S.map((M)=>{try{return JSON.stringify(M)}catch{return String(M)}}),f=$.length?` -- params: [${$.join(", ")}]`:"";this.writer.write(`Query: ${T}${f}`)}}class L1{static[y]="NoopLogger";logQuery(){}}class zS{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}then(T,S){return this.execute().then(T,S)}}function n2(T,S,$){let f={},M=T.reduce((J,{path:F,field:W},A)=>{let k;if(V(W,DT))k=W;else if(V(W,c))k=W.decoder;else k=W.sql.decoder;let X=J;for(let[w,K]of F.entries())if(w<F.length-1){if(!(K in X))X[K]={};X=X[K]}else{let G=S[A],z=X[K]=G===null?null:k.mapFromDriverValue(G);if($&&V(W,DT)&&F.length===2){let U=F[0];if(!(U in f))f[U]=z===null?PS(W.table):!1;else if(typeof f[U]==="string"&&f[U]!==PS(W.table))f[U]=!1}}return J},{});if($&&Object.keys(f).length>0){for(let[J,F]of Object.entries(f))if(typeof F==="string"&&!$[F])M[J]=null}return M}function nS(T,S){return Object.entries(T).reduce(($,[f,M])=>{if(typeof f!=="string")return $;let J=S?[...S,f]:[f];if(V(M,DT)||V(M,c)||V(M,c.Aliased))$.push({path:J,field:M});else if(V(M,v))$.push(...nS(M[v.Symbol.Columns],J));else $.push(...nS(M,J));return $},[])}function bJ(T,S){let $=Object.keys(T),f=Object.keys(S);if($.length!==f.length)return!1;for(let[M,J]of $.entries())if(J!==f[M])return!1;return!0}function WW(T,S){let $=Object.entries(S).filter(([,f])=>f!==void 0).map(([f,M])=>{if(V(M,c)||V(M,DT))return[f,M];else return[f,new IS(M,T[v.Symbol.Columns][f])]});if($.length===0)throw new Error("No values to set");return Object.fromEntries($)}function c2(T,S){for(let $ of S)for(let f of Object.getOwnPropertyNames($.prototype)){if(f==="constructor")continue;Object.defineProperty(T.prototype,f,Object.getOwnPropertyDescriptor($.prototype,f)||Object.create(null))}}function g2(T){return T[v.Symbol.Columns]}function x$(T){return V(T,aT)?T._.alias:V(T,US)?T[xT].name:V(T,c)?void 0:T[v.Symbol.IsAlias]?T[v.Symbol.Name]:T[v.Symbol.BaseName]}function AT(T,S){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:S}}function o2(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let S=typeof T.logger;if(S!=="boolean"&&(S!=="object"||typeof T.logger.logQuery!=="function")&&S!=="undefined")return!1;return!0}if("schema"in T){let S=typeof T.logger;if(S!=="object"&&S!=="undefined")return!1;return!0}if("casing"in T){let S=typeof T.logger;if(S!=="string"&&S!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let S=typeof T.connection;if(S!=="string"&&S!=="object"&&S!=="undefined")return!1;return!0}if("client"in T){let S=typeof T.client;if(S!=="object"&&S!=="function"&&S!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class l$ extends t{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:S,...$}=T;this.config.generatedIdentity={type:"always",sequenceName:S,sequenceOptions:$}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:S,...$}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:S,sequenceOptions:$}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class t2 extends l${static[y]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new p2(T,this.config)}}class p2 extends q{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class i2 extends l${static[y]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new d2(T,this.config)}}class d2 extends q{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function u2(T,S){let{name:$,config:f}=AT(T,S);if(f.mode==="number")return new t2($);return new i2($)}class l2 extends t{static[y]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new r2(T,this.config)}}class r2 extends q{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class a2 extends t{static[y]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new e2(T,this.config)}}class e2 extends q{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function s2(T,S){let{name:$,config:f}=AT(T,S);if(f.mode==="number")return new l2($);return new a2($)}class T8 extends t{static[y]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new S8(T,this.config)}}class S8 extends q{static[y]="PgBoolean";getSQLType(){return"boolean"}}function ZJ(T){return new T8(T??"")}class $8 extends t{static[y]="PgCharBuilder";constructor(T,S){super(T,"string","PgChar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new f8(T,this.config)}}class f8 extends q{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function M8(T,S={}){let{name:$,config:f}=AT(T,S);return new $8($,f)}class J8 extends t{static[y]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new F8(T,this.config)}}class F8 extends q{static[y]="PgCidr";getSQLType(){return"cidr"}}function W8(T){return new J8(T??"")}class A8 extends t{static[y]="PgCustomColumnBuilder";constructor(T,S,$){super(T,"custom","PgCustomColumn");this.config.fieldConfig=S,this.config.customTypeParams=$}build(T){return new k8(T,this.config)}}class k8 extends q{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,S){super(T,S);this.sqlName=S.customTypeParams.dataType(S.fieldConfig),this.mapTo=S.customTypeParams.toDriver,this.mapFrom=S.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function X8(T){return(S,$)=>{let{name:f,config:M}=AT(S,$);return new A8(f,M,T)}}class j$ extends t{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(O`now()`)}}class w8 extends j${static[y]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new AW(T,this.config)}}class AW extends q{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class K8 extends j${static[y]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new kW(T,this.config)}}class kW extends q{static[y]="PgDateString";getSQLType(){return"date"}}function Y8(T,S){let{name:$,config:f}=AT(T,S);if(f?.mode==="date")return new w8($);return new K8($)}class y8 extends t{static[y]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new O8(T,this.config)}}class O8 extends q{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function R8(T){return new y8(T??"")}class G8 extends t{static[y]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new z8(T,this.config)}}class z8 extends q{static[y]="PgInet";getSQLType(){return"inet"}}function _8(T){return new G8(T??"")}class H8 extends l${static[y]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new E8(T,this.config)}}class E8 extends q{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function XW(T){return new H8(T??"")}class D8 extends t{static[y]="PgIntervalBuilder";constructor(T,S){super(T,"string","PgInterval");this.config.intervalConfig=S}build(T){return new Q8(T,this.config)}}class Q8 extends q{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",S=this.precision?`(${this.precision})`:"";return`interval${T}${S}`}}function U8(T,S={}){let{name:$,config:f}=AT(T,S);return new D8($,f)}class V8 extends t{static[y]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new wW(T,this.config)}}class wW extends q{static[y]="PgJson";constructor(T,S){super(T,S)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function B8(T){return new V8(T??"")}class L8 extends t{static[y]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new KW(T,this.config)}}class KW extends q{static[y]="PgJsonb";constructor(T,S){super(T,S)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function N8(T){return new L8(T??"")}class C8 extends t{static[y]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new x8(T,this.config)}}class x8 extends q{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[S,$,f]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($),Number.parseFloat(f)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class j8 extends t{static[y]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new I8(T,this.config)}}class I8 extends q{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[S,$,f]=T.slice(1,-1).split(",");return{a:Number.parseFloat(S),b:Number.parseFloat($),c:Number.parseFloat(f)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function b8(T,S){let{name:$,config:f}=AT(T,S);if(!f?.mode||f.mode==="tuple")return new C8($);return new j8($)}class Z8 extends t{static[y]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new q8(T,this.config)}}class q8 extends q{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function m8(T){return new Z8(T??"")}class h8 extends t{static[y]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new v8(T,this.config)}}class v8 extends q{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function P8(T){return new h8(T??"")}class n8 extends t{static[y]="PgNumericBuilder";constructor(T,S,$){super(T,"string","PgNumeric");this.config.precision=S,this.config.scale=$}build(T){return new YW(T,this.config)}}class YW extends q{static[y]="PgNumeric";precision;scale;constructor(T,S){super(T,S);this.precision=S.precision,this.scale=S.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function c8(T,S){let{name:$,config:f}=AT(T,S);return new n8($,f?.precision,f?.scale)}class g8 extends t{static[y]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new o8(T,this.config)}}class o8 extends q{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[S,$]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class t8 extends t{static[y]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new p8(T,this.config)}}class p8 extends q{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[S,$]=T.slice(1,-1).split(",");return{x:Number.parseFloat(S),y:Number.parseFloat($)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function i8(T,S){let{name:$,config:f}=AT(T,S);if(!f?.mode||f.mode==="tuple")return new g8($);return new t8($)}function W7(T){let S=[];for(let $=0;$<T.length;$+=2)S.push(Number.parseInt(T.slice($,$+2),16));return new Uint8Array(S)}function d8(T,S){let $=new ArrayBuffer(8),f=new DataView($);for(let M=0;M<8;M++)f.setUint8(M,T[S+M]);return f.getFloat64(0,!0)}function N1(T){let S=W7(T),$=0,f=S[$];$+=1;let M=new DataView(S.buffer),J=M.getUint32($,f===1);$+=4;let F;if(J&536870912)F=M.getUint32($,f===1),$+=4;if((J&65535)===1){let W=d8(S,$);$+=8;let A=d8(S,$);return $+=8,[W,A]}throw new Error("Unsupported geometry type")}class u8 extends t{static[y]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new l8(T,this.config)}}class l8 extends q{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return N1(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class r8 extends t{static[y]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new a8(T,this.config)}}class a8 extends q{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let S=N1(T);return{x:S[0],y:S[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function e8(T,S){let{name:$,config:f}=AT(T,S);if(!f?.mode||f.mode==="tuple")return new u8($);return new r8($)}class s8 extends t{static[y]="PgRealBuilder";constructor(T,S){super(T,"number","PgReal");this.config.length=S}build(T){return new Tw(T,this.config)}}class Tw extends q{static[y]="PgReal";constructor(T,S){super(T,S)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function Sw(T){return new s8(T??"")}class $w extends t{static[y]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new fw(T,this.config)}}class fw extends q{static[y]="PgSerial";getSQLType(){return"serial"}}function Mw(T){return new $w(T??"")}class Jw extends l${static[y]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new Fw(T,this.config)}}class Fw extends q{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function Ww(T){return new Jw(T??"")}class Aw extends t{static[y]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new kw(T,this.config)}}class kw extends q{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function Xw(T){return new Aw(T??"")}class ww extends t{static[y]="PgTextBuilder";constructor(T,S){super(T,"string","PgText");this.config.enumValues=S.enum}build(T){return new Kw(T,this.config)}}class Kw extends q{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Yw(T,S={}){let{name:$,config:f}=AT(T,S);return new ww($,f)}class yw extends j${constructor(T,S,$){super(T,"string","PgTime");this.withTimezone=S,this.precision=$,this.config.withTimezone=S,this.config.precision=$}static[y]="PgTimeBuilder";build(T){return new yW(T,this.config)}}class yW extends q{static[y]="PgTime";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function Ow(T,S={}){let{name:$,config:f}=AT(T,S);return new yw($,f.withTimezone??!1,f.precision)}class Rw extends j${static[y]="PgTimestampBuilder";constructor(T,S,$){super(T,"date","PgTimestamp");this.config.withTimezone=S,this.config.precision=$}build(T){return new OW(T,this.config)}}class OW extends q{static[y]="PgTimestamp";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class Gw extends j${static[y]="PgTimestampStringBuilder";constructor(T,S,$){super(T,"string","PgTimestampString");this.config.withTimezone=S,this.config.precision=$}build(T){return new RW(T,this.config)}}class RW extends q{static[y]="PgTimestampString";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function f$(T,S={}){let{name:$,config:f}=AT(T,S);if(f?.mode==="string")return new Gw($,f.withTimezone??!1,f.precision);return new Rw($,f?.withTimezone??!1,f?.precision)}class zw extends t{static[y]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(O`gen_random_uuid()`)}build(T){return new GW(T,this.config)}}class GW extends q{static[y]="PgUUID";getSQLType(){return"uuid"}}function bS(T){return new zw(T??"")}class _w extends t{static[y]="PgVarcharBuilder";constructor(T,S){super(T,"string","PgVarchar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new Hw(T,this.config)}}class Hw extends q{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function fS(T,S={}){let{name:$,config:f}=AT(T,S);return new _w($,f)}class Ew extends t{static[y]="PgBinaryVectorBuilder";constructor(T,S){super(T,"string","PgBinaryVector");this.config.dimensions=S.dimensions}build(T){return new Dw(T,this.config)}}class Dw extends q{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function Qw(T,S){let{name:$,config:f}=AT(T,S);return new Ew($,f)}class Uw extends t{static[y]="PgHalfVectorBuilder";constructor(T,S){super(T,"array","PgHalfVector");this.config.dimensions=S.dimensions}build(T){return new Vw(T,this.config)}}class Vw extends q{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function Bw(T,S){let{name:$,config:f}=AT(T,S);return new Uw($,f)}class Lw extends t{static[y]="PgSparseVectorBuilder";constructor(T,S){super(T,"string","PgSparseVector");this.config.dimensions=S.dimensions}build(T){return new Nw(T,this.config)}}class Nw extends q{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function Cw(T,S){let{name:$,config:f}=AT(T,S);return new Lw($,f)}class xw extends t{static[y]="PgVectorBuilder";constructor(T,S){super(T,"array","PgVector");this.config.dimensions=S.dimensions}build(T){return new jw(T,this.config)}}class jw extends q{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function Iw(T,S){let{name:$,config:f}=AT(T,S);return new xw($,f)}function bw(){return{bigint:u2,bigserial:s2,boolean:ZJ,char:M8,cidr:W8,customType:X8,date:Y8,doublePrecision:R8,inet:_8,integer:XW,interval:U8,json:B8,jsonb:N8,line:b8,macaddr:m8,macaddr8:P8,numeric:c8,point:i8,geometry:e8,real:Sw,serial:Mw,smallint:Ww,smallserial:Xw,text:Yw,time:Ow,timestamp:f$,uuid:bS,varchar:fS,bit:Qw,halfvec:Bw,sparsevec:Cw,vector:Iw}}var C1=Symbol.for("drizzle:PgInlineForeignKeys"),Zw=Symbol.for("drizzle:EnableRLS");class MS extends v{static[y]="PgTable";static Symbol=Object.assign({},v.Symbol,{InlineForeignKeys:C1,EnableRLS:Zw});[C1]=[];[Zw]=!1;[v.Symbol.ExtraConfigBuilder]=void 0}function A7(T,S,$,f,M=T){let J=new MS(T,f,M),F=typeof S==="function"?S(bw()):S,W=Object.fromEntries(Object.entries(F).map(([X,w])=>{let K=w;K.setName(X);let G=K.build(J);return J[C1].push(...K.buildForeignKeys(G,J)),[X,G]})),A=Object.fromEntries(Object.entries(F).map(([X,w])=>{let K=w;K.setName(X);let G=K.buildExtraConfigColumn(J);return[X,G]})),k=Object.assign(J,W);if(k[v.Symbol.Columns]=W,k[v.Symbol.ExtraConfigColumns]=A,$)k[MS.Symbol.ExtraConfigBuilder]=$;return Object.assign(k,{enableRLS:()=>{return k[MS.Symbol.EnableRLS]=!0,k}})}var r$=(T,S,$)=>{return A7(T,S,$,void 0)};function qw(...T){if(T[0].columns)return new qJ(T[0].columns,T[0].name);return new qJ(T)}class qJ{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(T,S){this.columns=T,this.name=S}build(T){return new mw(T,this.columns,this.name)}}class mw{constructor(T,S,$){this.table=T,this.columns=S,this.name=$}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[MS.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class x1{constructor(T,S,$){this.sourceTable=T,this.referencedTable=S,this.relationName=$,this.referencedTableName=S[v.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class hw{constructor(T,S){this.table=T,this.config=S}static[y]="Relations"}class a$ extends x1{constructor(T,S,$,f){super(T,S,$?.relationName);this.config=$,this.isNullable=f}static[y]="One";withFieldName(T){let S=new a$(this.sourceTable,this.referencedTable,this.config,this.isNullable);return S.fieldName=T,S}}class mJ extends x1{constructor(T,S,$){super(T,S,$?.relationName);this.config=$}static[y]="Many";withFieldName(T){let S=new mJ(this.sourceTable,this.referencedTable,this.config);return S.fieldName=T,S}}function vw(){return{and:IJ,between:j2,eq:JW,exists:C2,gt:FW,gte:D2,ilike:q2,inArray:V2,isNull:L2,isNotNull:N2,like:b2,lt:Q2,lte:U2,ne:_2,not:E2,notBetween:I2,notExists:x2,notLike:Z2,notIlike:m2,notInArray:B2,or:H2,sql:O}}function Pw(){return{sql:O,asc:h2,desc:v2}}function nw(T,S){if(Object.keys(T).length===1&&"default"in T&&!V(T.default,v))T=T.default;let $={},f={},M={};for(let[J,F]of Object.entries(T))if(V(F,v)){let W=Ef(F),A=f[W];$[W]=J,M[J]={tsName:J,dbName:F[v.Symbol.Name],schema:F[v.Symbol.Schema],columns:F[v.Symbol.Columns],relations:A?.relations??{},primaryKey:A?.primaryKey??[]};for(let X of Object.values(F[v.Symbol.Columns]))if(X.primary)M[J].primaryKey.push(X);let k=F[v.Symbol.ExtraConfigBuilder]?.(F[v.Symbol.ExtraConfigColumns]);if(k){for(let X of Object.values(k))if(V(X,qJ))M[J].primaryKey.push(...X.columns)}}else if(V(F,hw)){let W=Ef(F.table),A=$[W],k=F.config(S(F.table)),X;for(let[w,K]of Object.entries(k))if(A){let G=M[A];if(G.relations[w]=K,X)G.primaryKey.push(...X)}else{if(!(W in f))f[W]={relations:{},primaryKey:X};f[W].relations[w]=K}}return{tables:M,tableNamesMap:$}}function k7(T){return function S($,f){return new a$(T,$,f,f?.fields.reduce((M,J)=>M&&J.notNull,!0)??!1)}}function X7(T){return function S($,f){return new mJ(T,$,f)}}function cw(T,S,$){if(V($,a$)&&$.config)return{fields:$.config.fields,references:$.config.references};let f=S[Ef($.referencedTable)];if(!f)throw new Error(`Table "${$.referencedTable[v.Symbol.Name]}" not found in schema`);let M=T[f];if(!M)throw new Error(`Table "${f}" not found in schema`);let J=$.sourceTable,F=S[Ef(J)];if(!F)throw new Error(`Table "${J[v.Symbol.Name]}" not found in schema`);let W=[];for(let A of Object.values(M.relations))if($.relationName&&$!==A&&A.relationName===$.relationName||!$.relationName&&A.referencedTable===$.sourceTable)W.push(A);if(W.length>1)throw $.relationName?new Error(`There are multiple relations with name "${$.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${$.sourceTable[v.Symbol.Name]}". Please specify relation name`);if(W[0]&&V(W[0],a$)&&W[0].config)return{fields:W[0].config.references,references:W[0].config.fields};throw new Error(`There is not enough information to infer relation "${F}.${$.fieldName}"`)}function gw(T){return{one:k7(T),many:X7(T)}}function zW(T,S,$,f,M=(J)=>J){let J={};for(let[F,W]of f.entries())if(W.isJson){let A=S.relations[W.tsKey],k=$[F],X=typeof k==="string"?JSON.parse(k):k;J[W.tsKey]=V(A,a$)?X&&zW(T,T[W.relationTableTsKey],X,W.selection,M):X.map((w)=>zW(T,T[W.relationTableTsKey],w,W.selection,M))}else{let A=M($[F]),k=W.field,X;if(V(k,DT))X=k;else if(V(k,c))X=k.decoder;else X=k.sql.decoder;J[W.tsKey]=A===null?null:X.mapFromDriverValue(A)}return J}import Jy from"path";import Z7 from"os";import q7 from"fs";var _W=new Map,j1=new Map,I1=Symbol("OriginError"),_M={};class cS extends Promise{constructor(T,S,$,f,M={}){let J,F;super((W,A)=>{J=W,F=A});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=S,this.handler=$,this.canceller=f,this.options=M,this.state=null,this.statement=null,this.resolve=(W)=>(this.active=!1,J(W)),this.reject=(W)=>(this.active=!1,F(W)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[I1]=this.handler.debug?new Error:this.tagged&&w7(this.strings)}get origin(){return(this.handler.debug?this[I1].stack:this.tagged&&j1.has(this.strings)?j1.get(this.strings):j1.set(this.strings,this[I1].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,S){if(this.options.simple=!1,typeof T==="function")S=T,T=1;if(this.cursorRows=T,typeof S==="function")return this.cursorFn=S,this;let $;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};$&&$();let f=new Promise((M,J)=>{this.cursorFn=(F)=>{return M({value:F,done:!1}),new Promise((W)=>$=W)},this.resolve=()=>(this.active=!1,M({done:!0})),this.reject=(F)=>(this.active=!1,J(F))});return this.execute(),f},return(){return $&&$(_M),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function w7(T){if(_W.has(T))return _W.get(T);let S=Error.stackTraceLimit;return Error.stackTraceLimit=4,_W.set(T,new Error),Error.stackTraceLimit=S,_W.get(T)}class HM extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var oT={connection:ow,postgres:tw,generic:pw,notSupported:iw};function ow(T,S,$){let{host:f,port:M}=$||S,J=Object.assign(new Error("write "+T+" "+(S.path||f+":"+M)),{code:T,errno:T,address:S.path||f},S.path?{}:{port:M});return Error.captureStackTrace(J,ow),J}function tw(T){let S=new HM(T);return Error.captureStackTrace(S,tw),S}function pw(T,S){let $=Object.assign(new Error(T+": "+S),{code:T});return Error.captureStackTrace($,pw),$}function iw(T){let S=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(S,iw),S}var K7={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class DW{then(){b1()}catch(){b1()}finally(){b1()}}class nJ extends DW{constructor(T){super();this.value=VW(T)}}class Y$ extends DW{constructor(T,S,$){super();this.value=T,this.type=S,this.array=$}}class QW extends DW{constructor(T,S){super();this.first=T,this.rest=S}build(T,S,$,f){let M=Y7.map(([J,F])=>({fn:F,i:T.search(J)})).sort((J,F)=>J.i-F.i).pop();return M.i===-1?v1(this.first,f):M.fn(this.first,this.rest,S,$,f)}}function UW(T,S,$,f){let M=T instanceof Y$?T.value:T;if(M===void 0){if(T instanceof Y$?T.value=f.transform.undefined:M=T=f.transform.undefined,M===void 0)throw oT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+$.push(T instanceof Y$?(S.push(T.value),T.array?T.array[T.type||EW(T.value)]||T.type||rw(T.value):T.type):(S.push(T),EW(T)))}var uw=ew(K7);function m1(T,S,$,f,M,J){for(let F=1;F<T.strings.length;F++)S+=h1(S,$,f,M,J)+T.strings[F],$=T.args[F];return S}function h1(T,S,$,f,M){return S instanceof QW?S.build(T,$,f,M):S instanceof cS?q1(S,$,f,M):S instanceof nJ?S.value:S&&S[0]instanceof cS?S.reduce((J,F)=>J+" "+q1(F,$,f,M),""):UW(S,$,f,M)}function q1(T,S,$,f){return T.fragment=!0,m1(T,T.strings[0],T.args[0],S,$,f)}function lw(T,S,$,f,M){return T.map((J)=>"("+f.map((F)=>h1("values",J[F],S,$,M)).join(",")+")").join(",")}function dw(T,S,$,f,M){let J=Array.isArray(T[0]),F=S.length?S.flat():Object.keys(J?T[0]:T);return lw(J?T:[T],$,f,F,M)}function HW(T,S,$,f,M){if(typeof T==="string"&&(T=[T].concat(S)),Array.isArray(T))return v1(T,M);let J;return(S.length?S.flat():Object.keys(T)).map((W)=>{return J=T[W],(J instanceof cS?q1(J,$,f,M):J instanceof nJ?J.value:UW(J,$,f,M))+" as "+VW(M.transform.column.to?M.transform.column.to(W):W)}).join(",")}var Y7=Object.entries({values:dw,in:(...T)=>{let S=dw(...T);return S==="()"?"(null)":S},select:HW,as:HW,returning:HW,"\\(":HW,update(T,S,$,f,M){return(S.length?S.flat():Object.keys(T)).map((J)=>VW(M.transform.column.to?M.transform.column.to(J):J)+"="+h1("values",T[J],$,f,M))},insert(T,S,$,f,M){let J=S.length?S.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+v1(J,M)+")values"+lw(Array.isArray(T)?T:[T],$,f,J,M)}}).map(([T,S])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),S]);function b1(){throw oT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:y7,parsers:O7}=uw;function rw(T){if(Array.isArray(T))return rw(T[0]);return typeof T==="string"?1009:0}var aw=function(T){let S=ew(T||{});return{serializers:Object.assign({},y7,S.serializers),parsers:Object.assign({},O7,S.parsers)}};function ew(T){return Object.keys(T).reduce((S,$)=>{if(T[$].from&&[].concat(T[$].from).forEach((f)=>S.parsers[f]=T[$].parse),T[$].serialize)S.serializers[T[$].to]=T[$].serialize,T[$].from&&[].concat(T[$].from).forEach((f)=>S.serializers[f]=T[$].serialize);return S},{parsers:{},serializers:{}})}function v1(T,{transform:{column:S}}){return T.map(($)=>VW(S.to?S.to($):$)).join(",")}var VW=function T(S){return'"'+S.replace(/"/g,'""').replace(/\./g,'"."')+'"'},EW=function T(S){return S instanceof Y$?S.type:S instanceof Date?1184:S instanceof Uint8Array?17:S===!0||S===!1?16:typeof S==="bigint"?20:Array.isArray(S)?T(S[0]):0},R7=/\\/g,G7=/"/g;function z7(T){return T.replace(R7,"\\\\").replace(G7,"\\\"")}var sw=function T(S,$,f,M){if(Array.isArray(S)===!1)return S;if(!S.length)return"{}";let J=S[0],F=M===1020?";":",";if(Array.isArray(J)&&!J.type)return"{"+S.map((W)=>T(W,$,f,M)).join(F)+"}";return"{"+S.map((W)=>{if(W===void 0){if(W=f.transform.undefined,W===void 0)throw oT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return W===null?"null":'"'+z7($?$(W.type?W.value:W):""+W)+'"'}).join(F)+"}"},Z1={i:0,char:null,str:"",quoted:!1,last:0},TK=function T(S,$,f){return Z1.i=Z1.last=0,SK(Z1,S,$,f)};function SK(T,S,$,f){let M=[],J=f===1020?";":",";for(;T.i<S.length;T.i++){if(T.char=S[T.i],T.quoted)if(T.char==="\\")T.str+=S[++T.i];else if(T.char==='"')M.push($?$(T.str):T.str),T.str="",T.quoted=S[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,M.push(SK(T,S,$,f));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&M.push($?$(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===J&&T.p!=="}"&&T.p!=='"')M.push($?$(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&M.push($?$(S.slice(T.last,T.i+1)):S.slice(T.last,T.i+1)),M}var Df=(T)=>{let S=T[0];for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Qf=(T)=>{let S=T[0].toUpperCase();for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Uf=(T)=>T.replace(/_/g,"-"),hJ=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),vJ=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),PJ=(T)=>T.replace(/-/g,"_");function P1(T){return function S($,f){return typeof $==="object"&&$!==null&&(f.type===114||f.type===3802)?Array.isArray($)?$.map((M)=>S(M,f)):Object.entries($).reduce((M,[J,F])=>Object.assign(M,{[T(J)]:S(F,f)}),{}):$}}Df.column={from:Df};Df.value={from:P1(Df)};hJ.column={to:hJ};var n1={...Df};n1.column.to=hJ;Qf.column={from:Qf};Qf.value={from:P1(Qf)};vJ.column={to:vJ};var c1={...Qf};c1.column.to=vJ;Uf.column={from:Uf};Uf.value={from:P1(Uf)};PJ.column={to:PJ};var g1={...Uf};g1.column.to=PJ;import $K from"net";import D7 from"tls";import cJ from"crypto";import o1 from"stream";import{performance as fK}from"perf_hooks";class Vf extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var ZS=_7;function _7(T=[]){let S=T.slice(),$=0;return{get length(){return S.length-$},remove:(f)=>{let M=S.indexOf(f);return M===-1?null:(S.splice(M,1),f)},push:(f)=>(S.push(f),f),shift:()=>{let f=S[$++];if($===S.length)$=0,S=[];else S[$-1]=void 0;return f}}}var yS=Buffer.allocUnsafe(256),H7="BCcDdEFfHPpQSX".split("").reduce((T,S)=>{let $=S.charCodeAt(0);return T[S]=()=>{return yS[0]=$,ET.i=5,ET},T},{}),ET=Object.assign(E7,H7,{N:String.fromCharCode(0),i:0,inc(T){return ET.i+=T,ET},str(T){let S=Buffer.byteLength(T);return BW(S),ET.i+=yS.write(T,ET.i,S,"utf8"),ET},i16(T){return BW(2),yS.writeUInt16BE(T,ET.i),ET.i+=2,ET},i32(T,S){if(S||S===0)return yS.writeUInt32BE(T,S),ET;return BW(4),yS.writeUInt32BE(T,ET.i),ET.i+=4,ET},z(T){return BW(T),yS.fill(0,ET.i,ET.i+T),ET.i+=T,ET},raw(T){return yS=Buffer.concat([yS.subarray(0,ET.i),T]),ET.i=yS.length,ET},end(T=1){yS.writeUInt32BE(ET.i-T,T);let S=yS.subarray(0,ET.i);return ET.i=0,yS=Buffer.allocUnsafe(256),S}}),r=ET;function BW(T){if(yS.length-ET.i<T){let S=yS,$=S.length;yS=Buffer.allocUnsafe($+($>>1)+T),S.copy(yS)}}function E7(){return ET.i=0,ET}var i1=FK,Q7=1,e$=r().S().end(),MK=r().H().end(),U7=r().i32(8).i32(80877103).end(8),V7=Buffer.concat([r().E().str(r.N).i32(0).end(),e$]),B7=r().D().str("S").str(r.N).end(),EM=()=>{},L7=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),N7={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function FK(T,S={},{onopen:$=EM,onend:f=EM,onclose:M=EM}={}){let{ssl:J,max:F,user:W,host:A,port:k,database:X,parsers:w,transform:K,onnotice:G,onnotify:z,onparameter:U,max_pipeline:D,keep_alive:B,backoff:L,target_session_attrs:Z}=T,j=ZS(),E=Q7++,_={pid:null,secret:null},Q=p1(nW,T.idle_timeout),b=p1(nW,T.max_lifetime),h=p1(jK,T.connect_timeout),R=null,g,n=new Vf,p=Buffer.alloc(0),OT=T.fetch_types,_T={},HS={},y$=Math.random().toString(36).slice(2),N=1,l=0,RT=0,jT=0,tT=0,FT=0,UT=0,cT=0,bT=null,LT=null,FS=!1,VT=null,gS=null,WS=null,Z$=null,pT=null,NT=null,oS=null,M$=null,m=null,VM=null,AS={queue:S.closed,idleTimer:Q,connect(Y){WS=Y||!0,RA()},terminate:LM,execute:BM,cancel:LK,end:nW,count:0,id:E};return S.closed&&S.closed.push(AS),AS;async function BK(){let Y;try{Y=T.socket?await Promise.resolve(T.socket(T)):new $K.Socket}catch(H){Cf(H);return}return Y.on("error",Cf),Y.on("close",GA),Y.on("drain",yA),Y}async function LK({pid:Y,secret:H},a,GT){try{g=r().i32(16).i32(80877102).i32(Y).i32(H).end(16),await OA(),R.once("error",GT),R.once("close",a)}catch(hT){GT(hT)}}function BM(Y){if(FS)return uJ(Y,oT.connection("CONNECTION_DESTROYED",T));if(Y.cancelled)return;try{return Y.state=_,m?j.push(Y):(m=Y,m.active=!0),xK(Y),TS(NK(Y))&&!Y.describeFirst&&!Y.cursorFn&&j.length<D&&(!Y.options.onexecute||Y.options.onexecute(AS))}catch(H){return j.length===0&&TS(e$),J$(H),!0}}function NK(Y){if(Y.parameters.length>=65534)throw oT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return Y.options.simple?r().Q().str(Y.statement.string+r.N).end():Y.describeFirst?Buffer.concat([wA(Y),MK]):Y.prepare?Y.prepared?dJ(Y):Buffer.concat([wA(Y),dJ(Y)]):CK(Y)}function wA(Y){return Buffer.concat([_A(Y.statement.string,Y.parameters,Y.statement.types,Y.statement.name),O4("S",Y.statement.name)])}function dJ(Y){return Buffer.concat([y4(Y.parameters,Y.statement.types,Y.statement.name,Y.cursorName),Y.cursorFn?HA("",Y.cursorRows):V7])}function CK(Y){return Buffer.concat([_A(Y.statement.string,Y.parameters,Y.statement.types),B7,dJ(Y)])}function xK(Y){let H=[],a=[],GT=m1(Y,Y.strings[0],Y.args[0],H,a,T);!Y.tagged&&Y.args.forEach((hT)=>UW(hT,H,a,T)),Y.prepare=T.prepare&&("prepare"in Y.options?Y.options.prepare:!0),Y.string=GT,Y.signature=Y.prepare&&a+GT,Y.onlyDescribe&&delete HS[Y.signature],Y.parameters=Y.parameters||H,Y.prepared=Y.prepare&&Y.signature in HS,Y.describeFirst=Y.onlyDescribe||H.length&&!Y.prepared,Y.statement=Y.prepared?HS[Y.signature]:{string:GT,types:a,name:Y.prepare?y$+N++:""},typeof T.debug==="function"&&T.debug(E,GT,H,a)}function TS(Y,H){if(NT=NT?Buffer.concat([NT,Y]):Buffer.from(Y),H||NT.length>=1024)return KA(H);return LT===null&&(LT=setImmediate(KA)),!0}function KA(Y){let H=R.write(NT,Y);return LT!==null&&clearImmediate(LT),NT=LT=null,H}function jK(){J$(oT.connection("CONNECT_TIMEOUT",T,R)),R.destroy()}async function YA(){if(TS(U7),!await new Promise((H)=>R.once("data",(a)=>H(a[0]===83)))&&J==="prefer")return Nf();R.removeAllListeners(),R=D7.connect({socket:R,servername:$K.isIP(R.host)?void 0:R.host,...J==="require"||J==="allow"||J==="prefer"?{rejectUnauthorized:!1}:J==="verify-full"?{}:typeof J==="object"?J:{}}),R.on("secureConnect",Nf),R.on("error",Cf),R.on("close",GA),R.on("drain",yA)}function yA(){!m&&$(AS)}function PW(Y){if(VT){if(VT.push(Y),RT-=Y.length,RT>=0)return}p=VT?Buffer.concat(VT,FT-RT):p.length===0?Y:Buffer.concat([p,Y],p.length+Y.length);while(p.length>4){if(FT=p.readUInt32BE(1),FT>=p.length){RT=FT-p.length,VT=[p];break}try{IK(p.subarray(0,FT+1))}catch(H){m&&(m.cursorFn||m.describeFirst)&&TS(e$),J$(H)}p=p.subarray(FT+1),RT=0,VT=null}}async function OA(){if(FS=!1,_T={},R||(R=await BK()),!R)return;if(h.start(),T.socket)return J?YA():Nf();if(R.on("connect",J?YA:Nf),T.path)return R.connect(T.path);R.ssl=J,R.connect(k[jT],A[jT]),R.host=A[jT],R.port=k[jT],jT=(jT+1)%k.length}function RA(){setTimeout(OA,l?l+UT-fK.now():0)}function Nf(){try{HS={},OT=T.fetch_types,y$=Math.random().toString(36).slice(2),N=1,b.start(),R.on("data",PW),B&&R.setKeepAlive&&R.setKeepAlive(!0,1000*B);let Y=G4();TS(Y)}catch(Y){Cf(Y)}}function Cf(Y){if(AS.queue===S.connecting&&T.host[tT+1])return;J$(Y);while(j.length)uJ(j.shift(),Y)}function J$(Y){pT&&(pT.destroy(Y),pT=null),m&&uJ(m,Y),WS&&(uJ(WS,Y),WS=null)}function uJ(Y,H){"query"in H||"parameters"in H||Object.defineProperties(H,{stack:{value:H.stack+Y.origin.replace(/.*\n/,`
43
+ `),enumerable:T.debug},query:{value:Y.string,enumerable:T.debug},parameters:{value:Y.parameters,enumerable:T.debug},args:{value:Y.args,enumerable:T.debug},types:{value:Y.statement&&Y.statement.types,enumerable:T.debug}}),Y.reject(H)}function nW(){return Z$||(!AS.reserved&&f(AS),!AS.reserved&&!WS&&!m&&j.length===0?(LM(),new Promise((Y)=>R&&R.readyState!=="closed"?R.once("close",Y):Y())):Z$=new Promise((Y)=>oS=Y))}function LM(){if(FS=!0,pT||m||WS||j.length)Cf(oT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(LT),R)R.removeListener("data",PW),R.removeListener("connect",Nf),R.readyState==="open"&&R.end(r().X().end());oS&&(oS(),Z$=oS=null)}async function GA(Y){if(p=Buffer.alloc(0),RT=0,VT=null,clearImmediate(LT),R.removeListener("data",PW),R.removeListener("connect",Nf),Q.cancel(),b.cancel(),h.cancel(),R.removeAllListeners(),R=null,WS)return RA();!Y&&(m||j.length)&&Cf(oT.connection("CONNECTION_CLOSED",T,R)),l=fK.now(),Y&&T.shared.retries++,UT=(typeof L==="function"?L(T.shared.retries):L)*1000,M(AS,oT.connection("CONNECTION_CLOSED",T,R))}function IK(Y,H=Y[0]){(H===68?bK:H===100?F4:H===65?T4:H===83?ZK:H===90?qK:H===67?mK:H===50?zA:H===49?hK:H===116?vK:H===84?PK:H===82?nK:H===110?iK:H===75?dK:H===69?eK:H===115?S4:H===51?$4:H===71?f4:H===78?A4:H===72?M4:H===99?W4:H===73?k4:H===86?X4:H===118?w4:H===87?J4:K4)(Y)}function bK(Y){let H=7,a,GT,hT,kS=m.isRaw?new Array(m.statement.columns.length):{};for(let OS=0;OS<m.statement.columns.length;OS++)GT=m.statement.columns[OS],a=Y.readInt32BE(H),H+=4,hT=a===-1?null:m.isRaw===!0?Y.subarray(H,H+=a):GT.parser===void 0?Y.toString("utf8",H,H+=a):GT.parser.array===!0?GT.parser(Y.toString("utf8",H+1,H+=a)):GT.parser(Y.toString("utf8",H,H+=a)),m.isRaw?kS[OS]=m.isRaw===!0?hT:K.value.from?K.value.from(hT,GT):hT:kS[GT.name]=K.value.from?K.value.from(hT,GT):hT;m.forEachFn?m.forEachFn(K.row.from?K.row.from(kS):kS,n):n[cT++]=K.row.from?K.row.from(kS):kS}function ZK(Y){let[H,a]=Y.toString("utf8",5,Y.length-1).split(r.N);if(_T[H]=a,T.parameters[H]!==a)T.parameters[H]=a,U&&U(H,a)}function qK(Y){if(m&&m.options.simple&&m.resolve(gS||n),m=gS=null,n=new Vf,h.cancel(),WS){if(Z){if(!_T.in_hot_standby||!_T.default_transaction_read_only)return aK();else if(rK(Z,_T))return LM()}if(OT)return WS===!0&&(WS=null),uK();WS!==!0&&BM(WS),T.shared.retries=tT=0,WS=null;return}while(j.length&&(m=j.shift())&&(m.active=!0,m.cancelled))FK(T).cancel(m.state,m.cancelled.resolve,m.cancelled.reject);if(m)return;AS.reserved?!AS.reserved.release&&Y[5]===73?Z$?LM():(AS.reserved=null,$(AS)):AS.reserved():Z$?LM():$(AS)}function mK(Y){cT=0;for(let H=Y.length-1;H>0;H--){if(Y[H]===32&&Y[H+1]<58&&n.count===null)n.count=+Y.toString("utf8",H+1,Y.length-1);if(Y[H-1]>=65){n.command=Y.toString("utf8",5,H),n.state=_;break}}if(VM&&(VM(),VM=null),n.command==="BEGIN"&&F!==1&&!AS.reserved)return J$(oT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(m.options.simple)return zA();if(m.cursorFn)n.count&&m.cursorFn(n),TS(e$);m.resolve(n)}function hK(){m.parsing=!1}function zA(){!n.statement&&(n.statement=m.statement),n.columns=m.statement.columns}function vK(Y){let H=Y.readUInt16BE(5);for(let a=0;a<H;++a)!m.statement.types[a]&&(m.statement.types[a]=Y.readUInt32BE(7+a*4));m.prepare&&(HS[m.signature]=m.statement),m.describeFirst&&!m.onlyDescribe&&(TS(dJ(m)),m.describeFirst=!1)}function PK(Y){if(n.command)gS=gS||[n],gS.push(n=new Vf),n.count=null,m.statement.columns=null;let H=Y.readUInt16BE(5),a=7,GT;m.statement.columns=Array(H);for(let hT=0;hT<H;++hT){GT=a;while(Y[a++]!==0);let kS=Y.readUInt32BE(a),OS=Y.readUInt16BE(a+4),q$=Y.readUInt32BE(a+6);m.statement.columns[hT]={name:K.column.from?K.column.from(Y.toString("utf8",GT,a-1)):Y.toString("utf8",GT,a-1),parser:w[q$],table:kS,number:OS,type:q$},a+=18}if(n.statement=m.statement,m.onlyDescribe)return m.resolve(m.statement),TS(e$)}async function nK(Y,H=Y.readUInt32BE(5)){(H===3?cK:H===5?gK:H===10?oK:H===11?tK:H===12?pK:H!==0?Y4:EM)(Y,H)}async function cK(){let Y=await cW();TS(r().p().str(Y).z(1).end())}async function gK(Y){let H="md5"+await JK(Buffer.concat([Buffer.from(await JK(await cW()+W)),Y.subarray(9)]));TS(r().p().str(H).z(1).end())}async function oK(){M$=(await cJ.randomBytes(18)).toString("base64"),r().p().str("SCRAM-SHA-256"+r.N);let Y=r.i;TS(r.inc(4).str("n,,n=*,r="+M$).i32(r.i-Y-4,Y).end())}async function tK(Y){let H=Y.toString("utf8",9).split(",").reduce((OS,q$)=>(OS[q$[0]]=q$.slice(2),OS),{}),a=await cJ.pbkdf2Sync(await cW(),Buffer.from(H.s,"base64"),parseInt(H.i),32,"sha256"),GT=await LW(a,"Client Key"),hT="n=*,r="+M$+",r="+H.r+",s="+H.s+",i="+H.i+",c=biws,r="+H.r;bT=(await LW(await LW(a,"Server Key"),hT)).toString("base64");let kS="c=biws,r="+H.r+",p="+x7(GT,Buffer.from(await LW(await C7(GT),hT))).toString("base64");TS(r().p().str(kS).end())}function pK(Y){if(Y.toString("utf8",9).split(r.N,1)[0].slice(2)===bT)return;J$(oT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),R.destroy()}function cW(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function iK(){if(n.statement=m.statement,n.statement.columns=[],m.onlyDescribe)return m.resolve(m.statement),TS(e$)}function dK(Y){_.pid=Y.readUInt32BE(5),_.secret=Y.readUInt32BE(9)}async function uK(){OT=!1,(await new cS([`
13
44
  select b.oid, b.typarray
14
45
  from pg_catalog.pg_type a
15
46
  left join pg_catalog.pg_type b on b.oid = a.typelem
16
47
  where a.typcategory = 'A'
17
48
  group by b.oid, b.typarray
18
49
  order by b.oid
19
- `],[],VM)).forEach(({oid:_,typarray:r})=>dK(_,r))}function dK(w,_){if(!!T.parsers[_]&&!!T.serializers[_])return;let r=T.parsers[w];T.shared.typeArrayMap[w]=_,T.parsers[_]=(zT)=>s8(zT,r,_),T.parsers[_].array=!0,T.serializers[_]=(zT)=>e8(zT,T.serializers[w],T,_)}function rK(w,_){return w==="read-write"&&_.default_transaction_read_only==="on"||w==="read-only"&&_.default_transaction_read_only==="off"||w==="primary"&&_.in_hot_standby==="on"||w==="standby"&&_.in_hot_standby==="off"||w==="prefer-standby"&&_.in_hot_standby==="off"&&T.host[pT]}function aK(){let w=new oS([`
50
+ `],[],BM)).forEach(({oid:H,typarray:a})=>lK(H,a))}function lK(Y,H){if(!!T.parsers[H]&&!!T.serializers[H])return;let a=T.parsers[Y];T.shared.typeArrayMap[Y]=H,T.parsers[H]=(GT)=>TK(GT,a,H),T.parsers[H].array=!0,T.serializers[H]=(GT)=>sw(GT,T.serializers[Y],T,H)}function rK(Y,H){return Y==="read-write"&&H.default_transaction_read_only==="on"||Y==="read-only"&&H.default_transaction_read_only==="off"||Y==="primary"&&H.in_hot_standby==="on"||Y==="standby"&&H.in_hot_standby==="off"||Y==="prefer-standby"&&H.in_hot_standby==="off"&&T.host[tT]}function aK(){let Y=new cS([`
20
51
  show transaction_read_only;
21
52
  select pg_catalog.pg_is_in_recovery()
22
- `],[],VM,null,{simple:!0});w.resolve=([[_],[r]])=>{fT.default_transaction_read_only=_.transaction_read_only,fT.in_hot_standby=r.pg_is_in_recovery?"on":"off"},w.execute()}function eK(w){m&&(m.cursorFn||m.describeFirst)&&TS(a$);let _=tT.postgres(c1(w));m&&m.retried?F$(m.retried):m&&m.prepared&&LY.has(_.routine)?sK(m,_):F$(_)}function sK(w,_){delete UT[w.signature],w.retried=_,VM(w)}function T4(w){if(!z)return;let _=9;while(w[_++]!==0);z(w.toString("utf8",9,_-1),w.toString("utf8",_,w.length-1))}async function S4(){try{let w=await Promise.resolve(m.cursorFn(P));oT=0,w===zM?TS(O4(m.portal)):(P=new Uf,TS(GA("",m.cursorRows)))}catch(w){TS(a$),m.reject(w)}}function $4(){P.count&&m.cursorFn(P),m.resolve(P)}function f4(){iT=new n1.Writable({autoDestroy:!0,write(w,_,r){O.write(d().d().raw(w).end(),r)},destroy(w,_){_(w),O.write(d().f().str(w+d.N).end()),iT=null},final(w){O.write(d().c().end()),UM=w}}),m.resolve(iT)}function M4(){iT=new n1.Readable({read(){O.resume()}}),m.resolve(iT)}function J4(){iT=new n1.Duplex({autoDestroy:!0,read(){O.resume()},write(w,_,r){O.write(d().d().raw(w).end(),r)},destroy(w,_){_(w),O.write(d().f().str(w+d.N).end()),iT=null},final(w){O.write(d().c().end()),UM=w}}),m.resolve(iT)}function F4(w){iT&&(iT.push(w.subarray(5))||O.pause())}function W4(){iT&&iT.push(null),iT=null}function A4(w){G?G(c1(w)):console.log(c1(w))}function k4(){}function X4(){F$(tT.notSupported("FunctionCallResponse"))}function y4(){F$(tT.notSupported("NegotiateProtocolVersion"))}function K4(w){console.error("Postgres.js : Unknown Message:",w[0])}function w4(w,_){console.error("Postgres.js : Unknown Auth:",_)}function Y4(w,_,r="",zT=""){let vT,AS;return d().B().str(zT+d.N).str(r+d.N).i16(0).i16(w.length),w.forEach((YS,q$)=>{if(YS===null)return d.i32(4294967295);AS=_[q$],w[q$]=YS=AS in T.serializers?T.serializers[AS](YS):""+YS,vT=d.i,d.inc(4).str(YS).i32(d.i-vT-4,vT)}),d.i16(0),d.end()}function OA(w,_,r,zT=""){return d().P().str(zT+d.N).str(w+d.N).i16(_.length),_.forEach((vT,AS)=>d.i32(r[AS]||0)),d.end()}function R4(w,_=""){return d().D().str(w).str(_+d.N).end()}function GA(w="",_=0){return Buffer.concat([d().E().str(w+d.N).i32(_).end(),fK])}function O4(w=""){return Buffer.concat([d().C().str("P").str(w+d.N).end(),d().S().end()])}function G4(){return o||d().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:W,database:X,client_encoding:"UTF8"},T.connection)).filter(([,w])=>w).map(([w,_])=>w+d.N+_).join(d.N)).z(2).end(0)}}function c1(T){let S={},$=5;for(let f=5;f<T.length-1;f++)if(T[f]===0)S[NY[T[$]]]=T.toString("utf8",$+1,f),$=f+1;return S}function MK(T){return PJ.createHash("md5").update(T).digest("hex")}function EW(T,S){return PJ.createHmac("sha256",T).update(S).digest()}function CY(T){return PJ.createHash("sha256").update(T).digest()}function xY(T,S){let $=Math.max(T.length,S.length),f=Buffer.allocUnsafe($);for(let M=0;M<$;M++)f[M]=T[M]^S[M];return f}function o1(T,S){if(S=typeof S==="function"?S():S,!S)return{cancel:HM,start:HM};let $;return{cancel(){$&&(clearTimeout($),$=null)},start(){$&&clearTimeout($),$=setTimeout(f,S*1000,arguments)}};function f(M){T.apply(null,M),$=null}}var FK=()=>{};function t1(T,S){let $=new Map,f="postgresjs_"+Math.random().toString(36).slice(2),M={},J,F,W=!1,A=y.sql=T({...S,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...S.connection,replication:"database"},onclose:async function(){if(W)return;F=null,M.pid=M.secret=void 0,K(await G(A,f,S.publications)),$.forEach((Q)=>Q.forEach(({onsubscribe:E})=>E()))},no_subscribe:!0}),k=A.end,X=A.close;return A.end=async()=>{return W=!0,F&&await new Promise((Q)=>(F.once("close",Q),F.end())),k()},A.close=async()=>{return F&&await new Promise((Q)=>(F.once("close",Q),F.end())),X()},y;async function y(Q,E,B=FK,L=FK){if(Q=bY(Q),!J)J=G(A,f,S.publications);let b={fn:E,onsubscribe:B},C=$.has(Q)?$.get(Q).add(b):$.set(Q,new Set([b])).get(Q),D=()=>{C.delete(b),C.size===0&&$.delete(Q)};return J.then((H)=>{return K(H),B(),F&&F.on("error",L),{unsubscribe:D,state:M,sql:A}})}function K(Q){F=Q.stream,M.pid=Q.state.pid,M.secret=Q.state.secret}async function G(Q,E,B){if(!B)throw new Error("Missing publication names");let L=await Q.unsafe(`CREATE_REPLICATION_SLOT ${E} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[b]=L,C=await Q.unsafe(`START_REPLICATION SLOT ${E} LOGICAL ${b.consistent_point} (proto_version '1', publication_names '${B}')`).writable(),D={lsn:Buffer.concat(b.consistent_point.split("/").map((O)=>Buffer.from(("00000000"+O).slice(-8),"hex")))};return C.on("data",U),C.on("error",H),C.on("close",Q.close),{stream:C,state:L.state};function H(O){console.error("Unexpected error during logical streaming - reconnecting",O)}function U(O){if(O[0]===119)IY(O.subarray(25),D,Q.options.parsers,Z,S.transform);else if(O[0]===107&&O[17])D.lsn=O.subarray(1,9),h()}function Z(O,o){let P=o.relation.schema+"."+o.relation.table;z("*",O,o),z("*:"+P,O,o),o.relation.keys.length&&z("*:"+P+"="+o.relation.keys.map((a)=>O[a.name]),O,o),z(o.command,O,o),z(o.command+":"+P,O,o),o.relation.keys.length&&z(o.command+":"+P+"="+o.relation.keys.map((a)=>O[a.name]),O,o)}function h(){let O=Buffer.alloc(34);O[0]="r".charCodeAt(0),O.fill(D.lsn,1),O.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),C.write(O)}}function z(Q,E,B){$.has(Q)&&$.get(Q).forEach(({fn:L})=>L(E,B,Q))}}function jY(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function IY(T,S,$,f,M){let J=(F,[W,A])=>(F[W.charCodeAt(0)]=A,F);Object.entries({R:(F)=>{let W=1,A=S[F.readUInt32BE(W)]={schema:F.toString("utf8",W+=4,W=F.indexOf(0,W))||"pg_catalog",table:F.toString("utf8",W+1,W=F.indexOf(0,W+1)),columns:Array(F.readUInt16BE(W+=2)),keys:[]};W+=2;let k=0,X;while(W<F.length)X=A.columns[k++]={key:F[W++],name:M.column.from?M.column.from(F.toString("utf8",W,W=F.indexOf(0,W))):F.toString("utf8",W,W=F.indexOf(0,W)),type:F.readUInt32BE(W+=1),parser:$[F.readUInt32BE(W)],atttypmod:F.readUInt32BE(W+=4)},X.key&&A.keys.push(X),W+=4},Y:()=>{},O:()=>{},B:(F)=>{S.date=jY(F.readBigInt64BE(9)),S.lsn=F.subarray(1,9)},I:(F)=>{let W=1,A=S[F.readUInt32BE(W)],{row:k}=QW(F,A.columns,W+=7,M);f(k,{command:"insert",relation:A})},D:(F)=>{let W=1,A=S[F.readUInt32BE(W)];W+=4;let k=F[W]===75;f(k||F[W]===79?QW(F,A.columns,W+=3,M).row:null,{command:"delete",relation:A,key:k})},U:(F)=>{let W=1,A=S[F.readUInt32BE(W)];W+=4;let k=F[W]===75,X=k||F[W]===79?QW(F,A.columns,W+=3,M):null;X&&(W=X.i);let{row:y}=QW(F,A.columns,W+3,M);f(y,{command:"update",relation:A,key:k,old:X&&X.row})},T:()=>{},C:()=>{}}).reduce(J,{})[T[0]](T)}function QW(T,S,$,f){let M,J,F,W=f.raw?new Array(S.length):{};for(let A=0;A<S.length;A++)M=T[$++],J=S[A],F=M===110?null:M===117?void 0:J.parser===void 0?T.toString("utf8",$+4,$+=4+T.readUInt32BE($)):J.parser.array===!0?J.parser(T.toString("utf8",$+5,$+=4+T.readUInt32BE($))):J.parser(T.toString("utf8",$+4,$+=4+T.readUInt32BE($))),f.raw?W[A]=f.raw===!0?F:f.value.from?f.value.from(F,J):F:W[J.name]=f.value.from?f.value.from(F,J):F;return{i:$,row:f.row.from?f.row.from(W):W}}function bY(T){let S=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!S)throw new Error("Malformed subscribe pattern: "+T);let[,$,f,M]=S;return($||"*")+(f?":"+(f.indexOf(".")===-1?"public."+f:f):"")+(M?"="+M:"")}import WK from"stream";function p1(T,S,$=393216){return new Promise(async(f,M)=>{await T.begin(async(J)=>{let F;!S&&([{oid:S}]=await J`select lo_creat(-1) as oid`);let[{fd:W}]=await J`select lo_open(${S}, ${$}) as fd`,A={writable:X,readable:k,close:()=>J`select lo_close(${W})`.then(F),tell:()=>J`select lo_tell64(${W})`,read:(y)=>J`select loread(${W}, ${y}) as data`,write:(y)=>J`select lowrite(${W}, ${y})`,truncate:(y)=>J`select lo_truncate64(${W}, ${y})`,seek:(y,K=0)=>J`select lo_lseek64(${W}, ${y}, ${K})`,size:()=>J`
53
+ `],[],BM,null,{simple:!0});Y.resolve=([[H],[a]])=>{_T.default_transaction_read_only=H.transaction_read_only,_T.in_hot_standby=a.pg_is_in_recovery?"on":"off"},Y.execute()}function eK(Y){m&&(m.cursorFn||m.describeFirst)&&TS(e$);let H=oT.postgres(t1(Y));m&&m.retried?J$(m.retried):m&&m.prepared&&L7.has(H.routine)?sK(m,H):J$(H)}function sK(Y,H){delete HS[Y.signature],Y.retried=H,BM(Y)}function T4(Y){if(!z)return;let H=9;while(Y[H++]!==0);z(Y.toString("utf8",9,H-1),Y.toString("utf8",H,Y.length-1))}async function S4(){try{let Y=await Promise.resolve(m.cursorFn(n));cT=0,Y===_M?TS(R4(m.portal)):(n=new Vf,TS(HA("",m.cursorRows)))}catch(Y){TS(e$),m.reject(Y)}}function $4(){n.count&&m.cursorFn(n),m.resolve(n)}function f4(){pT=new o1.Writable({autoDestroy:!0,write(Y,H,a){R.write(r().d().raw(Y).end(),a)},destroy(Y,H){H(Y),R.write(r().f().str(Y+r.N).end()),pT=null},final(Y){R.write(r().c().end()),VM=Y}}),m.resolve(pT)}function M4(){pT=new o1.Readable({read(){R.resume()}}),m.resolve(pT)}function J4(){pT=new o1.Duplex({autoDestroy:!0,read(){R.resume()},write(Y,H,a){R.write(r().d().raw(Y).end(),a)},destroy(Y,H){H(Y),R.write(r().f().str(Y+r.N).end()),pT=null},final(Y){R.write(r().c().end()),VM=Y}}),m.resolve(pT)}function F4(Y){pT&&(pT.push(Y.subarray(5))||R.pause())}function W4(){pT&&pT.push(null),pT=null}function A4(Y){G?G(t1(Y)):console.log(t1(Y))}function k4(){}function X4(){J$(oT.notSupported("FunctionCallResponse"))}function w4(){J$(oT.notSupported("NegotiateProtocolVersion"))}function K4(Y){console.error("Postgres.js : Unknown Message:",Y[0])}function Y4(Y,H){console.error("Postgres.js : Unknown Auth:",H)}function y4(Y,H,a="",GT=""){let hT,kS;return r().B().str(GT+r.N).str(a+r.N).i16(0).i16(Y.length),Y.forEach((OS,q$)=>{if(OS===null)return r.i32(4294967295);kS=H[q$],Y[q$]=OS=kS in T.serializers?T.serializers[kS](OS):""+OS,hT=r.i,r.inc(4).str(OS).i32(r.i-hT-4,hT)}),r.i16(0),r.end()}function _A(Y,H,a,GT=""){return r().P().str(GT+r.N).str(Y+r.N).i16(H.length),H.forEach((hT,kS)=>r.i32(a[kS]||0)),r.end()}function O4(Y,H=""){return r().D().str(Y).str(H+r.N).end()}function HA(Y="",H=0){return Buffer.concat([r().E().str(Y+r.N).i32(H).end(),MK])}function R4(Y=""){return Buffer.concat([r().C().str("P").str(Y+r.N).end(),r().S().end()])}function G4(){return g||r().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:W,database:X,client_encoding:"UTF8"},T.connection)).filter(([,Y])=>Y).map(([Y,H])=>Y+r.N+H).join(r.N)).z(2).end(0)}}function t1(T){let S={},$=5;for(let f=5;f<T.length-1;f++)if(T[f]===0)S[N7[T[$]]]=T.toString("utf8",$+1,f),$=f+1;return S}function JK(T){return cJ.createHash("md5").update(T).digest("hex")}function LW(T,S){return cJ.createHmac("sha256",T).update(S).digest()}function C7(T){return cJ.createHash("sha256").update(T).digest()}function x7(T,S){let $=Math.max(T.length,S.length),f=Buffer.allocUnsafe($);for(let M=0;M<$;M++)f[M]=T[M]^S[M];return f}function p1(T,S){if(S=typeof S==="function"?S():S,!S)return{cancel:EM,start:EM};let $;return{cancel(){$&&(clearTimeout($),$=null)},start(){$&&clearTimeout($),$=setTimeout(f,S*1000,arguments)}};function f(M){T.apply(null,M),$=null}}var WK=()=>{};function d1(T,S){let $=new Map,f="postgresjs_"+Math.random().toString(36).slice(2),M={},J,F,W=!1,A=w.sql=T({...S,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...S.connection,replication:"database"},onclose:async function(){if(W)return;F=null,M.pid=M.secret=void 0,K(await G(A,f,S.publications)),$.forEach((U)=>U.forEach(({onsubscribe:D})=>D()))},no_subscribe:!0}),k=A.end,X=A.close;return A.end=async()=>{return W=!0,F&&await new Promise((U)=>(F.once("close",U),F.end())),k()},A.close=async()=>{return F&&await new Promise((U)=>(F.once("close",U),F.end())),X()},w;async function w(U,D,B=WK,L=WK){if(U=b7(U),!J)J=G(A,f,S.publications);let Z={fn:D,onsubscribe:B},j=$.has(U)?$.get(U).add(Z):$.set(U,new Set([Z])).get(U),E=()=>{j.delete(Z),j.size===0&&$.delete(U)};return J.then((_)=>{return K(_),B(),F&&F.on("error",L),{unsubscribe:E,state:M,sql:A}})}function K(U){F=U.stream,M.pid=U.state.pid,M.secret=U.state.secret}async function G(U,D,B){if(!B)throw new Error("Missing publication names");let L=await U.unsafe(`CREATE_REPLICATION_SLOT ${D} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[Z]=L,j=await U.unsafe(`START_REPLICATION SLOT ${D} LOGICAL ${Z.consistent_point} (proto_version '1', publication_names '${B}')`).writable(),E={lsn:Buffer.concat(Z.consistent_point.split("/").map((R)=>Buffer.from(("00000000"+R).slice(-8),"hex")))};return j.on("data",Q),j.on("error",_),j.on("close",U.close),{stream:j,state:L.state};function _(R){console.error("Unexpected error during logical streaming - reconnecting",R)}function Q(R){if(R[0]===119)I7(R.subarray(25),E,U.options.parsers,b,S.transform);else if(R[0]===107&&R[17])E.lsn=R.subarray(1,9),h()}function b(R,g){let n=g.relation.schema+"."+g.relation.table;z("*",R,g),z("*:"+n,R,g),g.relation.keys.length&&z("*:"+n+"="+g.relation.keys.map((p)=>R[p.name]),R,g),z(g.command,R,g),z(g.command+":"+n,R,g),g.relation.keys.length&&z(g.command+":"+n+"="+g.relation.keys.map((p)=>R[p.name]),R,g)}function h(){let R=Buffer.alloc(34);R[0]=114,R.fill(E.lsn,1),R.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),j.write(R)}}function z(U,D,B){$.has(U)&&$.get(U).forEach(({fn:L})=>L(D,B,U))}}function j7(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function I7(T,S,$,f,M){let J=(F,[W,A])=>(F[W.charCodeAt(0)]=A,F);Object.entries({R:(F)=>{let W=1,A=S[F.readUInt32BE(W)]={schema:F.toString("utf8",W+=4,W=F.indexOf(0,W))||"pg_catalog",table:F.toString("utf8",W+1,W=F.indexOf(0,W+1)),columns:Array(F.readUInt16BE(W+=2)),keys:[]};W+=2;let k=0,X;while(W<F.length)X=A.columns[k++]={key:F[W++],name:M.column.from?M.column.from(F.toString("utf8",W,W=F.indexOf(0,W))):F.toString("utf8",W,W=F.indexOf(0,W)),type:F.readUInt32BE(W+=1),parser:$[F.readUInt32BE(W)],atttypmod:F.readUInt32BE(W+=4)},X.key&&A.keys.push(X),W+=4},Y:()=>{},O:()=>{},B:(F)=>{S.date=j7(F.readBigInt64BE(9)),S.lsn=F.subarray(1,9)},I:(F)=>{let W=1,A=S[F.readUInt32BE(W)],{row:k}=NW(F,A.columns,W+=7,M);f(k,{command:"insert",relation:A})},D:(F)=>{let W=1,A=S[F.readUInt32BE(W)];W+=4;let k=F[W]===75;f(k||F[W]===79?NW(F,A.columns,W+=3,M).row:null,{command:"delete",relation:A,key:k})},U:(F)=>{let W=1,A=S[F.readUInt32BE(W)];W+=4;let k=F[W]===75,X=k||F[W]===79?NW(F,A.columns,W+=3,M):null;X&&(W=X.i);let{row:w}=NW(F,A.columns,W+3,M);f(w,{command:"update",relation:A,key:k,old:X&&X.row})},T:()=>{},C:()=>{}}).reduce(J,{})[T[0]](T)}function NW(T,S,$,f){let M,J,F,W=f.raw?new Array(S.length):{};for(let A=0;A<S.length;A++)M=T[$++],J=S[A],F=M===110?null:M===117?void 0:J.parser===void 0?T.toString("utf8",$+4,$+=4+T.readUInt32BE($)):J.parser.array===!0?J.parser(T.toString("utf8",$+5,$+=4+T.readUInt32BE($))):J.parser(T.toString("utf8",$+4,$+=4+T.readUInt32BE($))),f.raw?W[A]=f.raw===!0?F:f.value.from?f.value.from(F,J):F:W[J.name]=f.value.from?f.value.from(F,J):F;return{i:$,row:f.row.from?f.row.from(W):W}}function b7(T){let S=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!S)throw new Error("Malformed subscribe pattern: "+T);let[,$,f,M]=S;return($||"*")+(f?":"+(f.indexOf(".")===-1?"public."+f:f):"")+(M?"="+M:"")}import AK from"stream";function u1(T,S,$=393216){return new Promise(async(f,M)=>{await T.begin(async(J)=>{let F;!S&&([{oid:S}]=await J`select lo_creat(-1) as oid`);let[{fd:W}]=await J`select lo_open(${S}, ${$}) as fd`,A={writable:X,readable:k,close:()=>J`select lo_close(${W})`.then(F),tell:()=>J`select lo_tell64(${W})`,read:(w)=>J`select loread(${W}, ${w}) as data`,write:(w)=>J`select lowrite(${W}, ${w})`,truncate:(w)=>J`select lo_truncate64(${W}, ${w})`,seek:(w,K=0)=>J`select lo_lseek64(${W}, ${w}, ${K})`,size:()=>J`
23
54
  select
24
55
  lo_lseek64(${W}, location, 0) as position,
25
56
  seek.size
@@ -29,10 +60,18 @@ var z4=Object.create;var{getPrototypeOf:_4,defineProperty:hW,getOwnPropertyNames
29
60
  tell.location
30
61
  from (select lo_tell64($1) as location) tell
31
62
  ) seek
32
- `};return f(A),new Promise(async(y)=>F=y);async function k({highWaterMark:y=16384,start:K=0,end:G=1/0}={}){let z=G-K;return K&&await A.seek(K),new WK.Readable({highWaterMark:y,async read(Q){let E=Q>z?Q-z:Q;z-=Q;let[{data:B}]=await A.read(E);if(this.push(B),B.length<Q)this.push(null)}})}async function X({highWaterMark:y=16384,start:K=0}={}){return K&&await A.seek(K),new WK.Writable({highWaterMark:y,write(G,z,Q){A.write(G).then(()=>Q(),Q)}})}}).catch(M)})}Object.assign(UW,{PostgresError:_M,toPascal:Ef,pascal:v1,toCamel:Df,camel:h1,toKebab:Qf,kebab:P1,fromPascal:mJ,fromCamel:ZJ,fromKebab:hJ,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var DM=UW;function UW(T,S){let $=mY(T,S),f=$.no_subscribe||t1(UW,{...$}),M=!1,J=qS(),F=qS(),W=qS(),A=qS(),k=qS(),X=qS(),y=qS(),K=qS(),G={connecting:F,reserved:W,closed:A,ended:k,open:X,busy:y,full:K},z=[...Array($.max)].map(()=>g1($,G,{onopen:UT,onend:fT,onclose:VS})),Q=E(Z);return Object.assign(Q,{get parameters(){return $.parameters},largeObject:p1.bind(null,Q),subscribe:f,CLOSE:zM,END:zM,PostgresError:_M,options:$,reserve:b,listen:B,begin:C,close:P,end:o}),Q;function E(N){return N.debug=$.debug,Object.entries($.types).reduce((AT,[VT,oT])=>{return AT[VT]=(bT)=>new Y$(bT,oT.to),AT},p),Object.assign(kT,{types:p,typed:p,unsafe:_T,notify:L,array:U,json:H,file:pT}),kT;function p(AT,VT){return new Y$(AT,VT)}function kT(AT,...VT){return AT&&Array.isArray(AT.raw)?new oS(AT,VT,N,O):typeof AT==="string"&&!VT.length?new vJ($.transform.column.to?$.transform.column.to(AT):AT):new zW(AT,VT)}function _T(AT,VT=[],oT={}){return arguments.length===2&&!Array.isArray(VT)&&(oT=VT,VT=[]),new oS([AT],VT,N,O,{prepare:!1,...oT,simple:"simple"in oT?oT.simple:VT.length===0})}function pT(AT,VT=[],oT={}){return arguments.length===2&&!Array.isArray(VT)&&(oT=VT,VT=[]),new oS([],VT,(CT)=>{ZY.readFile(AT,"utf8",(JS,BT)=>{if(JS)return CT.reject(JS);CT.strings=[BT],N(CT)})},O,{...oT,simple:"simple"in oT?oT.simple:VT.length===0})}}async function B(N,p,kT){let _T={fn:p,onlisten:kT},pT=B.sql||(B.sql=UW({...$,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(B.channels).forEach(([CT,{listeners:JS}])=>{delete B.channels[CT],Promise.all(JS.map((BT)=>B(CT,BT.fn,BT.onlisten).catch(()=>{})))})},onnotify(CT,JS){CT in B.channels&&B.channels[CT].listeners.forEach((BT)=>BT.fn(JS))}})),AT=B.channels||(B.channels={});if(N in AT){AT[N].listeners.push(_T);let CT=await AT[N].result;return _T.onlisten&&_T.onlisten(),{state:CT.state,unlisten:bT}}AT[N]={result:pT`listen ${pT.unsafe('"'+N.replace(/"/g,'""')+'"')}`,listeners:[_T]};let oT=await AT[N].result;return _T.onlisten&&_T.onlisten(),{state:oT.state,unlisten:bT};async function bT(){if(N in AT===!1)return;if(AT[N].listeners=AT[N].listeners.filter((CT)=>CT!==_T),AT[N].listeners.length)return;return delete AT[N],pT`unlisten ${pT.unsafe('"'+N.replace(/"/g,'""')+'"')}`}}async function L(N,p){return await Q`select pg_notify(${N}, ${""+p})`}async function b(){let N=qS(),p=X.length?X.shift():await new Promise((pT)=>{J.push({reserve:pT}),A.length&&MT(A.shift())});D(p,W),p.reserved=()=>N.length?p.execute(N.shift()):D(p,W),p.reserved.release=!0;let kT=E(_T);return kT.release=()=>{p.reserved=null,UT(p)},kT;function _T(pT){p.queue===K?N.push(pT):p.execute(pT)||D(p,K)}}async function C(N,p){!p&&(p=N,N="");let kT=qS(),_T=0,pT,AT=null;try{return await Q.unsafe("begin "+N.replace(/[^a-z ]/ig,""),[],{onexecute:oT}).execute(),await Promise.race([VT(pT,p),new Promise((bT,CT)=>pT.onclose=CT)])}catch(bT){throw bT}async function VT(bT,CT,JS){let BT=E(iT);BT.savepoint=b$,BT.prepare=(xT)=>AT=xT.replace(/[^a-z0-9$-_. ]/gi);let gS,FS;JS&&await BT`savepoint ${BT(JS)}`;try{if(FS=await new Promise((xT,tS)=>{let J$=CT(BT);Promise.resolve(Array.isArray(J$)?Promise.all(J$):J$).then(xT,tS)}),gS)throw gS}catch(xT){throw await(JS?BT`rollback to ${BT(JS)}`:BT`rollback`),xT instanceof _M&&xT.code==="25P02"&&gS||xT}if(!JS)AT?await BT`prepare transaction '${BT.unsafe(AT)}'`:await BT`commit`;return FS;function b$(xT,tS){if(xT&&Array.isArray(xT.raw))return b$((J$)=>J$.apply(J$,arguments));return arguments.length===1&&(tS=xT,xT=null),VT(bT,tS,"s"+_T+++(xT?"_"+xT:""))}function iT(xT){xT.catch((tS)=>gS||(gS=tS)),bT.queue===K?kT.push(xT):bT.execute(xT)||D(bT,K)}}function oT(bT){pT=bT,D(bT,W),bT.reserved=()=>kT.length?bT.execute(kT.shift()):D(bT,W)}}function D(N,p){return N.queue.remove(N),p.push(N),N.queue=p,p===X?N.idleTimer.start():N.idleTimer.cancel(),N}function H(N){return new Y$(N,3802)}function U(N,p){if(!Array.isArray(N))return U(Array.from(arguments));return new Y$(N,p||(N.length?OW(N)||25:0),$.shared.typeArrayMap)}function Z(N){if(M)return N.reject(tT.connection("CONNECTION_ENDED",$,$));if(X.length)return h(X.shift(),N);if(A.length)return MT(A.shift(),N);y.length?h(y.shift(),N):J.push(N)}function h(N,p){return N.execute(p)?D(N,y):D(N,K)}function O(N){return new Promise((p,kT)=>{N.state?N.active?g1($).cancel(N.state,p,kT):N.cancelled={resolve:p,reject:kT}:(J.remove(N),N.cancelled=!0,N.reject(tT.generic("57014","canceling statement due to user request")),p())})}async function o({timeout:N=null}={}){if(M)return M;await 1;let p;return M=Promise.race([new Promise((kT)=>N!==null&&(p=setTimeout(a,N*1000,kT))),Promise.all(z.map((kT)=>kT.end()).concat(B.sql?B.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function P(){await Promise.all(z.map((N)=>N.end()))}async function a(N){await Promise.all(z.map((p)=>p.terminate()));while(J.length)J.shift().reject(tT.connection("CONNECTION_DESTROYED",$));N()}function MT(N,p){return D(N,F),N.connect(p),N}function fT(N){D(N,k)}function UT(N){if(J.length===0)return D(N,X);let p=Math.ceil(J.length/(F.length+1)),kT=!0;while(kT&&J.length&&p-- >0){let _T=J.shift();if(_T.reserve)return _T.reserve(N);kT=N.execute(_T)}kT?D(N,y):D(N,K)}function VS(N,p){D(N,A),N.reserved=null,N.onclose&&(N.onclose(p),N.onclose=null),$.onclose&&$.onclose(N.id),J.length&&MT(N,J.shift())}}function mY(T,S){if(T&&T.shared)return T;let $=process.env,f=(!T||typeof T==="string"?S:T)||{},{url:M,multihost:J}=cY(T),F=[...M.searchParams].reduce((K,[G,z])=>(K[G]=z,K),{}),W=f.hostname||f.host||J||M.hostname||$.PGHOST||"localhost",A=f.port||M.port||$.PGPORT||5432,k=f.user||f.username||M.username||$.PGUSERNAME||$.PGUSER||oY();f.no_prepare&&(f.prepare=!1),F.sslmode&&(F.ssl=F.sslmode,delete F.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),F.sslrootcert==="system"&&(F.ssl="verify-full");let X=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],y={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:PY,max_pipeline:100,backoff:vY,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(W)?W:W.split(",").map((K)=>K.split(":")[0]),port:Array.isArray(A)?A:W.split(",").map((K)=>parseInt(K.split(":")[1]||A)),path:f.path||W.indexOf("/")>-1&&W+"/.s.PGSQL."+A,database:f.database||f.db||(M.pathname||"").slice(1)||$.PGDATABASE||k,user:k,pass:f.pass||f.password||M.password||$.PGPASSWORD||"",...Object.entries(y).reduce((K,[G,z])=>{let Q=G in f?f[G]:(G in F)?F[G]==="disable"||F[G]==="false"?!1:F[G]:$["PG"+G.toUpperCase()]||z;return K[G]=typeof Q==="string"&&X.includes(G)?+Q:Q,K},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries(F).reduce((K,[G,z])=>((G in y)||(K[G]=z),K),{})},types:f.types||{},target_session_attrs:hY(f,M,$),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:nY(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...r8(f.types)}}function hY(T,S,$){let f=T.target_session_attrs||S.searchParams.get("target_session_attrs")||$.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function vY(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function PY(){return 60*(30+Math.random()*30)}function nY(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function cY(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let S=T;S=S.slice(S.indexOf("://")+3).split(/[?/]/)[0],S=decodeURIComponent(S.slice(S.indexOf("@")+1));let $=new URL(T.replace(S,S.split(",")[0]));return{url:{username:decodeURIComponent($.username),password:decodeURIComponent($.password),host:$.host,hostname:$.hostname,port:$.port,pathname:$.pathname,searchParams:$.searchParams},multihost:S.indexOf(",")>-1&&S}}function oY(){try{return qY.userInfo().username}catch(T){return process.env.USERNAME||"runner"}}class VW extends GS{constructor(T,S,$,f){super();this.session=S,this.dialect=$,this.config={table:T,withList:f}}static[Y]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[c.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})};$dynamic(){return this}}class BW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[Y]="PgInsertBuilder";values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let S=T.map(($)=>{let f={},M=this.table[c.Symbol.Columns];for(let J of Object.keys($)){let F=$[J];f[J]=V(F,t)?F:new IS(F,M[J])}return f});return new AK(this.table,S,this.session,this.dialect,this.withList)}}class AK extends GS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={table:T,values:S,withList:M}}static[Y]="PgInsert";config;returning(T=this.config.table[c.Symbol.Columns]){return this.config.returning=nS(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=R`do nothing`;else{let S="";S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let $=T.where?R` where ${T.where}`:void 0;this.config.onConflict=R`(${R.raw(S)})${$} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let S=T.where?R` where ${T.where}`:void 0,$=T.targetWhere?R` where ${T.targetWhere}`:void 0,f=T.setWhere?R` where ${T.setWhere}`:void 0,M=this.dialect.buildUpdateSet(this.config.table,$W(this.config.table,T.set)),J="";return J=Array.isArray(T.target)?T.target.map((F)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(F))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=R`(${R.raw(J)})${$} do update set ${M}${S}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})};$dynamic(){return this}}function gY(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(($)=>$.toLowerCase()).join("_")}function tY(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce(($,f,M)=>{let J=M===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return $+J},"")}function pY(T){return T}class i1{static[Y]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?gY:T==="camelCase"?tY:pY}getColumnCasing(T){if(!T.keyAsName)return T.name;let S=T.table[c.Symbol.Schema]??"public",$=T.table[c.Symbol.OriginalName],f=`${S}.${$}.${T.name}`;if(!this.cache[f])this.cacheTable(T.table);return this.cache[f]}cacheTable(T){let S=T[c.Symbol.Schema]??"public",$=T[c.Symbol.OriginalName],f=`${S}.${$}`;if(!this.cachedTables[f]){for(let M of Object.values(T[c.Symbol.Columns])){let J=`${f}.${M.name}`;this.cache[J]=this.convert(M.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class nJ extends ES{static[Y]="PgViewBase"}class Vf{static[Y]="PgDialect";casing;constructor(T){this.casing=new i1(T?.casing)}async migrate(T,S,$){let f=typeof $==="string"?"__drizzle_migrations":$.migrationsTable??"__drizzle_migrations",M=typeof $==="string"?"drizzle":$.migrationsSchema??"drizzle",J=R`
33
- CREATE TABLE IF NOT EXISTS ${R.identifier(M)}.${R.identifier(f)} (
63
+ `};return f(A),new Promise(async(w)=>F=w);async function k({highWaterMark:w=16384,start:K=0,end:G=1/0}={}){let z=G-K;return K&&await A.seek(K),new AK.Readable({highWaterMark:w,async read(U){let D=U>z?U-z:U;z-=U;let[{data:B}]=await A.read(D);if(this.push(B),B.length<U)this.push(null)}})}async function X({highWaterMark:w=16384,start:K=0}={}){return K&&await A.seek(K),new AK.Writable({highWaterMark:w,write(G,z,U){A.write(G).then(()=>U(),U)}})}}).catch(M)})}Object.assign(CW,{PostgresError:HM,toPascal:Qf,pascal:c1,toCamel:Df,camel:n1,toKebab:Uf,kebab:g1,fromPascal:vJ,fromCamel:hJ,fromKebab:PJ,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var DM=CW;function CW(T,S){let $=m7(T,S),f=$.no_subscribe||d1(CW,{...$}),M=!1,J=ZS(),F=ZS(),W=ZS(),A=ZS(),k=ZS(),X=ZS(),w=ZS(),K=ZS(),G={connecting:F,reserved:W,closed:A,ended:k,open:X,busy:w,full:K},z=[...Array($.max)].map(()=>i1($,G,{onopen:HS,onend:_T,onclose:y$})),U=D(b);return Object.assign(U,{get parameters(){return $.parameters},largeObject:u1.bind(null,U),subscribe:f,CLOSE:_M,END:_M,PostgresError:HM,options:$,reserve:Z,listen:B,begin:j,close:n,end:g}),U;function D(N){return N.debug=$.debug,Object.entries($.types).reduce((FT,[UT,cT])=>{return FT[UT]=(bT)=>new Y$(bT,cT.to),FT},l),Object.assign(RT,{types:l,typed:l,unsafe:jT,notify:L,array:Q,json:_,file:tT}),RT;function l(FT,UT){return new Y$(FT,UT)}function RT(FT,...UT){return FT&&Array.isArray(FT.raw)?new cS(FT,UT,N,R):typeof FT==="string"&&!UT.length?new nJ($.transform.column.to?$.transform.column.to(FT):FT):new QW(FT,UT)}function jT(FT,UT=[],cT={}){return arguments.length===2&&!Array.isArray(UT)&&(cT=UT,UT=[]),new cS([FT],UT,N,R,{prepare:!1,...cT,simple:"simple"in cT?cT.simple:UT.length===0})}function tT(FT,UT=[],cT={}){return arguments.length===2&&!Array.isArray(UT)&&(cT=UT,UT=[]),new cS([],UT,(LT)=>{q7.readFile(FT,"utf8",(FS,VT)=>{if(FS)return LT.reject(FS);LT.strings=[VT],N(LT)})},R,{...cT,simple:"simple"in cT?cT.simple:UT.length===0})}}async function B(N,l,RT){let jT={fn:l,onlisten:RT},tT=B.sql||(B.sql=CW({...$,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(B.channels).forEach(([LT,{listeners:FS}])=>{delete B.channels[LT],Promise.all(FS.map((VT)=>B(LT,VT.fn,VT.onlisten).catch(()=>{})))})},onnotify(LT,FS){LT in B.channels&&B.channels[LT].listeners.forEach((VT)=>VT.fn(FS))}})),FT=B.channels||(B.channels={});if(N in FT){FT[N].listeners.push(jT);let LT=await FT[N].result;return jT.onlisten&&jT.onlisten(),{state:LT.state,unlisten:bT}}FT[N]={result:tT`listen ${tT.unsafe('"'+N.replace(/"/g,'""')+'"')}`,listeners:[jT]};let cT=await FT[N].result;return jT.onlisten&&jT.onlisten(),{state:cT.state,unlisten:bT};async function bT(){if(N in FT===!1)return;if(FT[N].listeners=FT[N].listeners.filter((LT)=>LT!==jT),FT[N].listeners.length)return;return delete FT[N],tT`unlisten ${tT.unsafe('"'+N.replace(/"/g,'""')+'"')}`}}async function L(N,l){return await U`select pg_notify(${N}, ${""+l})`}async function Z(){let N=ZS(),l=X.length?X.shift():await new Promise((tT)=>{J.push({reserve:tT}),A.length&&OT(A.shift())});E(l,W),l.reserved=()=>N.length?l.execute(N.shift()):E(l,W),l.reserved.release=!0;let RT=D(jT);return RT.release=()=>{l.reserved=null,HS(l)},RT;function jT(tT){l.queue===K?N.push(tT):l.execute(tT)||E(l,K)}}async function j(N,l){!l&&(l=N,N="");let RT=ZS(),jT=0,tT,FT=null;try{return await U.unsafe("begin "+N.replace(/[^a-z ]/ig,""),[],{onexecute:cT}).execute(),await Promise.race([UT(tT,l),new Promise((bT,LT)=>tT.onclose=LT)])}catch(bT){throw bT}async function UT(bT,LT,FS){let VT=D(pT);VT.savepoint=Z$,VT.prepare=(NT)=>FT=NT.replace(/[^a-z0-9$-_. ]/gi);let gS,WS;FS&&await VT`savepoint ${VT(FS)}`;try{if(WS=await new Promise((NT,oS)=>{let M$=LT(VT);Promise.resolve(Array.isArray(M$)?Promise.all(M$):M$).then(NT,oS)}),gS)throw gS}catch(NT){throw await(FS?VT`rollback to ${VT(FS)}`:VT`rollback`),NT instanceof HM&&NT.code==="25P02"&&gS||NT}if(!FS)FT?await VT`prepare transaction '${VT.unsafe(FT)}'`:await VT`commit`;return WS;function Z$(NT,oS){if(NT&&Array.isArray(NT.raw))return Z$((M$)=>M$.apply(M$,arguments));return arguments.length===1&&(oS=NT,NT=null),UT(bT,oS,"s"+jT+++(NT?"_"+NT:""))}function pT(NT){NT.catch((oS)=>gS||(gS=oS)),bT.queue===K?RT.push(NT):bT.execute(NT)||E(bT,K)}}function cT(bT){tT=bT,E(bT,W),bT.reserved=()=>RT.length?bT.execute(RT.shift()):E(bT,W)}}function E(N,l){return N.queue.remove(N),l.push(N),N.queue=l,l===X?N.idleTimer.start():N.idleTimer.cancel(),N}function _(N){return new Y$(N,3802)}function Q(N,l){if(!Array.isArray(N))return Q(Array.from(arguments));return new Y$(N,l||(N.length?EW(N)||25:0),$.shared.typeArrayMap)}function b(N){if(M)return N.reject(oT.connection("CONNECTION_ENDED",$,$));if(X.length)return h(X.shift(),N);if(A.length)return OT(A.shift(),N);w.length?h(w.shift(),N):J.push(N)}function h(N,l){return N.execute(l)?E(N,w):E(N,K)}function R(N){return new Promise((l,RT)=>{N.state?N.active?i1($).cancel(N.state,l,RT):N.cancelled={resolve:l,reject:RT}:(J.remove(N),N.cancelled=!0,N.reject(oT.generic("57014","canceling statement due to user request")),l())})}async function g({timeout:N=null}={}){if(M)return M;await 1;let l;return M=Promise.race([new Promise((RT)=>N!==null&&(l=setTimeout(p,N*1000,RT))),Promise.all(z.map((RT)=>RT.end()).concat(B.sql?B.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(l))}async function n(){await Promise.all(z.map((N)=>N.end()))}async function p(N){await Promise.all(z.map((l)=>l.terminate()));while(J.length)J.shift().reject(oT.connection("CONNECTION_DESTROYED",$));N()}function OT(N,l){return E(N,F),N.connect(l),N}function _T(N){E(N,k)}function HS(N){if(J.length===0)return E(N,X);let l=Math.ceil(J.length/(F.length+1)),RT=!0;while(RT&&J.length&&l-- >0){let jT=J.shift();if(jT.reserve)return jT.reserve(N);RT=N.execute(jT)}RT?E(N,w):E(N,K)}function y$(N,l){E(N,A),N.reserved=null,N.onclose&&(N.onclose(l),N.onclose=null),$.onclose&&$.onclose(N.id),J.length&&OT(N,J.shift())}}function m7(T,S){if(T&&T.shared)return T;let $=process.env,f=(!T||typeof T==="string"?S:T)||{},{url:M,multihost:J}=c7(T),F=[...M.searchParams].reduce((K,[G,z])=>(K[G]=z,K),{}),W=f.hostname||f.host||J||M.hostname||$.PGHOST||"localhost",A=f.port||M.port||$.PGPORT||5432,k=f.user||f.username||M.username||$.PGUSERNAME||$.PGUSER||g7();f.no_prepare&&(f.prepare=!1),F.sslmode&&(F.ssl=F.sslmode,delete F.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),F.sslrootcert==="system"&&(F.ssl="verify-full");let X=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],w={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:P7,max_pipeline:100,backoff:v7,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(W)?W:W.split(",").map((K)=>K.split(":")[0]),port:Array.isArray(A)?A:W.split(",").map((K)=>parseInt(K.split(":")[1]||A)),path:f.path||W.indexOf("/")>-1&&W+"/.s.PGSQL."+A,database:f.database||f.db||(M.pathname||"").slice(1)||$.PGDATABASE||k,user:k,pass:f.pass||f.password||M.password||$.PGPASSWORD||"",...Object.entries(w).reduce((K,[G,z])=>{let U=G in f?f[G]:(G in F)?F[G]==="disable"||F[G]==="false"?!1:F[G]:$["PG"+G.toUpperCase()]||z;return K[G]=typeof U==="string"&&X.includes(G)?+U:U,K},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries(F).reduce((K,[G,z])=>((G in w)||(K[G]=z),K),{})},types:f.types||{},target_session_attrs:h7(f,M,$),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:n7(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...aw(f.types)}}function h7(T,S,$){let f=T.target_session_attrs||S.searchParams.get("target_session_attrs")||$.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function v7(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function P7(){return 60*(30+Math.random()*30)}function n7(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function c7(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let S=T;S=S.slice(S.indexOf("://")+3).split(/[?/]/)[0],S=decodeURIComponent(S.slice(S.indexOf("@")+1));let $=new URL(T.replace(S,S.split(",")[0]));return{url:{username:decodeURIComponent($.username),password:decodeURIComponent($.password),host:$.host,hostname:$.hostname,port:$.port,pathname:$.pathname,searchParams:$.searchParams},multihost:S.indexOf(",")>-1&&S}}function g7(){try{return Z7.userInfo().username}catch(T){return process.env.USERNAME||"runner"}}class xW extends zS{constructor(T,S,$,f){super();this.session=S,this.dialect=$,this.config={table:T,withList:f}}static[y]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[v.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};$dynamic(){return this}}function o7(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(($)=>$.toLowerCase()).join("_")}function t7(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce(($,f,M)=>{let J=M===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return $+J},"")}function p7(T){return T}class l1{static[y]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?o7:T==="camelCase"?t7:p7}getColumnCasing(T){if(!T.keyAsName)return T.name;let S=T.table[v.Symbol.Schema]??"public",$=T.table[v.Symbol.OriginalName],f=`${S}.${$}.${T.name}`;if(!this.cache[f])this.cacheTable(T.table);return this.cache[f]}cacheTable(T){let S=T[v.Symbol.Schema]??"public",$=T[v.Symbol.OriginalName],f=`${S}.${$}`;if(!this.cachedTables[f]){for(let M of Object.values(T[v.Symbol.Columns])){let J=`${f}.${M.name}`;this.cache[J]=this.convert(M.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class gJ extends US{static[y]="PgViewBase"}class Bf{static[y]="PgDialect";casing;constructor(T){this.casing=new l1(T?.casing)}async migrate(T,S,$){let f=typeof $==="string"?"__drizzle_migrations":$.migrationsTable??"__drizzle_migrations",M=typeof $==="string"?"drizzle":$.migrationsSchema??"drizzle",J=O`
64
+ CREATE TABLE IF NOT EXISTS ${O.identifier(M)}.${O.identifier(f)} (
34
65
  id SERIAL PRIMARY KEY,
35
66
  hash text NOT NULL,
36
67
  created_at bigint
37
68
  )
38
- `;await S.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(M)}`),await S.execute(J);let W=(await S.all(R`select id, hash, created_at from ${R.identifier(M)}.${R.identifier(f)} order by created_at desc limit 1`))[0];await S.transaction(async(A)=>{for await(let k of T)if(!W||Number(W.created_at)<k.folderMillis){for(let X of k.sql)await A.execute(R.raw(X));await A.execute(R`insert into ${R.identifier(M)}.${R.identifier(f)} ("hash", "created_at") values(${k.hash}, ${k.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`\$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let S=[R`with `];for(let[$,f]of T.entries())if(S.push(R`${R.identifier(f._.alias)} as (${f._.sql})`),$<T.length-1)S.push(R`, `);return S.push(R` `),R.join(S)}buildDeleteQuery({table:T,where:S,returning:$,withList:f}){let M=this.buildWithCTE(f),J=$?R` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,F=S?R` where ${S}`:void 0;return R`${M}delete from ${T}${F}${J}`}buildUpdateSet(T,S){let $=T[c.Symbol.Columns],f=Object.keys($).filter((J)=>S[J]!==void 0||$[J]?.onUpdateFn!==void 0),M=f.length;return R.join(f.flatMap((J,F)=>{let W=$[J],A=S[J]??R.param(W.onUpdateFn(),W),k=R`${R.identifier(this.casing.getColumnCasing(W))} = ${A}`;if(F<M-1)return[k,R.raw(", ")];return[k]}))}buildUpdateQuery({table:T,set:S,where:$,returning:f,withList:M}){let J=this.buildWithCTE(M),F=this.buildUpdateSet(T,S),W=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,A=$?R` where ${$}`:void 0;return R`${J}update ${T} set ${F}${A}${W}`}buildSelection(T,{isSingleTable:S=!1}={}){let $=T.length,f=T.flatMap(({field:M},J)=>{let F=[];if(V(M,t.Aliased)&&M.isSelectionField)F.push(R.identifier(M.fieldAlias));else if(V(M,t.Aliased)||V(M,t)){let W=V(M,t.Aliased)?M.sql:M;if(S)F.push(new t(W.queryChunks.map((A)=>{if(V(A,q))return R.identifier(this.casing.getColumnCasing(A));return A})));else F.push(W);if(V(M,t.Aliased))F.push(R` as ${R.identifier(M.fieldAlias)}`)}else if(V(M,NT))if(S)F.push(R.identifier(this.casing.getColumnCasing(M)));else F.push(M);if(J<$-1)F.push(R`, `);return F});return R.join(f)}buildSelectQuery({withList:T,fields:S,fieldsFlat:$,where:f,having:M,table:J,joins:F,orderBy:W,groupBy:A,limit:k,offset:X,lockingClause:y,distinct:K,setOperators:G}){let z=$??nS(S);for(let MT of z)if(V(MT.field,NT)&&PS(MT.field.table)!==(V(J,fS)?J._.alias:V(J,nJ)?J[hT].name:V(J,t)?void 0:PS(J))&&!((fT)=>F?.some(({alias:UT})=>UT===(fT[c.Symbol.IsAlias]?PS(fT):fT[c.Symbol.BaseName])))(MT.field.table)){let fT=PS(MT.field.table);throw new Error(`Your "${MT.path.join("->")}" field references a column "${fT}"."${MT.field.name}", but the table "${fT}" is not part of the query! Did you forget to join it?`)}let Q=!F||F.length===0,E=this.buildWithCTE(T),B;if(K)B=K===!0?R` distinct`:R` distinct on (${R.join(K.on,R`, `)})`;let L=this.buildSelection(z,{isSingleTable:Q}),b=(()=>{if(V(J,c)&&J[c.Symbol.OriginalName]!==J[c.Symbol.Name]){let MT=R`${R.identifier(J[c.Symbol.OriginalName])}`;if(J[c.Symbol.Schema])MT=R`${R.identifier(J[c.Symbol.Schema])}.${MT}`;return R`${MT} ${R.identifier(J[c.Symbol.Name])}`}return J})(),C=[];if(F)for(let[MT,fT]of F.entries()){if(MT===0)C.push(R` `);let UT=fT.table,VS=fT.lateral?R` lateral`:void 0;if(V(UT,cS)){let N=UT[cS.Symbol.Name],p=UT[cS.Symbol.Schema],kT=UT[cS.Symbol.OriginalName],_T=N===kT?void 0:fT.alias;C.push(R`${R.raw(fT.joinType)} join${VS} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(kT)}${_T&&R` ${R.identifier(_T)}`} on ${fT.on}`)}else if(V(UT,ES)){let N=UT[hT].name,p=UT[hT].schema,kT=UT[hT].originalName,_T=N===kT?void 0:fT.alias;C.push(R`${R.raw(fT.joinType)} join${VS} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(kT)}${_T&&R` ${R.identifier(_T)}`} on ${fT.on}`)}else C.push(R`${R.raw(fT.joinType)} join${VS} ${UT} on ${fT.on}`);if(MT<F.length-1)C.push(R` `)}let D=R.join(C),H=f?R` where ${f}`:void 0,U=M?R` having ${M}`:void 0,Z;if(W&&W.length>0)Z=R` order by ${R.join(W,R`, `)}`;let h;if(A&&A.length>0)h=R` group by ${R.join(A,R`, `)}`;let O=typeof k==="object"||typeof k==="number"&&k>=0?R` limit ${k}`:void 0,o=X?R` offset ${X}`:void 0,P=R.empty();if(y){let MT=R` for ${R.raw(y.strength)}`;if(y.config.of)MT.append(R` of ${R.join(Array.isArray(y.config.of)?y.config.of:[y.config.of],R`, `)}`);if(y.config.noWait)MT.append(R` no wait`);else if(y.config.skipLocked)MT.append(R` skip locked`);P.append(MT)}let a=R`${E}select${B} ${L} from ${b}${D}${H}${h}${U}${Z}${O}${o}${P}`;if(G.length>0)return this.buildSetOperations(a,G);return a}buildSetOperations(T,S){let[$,...f]=S;if(!$)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:$}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:$,rightSelect:f,limit:M,orderBy:J,offset:F}}){let W=R`(${T.getSQL()}) `,A=R`(${f.getSQL()})`,k;if(J&&J.length>0){let G=[];for(let z of J)if(V(z,q))G.push(R.identifier(z.name));else if(V(z,t)){for(let Q=0;Q<z.queryChunks.length;Q++){let E=z.queryChunks[Q];if(V(E,q))z.queryChunks[Q]=R.identifier(E.name)}G.push(R`${z}`)}else G.push(R`${z}`);k=R` order by ${R.join(G,R`, `)} `}let X=typeof M==="object"||typeof M==="number"&&M>=0?R` limit ${M}`:void 0,y=R.raw(`${S} ${$?"all ":""}`),K=F?R` offset ${F}`:void 0;return R`${W}${y}${A}${k}${X}${K}`}buildInsertQuery({table:T,values:S,onConflict:$,returning:f,withList:M}){let J=[],F=T[c.Symbol.Columns],W=Object.entries(F).filter(([G,z])=>!z.shouldDisableInsert()),A=W.map(([,G])=>R.identifier(this.casing.getColumnCasing(G)));for(let[G,z]of S.entries()){let Q=[];for(let[E,B]of W){let L=z[E];if(L===void 0||V(L,IS)&&L.value===void 0)if(B.defaultFn!==void 0){let b=B.defaultFn(),C=V(b,t)?b:R.param(b,B);Q.push(C)}else if(!B.default&&B.onUpdateFn!==void 0){let b=B.onUpdateFn(),C=V(b,t)?b:R.param(b,B);Q.push(C)}else Q.push(R`default`);else Q.push(L)}if(J.push(Q),G<S.length-1)J.push(R`, `)}let k=this.buildWithCTE(M),X=R.join(J),y=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,K=$?R` on conflict ${$}`:void 0;return R`${k}insert into ${T} ${A} values ${X}${K}${y}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:$}){let f=S?R` concurrently`:void 0,M=$?R` with no data`:void 0;return R`refresh materialized view${f} ${T}${M}`}prepareTyping(T){if(V(T,WW)||V(T,FW))return"json";else if(V(T,AW))return"decimal";else if(V(T,kW))return"time";else if(V(T,XW)||V(T,yW))return"timestamp";else if(V(T,fW)||V(T,MW))return"date";else if(V(T,KW))return"uuid";else return"none"}sqlToQuery(T,S){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:S})}buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:f,tableConfig:M,queryConfig:J,tableAlias:F,nestedQueryRelation:W,joinOn:A}){let k=[],X,y,K=[],G,z=[];if(J===!0)k=Object.entries(M.columns).map(([B,L])=>({dbKey:L.name,tsKey:B,field:w$(L,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let E=Object.fromEntries(Object.entries(M.columns).map(([H,U])=>[H,w$(U,F)]));if(J.where){let H=typeof J.where==="function"?J.where(E,h8()):J.where;G=H&&xJ(H,F)}let B=[],L=[];if(J.columns){let H=!1;for(let[U,Z]of Object.entries(J.columns)){if(Z===void 0)continue;if(U in M.columns){if(!H&&Z===!0)H=!0;L.push(U)}}if(L.length>0)L=H?L.filter((U)=>J.columns?.[U]===!0):Object.keys(M.columns).filter((U)=>!L.includes(U))}else L=Object.keys(M.columns);for(let H of L){let U=M.columns[H];B.push({tsKey:H,value:U})}let b=[];if(J.with)b=Object.entries(J.with).filter((H)=>!!H[1]).map(([H,U])=>({tsKey:H,queryConfig:U,relation:M.relations[H]}));let C;if(J.extras){C=typeof J.extras==="function"?J.extras(E,{sql:R}):J.extras;for(let[H,U]of Object.entries(C))B.push({tsKey:H,value:_1(U,F)})}for(let{tsKey:H,value:U}of B)k.push({dbKey:V(U,t.Aliased)?U.fieldAlias:M.columns[H].name,tsKey:H,field:V(U,NT)?w$(U,F):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof J.orderBy==="function"?J.orderBy(E,v8()):J.orderBy??[];if(!Array.isArray(D))D=[D];K=D.map((H)=>{if(V(H,NT))return w$(H,F);return xJ(H,F)}),X=J.limit,y=J.offset;for(let{tsKey:H,queryConfig:U,relation:Z}of b){let h=n8(S,$,Z),O=Hf(Z.referencedTable),o=$[O],P=`${F}_${H}`,a=jJ(...h.fields.map((UT,VS)=>TW(w$(h.references[VS],P),w$(UT,F)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[o],tableConfig:S[o],queryConfig:V(Z,r$)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:P,joinOn:a,nestedQueryRelation:Z}),fT=R`${R.identifier(P)}.${R.identifier("data")}`.as(H);z.push({on:R`true`,table:new fS(MT.sql,{},P),alias:P,joinType:"left",lateral:!0}),k.push({dbKey:H,tsKey:H,field:fT,relationTableTsKey:o,isJson:!0,selection:MT.selection})}}if(k.length===0)throw new sF({message:`No fields selected for table "${M.tsName}" ("${F}")`});let Q;if(G=jJ(A,G),W){let E=R`json_build_array(${R.join(k.map(({field:b,tsKey:C,isJson:D})=>D?R`${R.identifier(`${F}_${C}`)}.${R.identifier("data")}`:V(b,t.Aliased)?b.sql:b),R`, `)})`;if(V(W,qJ))E=R`coalesce(json_agg(${E}${K.length>0?R` order by ${R.join(K,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:E.as("data"),isJson:!0,relationTableTsKey:M.tsName,selection:k}];if(X!==void 0||y!==void 0||K.length>0)Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:X,offset:y,orderBy:K,setOperators:[]}),G=void 0,X=void 0,y=void 0,K=[];else Q=eF(f,F);Q=this.buildSelectQuery({table:V(Q,cS)?Q:new fS(Q,{},F),fields:{},fieldsFlat:B.map(({field:b})=>({path:[],field:V(b,NT)?w$(b,F):b})),joins:z,where:G,limit:X,offset:y,orderBy:K,setOperators:[]})}else Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:k.map(({field:E})=>({path:[],field:V(E,NT)?w$(E,F):E})),joins:z,where:G,limit:X,offset:y,orderBy:K,setOperators:[]});return{tableTsKey:M.tsName,sql:Q,selection:k}}}class US{static[Y]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,S){if(S==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(S===hT)return{...T[hT],selectedFields:new Proxy(T[hT].selectedFields,this)};if(typeof S==="symbol")return T[S];let f=(V(T,fS)?T._.selectedFields:V(T,ES)?T[hT].selectedFields:T)[S];if(V(f,t.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let M=f.clone();return M.isSelectionField=!0,M}if(V(f,t)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${S}" 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(V(f,NT)){if(this.config.alias)return new Proxy(f,new GM(new Proxy(f.table,new CJ(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new US(this.config))}}class l1{static[Y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class zS{static[Y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}from(T){let S=!!this.fields,$;if(this.fields)$=this.fields;else if(V(T,fS))$=Object.fromEntries(Object.keys(T._.selectedFields).map((f)=>[f,T[f]]));else if(V(T,nJ))$=T[hT].selectedFields;else if(V(T,t))$={};else $=c2(T);return new u1({table:T,fields:$,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class kK extends l1{static[Y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:$,session:f,dialect:M,withList:J,distinct:F}){super();this.config={withList:J,table:T,fields:{...S},distinct:F,setOperators:[]},this.isPartialSelect=$,this.session=f,this.dialect=M,this._={selectedFields:S},this.tableName=U1(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,$)=>{let f=this.tableName,M=U1(S);if(typeof M==="string"&&this.config.joins?.some((J)=>J.alias===M))throw new Error(`Alias "${M}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof M==="string"&&!V(S,t)){let J=V(S,fS)?S._.selectedFields:V(S,ES)?S[hT].selectedFields:S[c.Symbol.Columns];this.config.fields[M]=J}}if(typeof $==="function")$=$(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:$,table:S,joinType:T,alias:M}),typeof M==="string")switch(T){case"left":{this.joinsNotNullableMap[M]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!0;break}case"inner":{this.joinsNotNullableMap[M]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,S){return($)=>{let f=typeof $==="function"?$(iY()):$;if(!Q1(this.getSelectedFields(),f.getSelectedFields()))throw new 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:T,isAll:S,rightSelect:f}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(S)?S:[S]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(S)?S:[S];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}else{let S=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,S={}){return this.config.lockingClause={strength:T,config:S},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}as(T){return new Proxy(new fS(this.getSQL(),this.config.fields,T),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new US({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class u1 extends kK{static[Y]="PgSelect";_prepare(T){let{session:S,config:$,dialect:f,joinsNotNullableMap:M}=this;if(!S)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return QT.startActiveSpan("drizzle.prepareQuery",()=>{let J=nS($.fields),F=S.prepareQuery(f.sqlToQuery(this.getSQL()),J,T,!0);return F.joinsNotNullableMap=M,F})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}n2(u1,[GS]);function EM(T,S){return($,f,...M)=>{let J=[f,...M].map((F)=>({type:T,isAll:S,rightSelect:F}));for(let F of J)if(!Q1($.getSelectedFields(),F.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return $.addSetOperators(J)}}var iY=()=>({union:lY,unionAll:uY,intersect:dY,intersectAll:rY,except:aY,exceptAll:eY}),lY=EM("union",!1),uY=EM("union",!0),dY=EM("intersect",!1),rY=EM("intersect",!0),aY=EM("except",!1),eY=EM("except",!0);class d1{static[Y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=V(T,Vf)?T:void 0,this.dialectConfig=V(T,Vf)?void 0:T}$with(T){let S=this;return{as($){if(typeof $==="function")$=$(S);return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...T){let S=this;function $(J){return new zS({fields:J??void 0,session:void 0,dialect:S.getDialect(),withList:T})}function f(J){return new zS({fields:J??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function M(J,F){return new zS({fields:F??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:J}})}return{select:$,selectDistinct:f,selectDistinctOn:M}}select(T){return new zS({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new zS({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,S){return new zS({fields:S??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new Vf(this.dialectConfig);return this.dialect}}class r1 extends GS{constructor(T,S,$){super();this.session=S,this.dialect=$,this.config={view:T}}static[Y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}class LW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[Y]="PgUpdateBuilder";set(T){return new XK(this.table,$W(this.table,T),this.session,this.dialect,this.withList)}}class XK extends GS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={set:S,table:T,withList:M}}static[Y]="PgUpdate";config;where(T){return this.config.where=T,this}returning(T=this.config.table[c.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)}prepare(T){return this._prepare(T)}execute=(T)=>{return this._prepare().execute(T)};$dynamic(){return this}}class cJ extends t{constructor(T){super(cJ.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=cJ.buildCount(T.source,T.filters)}sql;static[Y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,S){return R`(select count(*) from ${T}${R.raw(" where ").if(S)}${S})`}static buildCount(T,S){return R`select count(*) as count from ${T}${R.raw(" where ").if(S)}${S};`}then(T,S){return Promise.resolve(this.session.count(this.sql)).then(T,S)}catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}}class e1{constructor(T,S,$,f,M,J,F){this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F}static[Y]="PgRelationalQueryBuilder";findMany(T){return new a1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new a1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class a1 extends GS{constructor(T,S,$,f,M,J,F,W,A){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F,this.config=W,this.mode=A}static[Y]="PgRelationalQuery";_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:S,builtQuery:$}=this._toSQL();return this.session.prepareQuery($,void 0,T,!0,(f,M)=>{let J=f.map((F)=>wW(this.schema,this.tableConfig,F,S.selection,M));if(this.mode==="first")return J[0];return J})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),S=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:S}}toSQL(){return this._toSQL().builtQuery}execute(){return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class s1 extends GS{constructor(T,S,$,f){super();this.execute=T,this.sql=S,this.query=$,this.mapBatchResult=f}static[Y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,S){return S?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class oJ{constructor(T,S,$){if(this.dialect=T,this.session=S,this._=$?{schema:$.schema,fullSchema:$.fullSchema,tableNamesMap:$.tableNamesMap,session:S}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:S},this.query={},this._.schema)for(let[f,M]of Object.entries(this._.schema))this.query[f]=new e1($.fullSchema,this._.schema,this._.tableNamesMap,$.fullSchema[f],M,T,S)}static[Y]="PgDatabase";query;$with(T){let S=this;return{as($){if(typeof $==="function")$=$(new d1(S.dialect));return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(T,S){return new cJ({source:T,filters:S,session:this.session})}with(...T){let S=this;function $(A){return new zS({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T})}function f(A){return new zS({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function M(A,k){return new zS({fields:k??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:{on:A}})}function J(A){return new LW(A,S.session,S.dialect,T)}function F(A){return new BW(A,S.session,S.dialect,T)}function W(A){return new VW(A,S.session,S.dialect,T)}return{select:$,selectDistinct:f,selectDistinctOn:M,update:J,insert:F,delete:W}}select(T){return new zS({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new zS({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,S){return new zS({fields:S??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new LW(T,this.session,this.dialect)}insert(T){return new BW(T,this.session,this.dialect)}delete(T){return new VW(T,this.session,this.dialect)}refreshMaterializedView(T){return new r1(T,this.session,this.dialect)}execute(T){let S=typeof T==="string"?R.raw(T):T.getSQL(),$=this.dialect.sqlToQuery(S),f=this.session.prepareQuery($,void 0,void 0,!1);return new s1(()=>f.execute(),S,$,(M)=>f.mapResult(M,!0))}transaction(T,S){return this.session.transaction(T,S)}}class yK{constructor(T,S){this.unique=T,this.name=S}static[Y]="PgIndexBuilderOn";on(...T){return new NW(T.map((S)=>{if(V(S,t))return S;S=S;let $=new LJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),$}),this.unique,!1,this.name)}onOnly(...T){return new NW(T.map((S)=>{if(V(S,t))return S;S=S;let $=new LJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=S.defaultConfig,$}),this.unique,!0,this.name)}using(T,...S){return new NW(S.map(($)=>{if(V($,t))return $;$=$;let f=new LJ($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),f}),this.unique,!0,this.name,T)}}class NW{static[Y]="PgIndexBuilder";config;constructor(T,S,$,f,M="btree"){this.config={name:f,columns:T,unique:S,only:$,method:M}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new KK(this.config,T)}}class KK{static[Y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function TA(T){return new yK(!0,T)}class SA{constructor(T){this.query=T}getQuery(){return this.query}mapResult(T,S){return T}static[Y]="PgPreparedQuery";joinsNotNullableMap}class $A{constructor(T){this.dialect=T}static[Y]="PgSession";execute(T){return QT.startActiveSpan("drizzle.operation",()=>{return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).execute()})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T){let S=await this.execute(T);return Number(S[0].count)}}class fA extends oJ{constructor(T,S,$,f=0){super(T,S,$);this.schema=$,this.nestedIndex=f}static[Y]="PgTransaction";rollback(){throw new H1}getTransactionConfigSQL(T){let S=[];if(T.isolationLevel)S.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)S.push(T.accessMode);if(typeof T.deferrable==="boolean")S.push(T.deferrable?"deferrable":"not deferrable");return R.raw(S.join(" "))}setTransaction(T){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(T)}`)}}class wK extends SA{constructor(T,S,$,f,M,J,F){super({sql:S,params:$});this.client=T,this.queryString=S,this.params=$,this.logger=f,this.fields=M,this._isResponseInArrayMode=J,this.customResultMapper=F}static[Y]="PostgresJsPreparedQuery";async execute(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=z1(this.params,T);S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$);let{fields:f,queryString:M,client:J,joinsNotNullableMap:F,customResultMapper:W}=this;if(!f&&!W)return QT.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(M,$)});let A=await QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":M,"drizzle.query.params":JSON.stringify($)}),J.unsafe(M,$).values()});return QT.startActiveSpan("drizzle.mapResponse",()=>{return W?W(A):A.map((k)=>P2(f,k,F))})})}all(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=z1(this.params,T);return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$),QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.client.unsafe(this.queryString,$)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class gJ extends $A{constructor(T,S,$,f={}){super(S);this.client=T,this.schema=$,this.options=f,this.logger=f.logger??new E1}static[Y]="PostgresJsSession";logger;prepareQuery(T,S,$,f,M){return new wK(this.client,T.sql,T.params,this.logger,S,f,M)}query(T,S){return this.logger.logQuery(T,S),this.client.unsafe(T,S).values()}queryObjects(T,S){return this.client.unsafe(T,S)}transaction(T,S){return this.client.begin(async($)=>{let f=new gJ($,this.dialect,this.schema,this.options),M=new MA(this.dialect,f,this.schema);if(S)await M.setTransaction(S);return T(M)})}}class MA extends fA{constructor(T,S,$,f=0){super(T,S,$,f);this.session=S}static[Y]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((S)=>{let $=new gJ(S,this.dialect,this.schema,this.session.options),f=new MA(this.dialect,$,this.schema);return T(f)})}}class YK extends oJ{static[Y]="PostgresJsDatabase"}function QM(T,S={}){let $=(A)=>A;for(let A of["1184","1082","1083","1114"])T.options.parsers[A]=$,T.options.serializers[A]=$;T.options.serializers["114"]=$,T.options.serializers["3802"]=$;let f=new Vf({casing:S.casing}),M;if(S.logger===!0)M=new D1;else if(S.logger!==!1)M=S.logger;let J;if(S.schema){let A=P8(S.schema,c8);J={fullSchema:S.schema,schema:A.tables,tableNamesMap:A.tableNamesMap}}let F=new gJ(T,f,J,{logger:M}),W=new YK(f,F,J);return W.$client=T,W}function CW(...T){if(typeof T[0]==="string"){let S=DM(T[0]);return QM(S,T[1])}if(o2(T[0])){let{connection:S,client:$,...f}=T[0];if($)return QM($,f);if(typeof S==="object"&&S.url!==void 0){let{url:J,...F}=S,W=DM(J,F);return QM(W,f)}let M=DM(S);return QM(M,f)}return QM(T[0],T[1])}((T)=>{function S($){return QM({},$)}T.mock=S})(CW||(CW={}));function RK(T){let S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[H,U]of Object.entries(S))if(U==="")delete S[H]}if(!!T.skipValidation)return S;let M=typeof T.client==="object"?T.client:{},J=typeof T.server==="object"?T.server:{},F=typeof T.shared==="object"?T.shared:{},W=dM(M),A=dM(J),k=dM(F),X=T.isServer??(typeof window==="undefined"||("Deno"in window)),y=W.merge(k),K=A.merge(k).merge(W),G=X?K.safeParse(S):y.safeParse(S),z=T.onValidationError??((H)=>{throw console.error("\u274C Invalid environment variables:",H.flatten().fieldErrors),new Error("Invalid environment variables")}),Q=T.onInvalidAccess??((H)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return z(G.error);let E=(H)=>{if(!T.clientPrefix)return!0;return!H.startsWith(T.clientPrefix)&&!(H in k.shape)},B=(H)=>{return X||!E(H)},L=(H)=>{return H==="__esModule"||H==="$$typeof"},b=(T.extends??[]).reduce((H,U)=>{return Object.assign(H,U)},{}),C=Object.assign(G.data,b);return new Proxy(C,{get(H,U){if(typeof U!=="string")return;if(L(U))return;if(!B(U))return Q(U);return Reflect.get(H,U)}})}var sY="__vite_start_time"in globalThis,T7=typeof window!=="undefined",Xm="vitest"in globalThis,j$=RK({isServer:!sY&&!T7,server:{CI:HT.string().transform((T)=>!0).optional(),POSTGRES_USER:HT.string(),POSTGRES_PASSWORD:HT.string(),POSTGRES_DATABASE:HT.string(),POSTGRES_HOST:HT.string(),POSTGRES_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:HT.union([HT.literal("true"),HT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:HT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:HT.string().transform((T)=>JSON.parse(T)).pipe(HT.array(HT.string())),OPENAI_API_KEY:HT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:HT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:HT.union([HT.literal("true"),HT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var FA={};E4(FA,{users:()=>Bf,userChanges:()=>$7,untrackedUserColumnNames:()=>S7,twoFactorMethod:()=>HK,trackedUserColumnName:()=>_K,trackableUserColumnNames:()=>zK,role:()=>GK,players:()=>JA,passwordResetAttempts:()=>M7,loginHistory:()=>f7,games:()=>xW,banishedIps:()=>jW});function OK(T){return R`lower(${T})`}var GK=dF("role",["admin","user"]),Bf=d$("users",{id:bS().primaryKey().defaultRandom(),username:MS({length:16}).notNull(),email:MS({length:254}).notNull(),hash:MS({length:64}).notNull(),salt:MS({length:36}).notNull(),createdAt:M$({withTimezone:!0}).notNull().defaultNow(),createdIp:MS({length:45}).notNull(),isActive:IJ().notNull().default(!1),verifiedAt:M$({withTimezone:!0}),userRole:GK().default("user")},(T)=>[TA("usernameUniqueIndex").on(OK(T.username)),TA("emailUniqueIndex").on(OK(T.email))]),S7=["id","createdAt","createdIp","isActive","salt","verifiedAt"],zK=["username","email","hash","userRole"],_K=dF("trackedUserColumnName",zK),$7=d$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Bf.id),changedAt:M$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:_K().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),xW=d$("games",{id:bS().primaryKey().defaultRandom()}),JA=d$("players",{userId:bS().notNull().references(()=>Bf.id),gameId:bS().notNull().references(()=>xW.id),score:JW().notNull()},(T)=>[q8({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),f7=d$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Bf.id),loginTime:M$({withTimezone:!0}).notNull().defaultNow(),ipAddress:MS({length:45}).notNull(),userAgent:MS({length:1024}),successful:IJ().notNull().default(!1)}),HK=dF("twoFactorMethod",["email","phone"]),M7=d$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Bf.id),requestedIp:MS({length:45}).notNull(),requestedAt:M$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:M$({withTimezone:!0}),verificationMethod:HK().notNull()}),jW=d$("banishedIps",{ip:MS({length:45}).primaryKey(),reason:MS({length:2048}).notNull(),banishedAt:M$({withTimezone:!0}).notNull().defaultNow(),banishedUntil:M$({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class WA{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(J7.resolve(__dirname,"notify_update.sql"));let T=[PS(Bf),PS(xW),PS(JA)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(S)=>{let $=S.split(","),f=$[0],M=$[1],J=`${f}("${M}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(T=!1,S={host:j$.POSTGRES_HOST,port:j$.POSTGRES_PORT,user:j$.POSTGRES_USER,password:j$.POSTGRES_PASSWORD,database:j$.POSTGRES_DATABASE}){this.options=S,this.sql=DM(S),this.drizzle=CW(this.sql,{schema:FA,logger:T})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new JT);this.observers.get(T).subscribe("SINGLETON",S)}}import*as IW from"fs";import*as DK from"readline";function F7(T){let $=T.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(f,M,J,F,W)=>{let k={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[J];return`${F}-${k}-${M}T${W}`});return new Date($)}async function EK(T,S="/var/log/nginx/access.log",$=new Date){let f=new Map;if(!IW.existsSync(S))return T.error(`Log file not found: ${S}`),f;let M=IW.createReadStream(S),J=DK.createInterface({input:M,crlfDelay:Number.POSITIVE_INFINITY}),F=new Date($.getTime()-3600000);return J.on("line",(W)=>{let A=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,k=W.match(A);if(k?.groups){let X=k.groups.ip,y=k.groups.dateTime,K=F7(y);if(!Number.isNaN(K.getTime())){if(K>=F&&K<=$){let G=f.get(X);if(!G)G=[],f.set(X,G);G.push(W)}}else T.error(`Failed to parse date: ${y}`)}}),new Promise((W,A)=>{J.on("error",(k)=>{A(k)}),J.on("close",()=>{W(f)})})}var W7=["Network security adjudicator, your job is to determine if an IP address should be banned.","The IP address in question created the following logs on our server today:","```nginx.log\n"].join("\n");function QK(T){return W7+T.join("\n\n")}var UK={schema:HT.union([HT.object({shouldBanIp:HT.literal(!1)}),HT.object({shouldBanIp:HT.literal(!0),veryConciseReason:HT.string()})]),fallback:{shouldBanIp:!1}};var w7=[".env","php"];async function VK({generator:T,logFilePath:S,logger:$,now:f}){let M=T.usdBudget,J=new WA({logQuery(C,D){$.info("\uD83D\uDCDD query",C,D)}}),F=await EK($,S,f),W=[],A=T.from(UK),k=0,X=0;for(let[C,D]of F){$.info(`\uD83D\uDD0D ruling on ${C}. logs:`),$.info(D.map((U)=>`\t${U}`).join("\n"));let H=!1;for(let U of w7)if(D.some((Z)=>Z.includes(U))){W.push({ip:C,reason:`Always ban ${U}`}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--always ban ${U}\n`),H=!0;break}if(H)continue;if(T.usdBudget>T.usdFloor){let U=QK(D),Z=await A(U);if(Z.shouldBanIp)W.push({ip:C,reason:Z.veryConciseReason}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--${Z.veryConciseReason}\n`);else X++,$.info(` \uD83D\uDD4A\uFE0F not banning ${C}\n`);k++}else{$.warn("\uD83D\uDCB0 insufficient funds to process all logs"),$.warn(`\uD83D\uDCB0 got through ${k}/${F.size} ips\n`);break}}let y=W.length;if(W.length>0)await J.drizzle.insert(jW).values(W).onConflictDoNothing();let K=[],G=HT.object({lastDay:HT.string()}),z=K7(import.meta.dirname,"tribunal.cache.json");if(k7(z)){let C=await X7(z,"utf-8");try{let D=JSON.parse(C),{lastDay:H}=G.parse(D);if(H){let U=new Date(H);K.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:SW(jW.banishedAt,U)}))}}catch(D){$.error(D)}}try{await Promise.all(K.map((C)=>new Promise((D,H)=>A7(`iptables -D INPUT -s ${C.ip} -j DROP`).on("exit",(U)=>{if(U===0)$.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${C.ip}`),D();else H(new Error(`iptables exited with code ${U}`))}))))}catch(C){if(C instanceof Error)$.error(C.message);else{let D=OM(C);$.error("iptables exited with error",D)}}await y7(z,JSON.stringify({lastDay:f}),"utf-8"),$.info(`\u2728 banned ${y} ips, didn't ban ${X} ips`);let E=M-T.usdBudget,B=E.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),L=M.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),b=Math.round(E/M*100);$.info(`\uD83D\uDCB8 spent ${B}, ${b}% of ${L} budget`)}var I$=new F0;Object.assign(console,I$.logger,{log:I$.logger.info});process.on("SIGINT",()=>{I$.logger.info("\u2757 received SIGINT; exiting gracefully"),bW()});process.on("SIGTERM",()=>{I$.logger.info("\u2757 received SIGTERM; exiting gracefully"),bW()});process.on("exit",()=>{I$.logger.info("\u2757 received exit; exiting gracefully"),bW()});I$.logger.info("\uD83D\uDEEB tribunal worker ready");var Y7=new rX({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:j$.OPENAI_API_KEY,cachingMode:"off",logger:I$.logger});if(j$.OPENAI_API_KEY===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await VK({generator:Y7,logFilePath:"/var/log/nginx/access.log",logger:I$.logger});bW();function bW(){I$.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
69
+ `;await S.execute(O`CREATE SCHEMA IF NOT EXISTS ${O.identifier(M)}`),await S.execute(J);let W=(await S.all(O`select id, hash, created_at from ${O.identifier(M)}.${O.identifier(f)} order by created_at desc limit 1`))[0];await S.transaction(async(A)=>{for await(let k of T)if(!W||Number(W.created_at)<k.folderMillis){for(let X of k.sql)await A.execute(O.raw(X));await A.execute(O`insert into ${O.identifier(M)}.${O.identifier(f)} ("hash", "created_at") values(${k.hash}, ${k.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let S=[O`with `];for(let[$,f]of T.entries())if(S.push(O`${O.identifier(f._.alias)} as (${f._.sql})`),$<T.length-1)S.push(O`, `);return S.push(O` `),O.join(S)}buildDeleteQuery({table:T,where:S,returning:$,withList:f}){let M=this.buildWithCTE(f),J=$?O` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,F=S?O` where ${S}`:void 0;return O`${M}delete from ${T}${F}${J}`}buildUpdateSet(T,S){let $=T[v.Symbol.Columns],f=Object.keys($).filter((J)=>S[J]!==void 0||$[J]?.onUpdateFn!==void 0),M=f.length;return O.join(f.flatMap((J,F)=>{let W=$[J],A=S[J]??O.param(W.onUpdateFn(),W),k=O`${O.identifier(this.casing.getColumnCasing(W))} = ${A}`;if(F<M-1)return[k,O.raw(", ")];return[k]}))}buildUpdateQuery({table:T,set:S,where:$,returning:f,withList:M,from:J,joins:F}){let W=this.buildWithCTE(M),A=T[MS.Symbol.Name],k=T[MS.Symbol.Schema],X=T[MS.Symbol.OriginalName],w=A===X?void 0:A,K=O`${k?O`${O.identifier(k)}.`:void 0}${O.identifier(X)}${w&&O` ${O.identifier(w)}`}`,G=this.buildUpdateSet(T,S),z=J&&O.join([O.raw(" from "),this.buildFromTable(J)]),U=this.buildJoins(F),D=f?O` returning ${this.buildSelection(f,{isSingleTable:!J})}`:void 0,B=$?O` where ${$}`:void 0;return O`${W}update ${K} set ${G}${z}${U}${B}${D}`}buildSelection(T,{isSingleTable:S=!1}={}){let $=T.length,f=T.flatMap(({field:M},J)=>{let F=[];if(V(M,c.Aliased)&&M.isSelectionField)F.push(O.identifier(M.fieldAlias));else if(V(M,c.Aliased)||V(M,c)){let W=V(M,c.Aliased)?M.sql:M;if(S)F.push(new c(W.queryChunks.map((A)=>{if(V(A,q))return O.identifier(this.casing.getColumnCasing(A));return A})));else F.push(W);if(V(M,c.Aliased))F.push(O` as ${O.identifier(M.fieldAlias)}`)}else if(V(M,DT))if(S)F.push(O.identifier(this.casing.getColumnCasing(M)));else F.push(M);if(J<$-1)F.push(O`, `);return F});return O.join(f)}buildJoins(T){if(!T||T.length===0)return;let S=[];for(let[$,f]of T.entries()){if($===0)S.push(O` `);let M=f.table,J=f.lateral?O` lateral`:void 0;if(V(M,MS)){let F=M[MS.Symbol.Name],W=M[MS.Symbol.Schema],A=M[MS.Symbol.OriginalName],k=F===A?void 0:f.alias;S.push(O`${O.raw(f.joinType)} join${J} ${W?O`${O.identifier(W)}.`:void 0}${O.identifier(A)}${k&&O` ${O.identifier(k)}`} on ${f.on}`)}else if(V(M,US)){let F=M[xT].name,W=M[xT].schema,A=M[xT].originalName,k=F===A?void 0:f.alias;S.push(O`${O.raw(f.joinType)} join${J} ${W?O`${O.identifier(W)}.`:void 0}${O.identifier(A)}${k&&O` ${O.identifier(k)}`} on ${f.on}`)}else S.push(O`${O.raw(f.joinType)} join${J} ${M} on ${f.on}`);if($<T.length-1)S.push(O` `)}return O.join(S)}buildFromTable(T){if(V(T,v)&&T[v.Symbol.OriginalName]!==T[v.Symbol.Name]){let S=O`${O.identifier(T[v.Symbol.OriginalName])}`;if(T[v.Symbol.Schema])S=O`${O.identifier(T[v.Symbol.Schema])}.${S}`;return O`${S} ${O.identifier(T[v.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:S,fieldsFlat:$,where:f,having:M,table:J,joins:F,orderBy:W,groupBy:A,limit:k,offset:X,lockingClause:w,distinct:K,setOperators:G}){let z=$??nS(S);for(let p of z)if(V(p.field,DT)&&PS(p.field.table)!==(V(J,aT)?J._.alias:V(J,gJ)?J[xT].name:V(J,c)?void 0:PS(J))&&!((OT)=>F?.some(({alias:_T})=>_T===(OT[v.Symbol.IsAlias]?PS(OT):OT[v.Symbol.BaseName])))(p.field.table)){let OT=PS(p.field.table);throw new Error(`Your "${p.path.join("->")}" field references a column "${OT}"."${p.field.name}", but the table "${OT}" is not part of the query! Did you forget to join it?`)}let U=!F||F.length===0,D=this.buildWithCTE(T),B;if(K)B=K===!0?O` distinct`:O` distinct on (${O.join(K.on,O`, `)})`;let L=this.buildSelection(z,{isSingleTable:U}),Z=this.buildFromTable(J),j=this.buildJoins(F),E=f?O` where ${f}`:void 0,_=M?O` having ${M}`:void 0,Q;if(W&&W.length>0)Q=O` order by ${O.join(W,O`, `)}`;let b;if(A&&A.length>0)b=O` group by ${O.join(A,O`, `)}`;let h=typeof k==="object"||typeof k==="number"&&k>=0?O` limit ${k}`:void 0,R=X?O` offset ${X}`:void 0,g=O.empty();if(w){let p=O` for ${O.raw(w.strength)}`;if(w.config.of)p.append(O` of ${O.join(Array.isArray(w.config.of)?w.config.of:[w.config.of],O`, `)}`);if(w.config.noWait)p.append(O` no wait`);else if(w.config.skipLocked)p.append(O` skip locked`);g.append(p)}let n=O`${D}select${B} ${L} from ${Z}${j}${E}${b}${_}${Q}${h}${R}${g}`;if(G.length>0)return this.buildSetOperations(n,G);return n}buildSetOperations(T,S){let[$,...f]=S;if(!$)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:$}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:$,rightSelect:f,limit:M,orderBy:J,offset:F}}){let W=O`(${T.getSQL()}) `,A=O`(${f.getSQL()})`,k;if(J&&J.length>0){let G=[];for(let z of J)if(V(z,q))G.push(O.identifier(z.name));else if(V(z,c)){for(let U=0;U<z.queryChunks.length;U++){let D=z.queryChunks[U];if(V(D,q))z.queryChunks[U]=O.identifier(D.name)}G.push(O`${z}`)}else G.push(O`${z}`);k=O` order by ${O.join(G,O`, `)} `}let X=typeof M==="object"||typeof M==="number"&&M>=0?O` limit ${M}`:void 0,w=O.raw(`${S} ${$?"all ":""}`),K=F?O` offset ${F}`:void 0;return O`${W}${w}${A}${k}${X}${K}`}buildInsertQuery({table:T,values:S,onConflict:$,returning:f,withList:M,select:J,overridingSystemValue_:F}){let W=[],A=T[v.Symbol.Columns],k=Object.entries(A).filter(([D,B])=>!B.shouldDisableInsert()),X=k.map(([,D])=>O.identifier(this.casing.getColumnCasing(D)));if(J){let D=S;if(V(D,c))W.push(D);else W.push(D.getSQL())}else{let D=S;W.push(O.raw("values "));for(let[B,L]of D.entries()){let Z=[];for(let[j,E]of k){let _=L[j];if(_===void 0||V(_,IS)&&_.value===void 0)if(E.defaultFn!==void 0){let Q=E.defaultFn(),b=V(Q,c)?Q:O.param(Q,E);Z.push(b)}else if(!E.default&&E.onUpdateFn!==void 0){let Q=E.onUpdateFn(),b=V(Q,c)?Q:O.param(Q,E);Z.push(b)}else Z.push(O`default`);else Z.push(_)}if(W.push(Z),B<D.length-1)W.push(O`, `)}}let w=this.buildWithCTE(M),K=O.join(W),G=f?O` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,z=$?O` on conflict ${$}`:void 0,U=F===!0?O`overriding system value `:void 0;return O`${w}insert into ${T} ${X} ${U}${K}${z}${G}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:$}){let f=S?O` concurrently`:void 0,M=$?O` with no data`:void 0;return O`refresh materialized view${f} ${T}${M}`}prepareTyping(T){if(V(T,KW)||V(T,wW))return"json";else if(V(T,YW))return"decimal";else if(V(T,yW))return"time";else if(V(T,OW)||V(T,RW))return"timestamp";else if(V(T,AW)||V(T,kW))return"date";else if(V(T,GW))return"uuid";else return"none"}sqlToQuery(T,S){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:S})}buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:f,tableConfig:M,queryConfig:J,tableAlias:F,nestedQueryRelation:W,joinOn:A}){let k=[],X,w,K=[],G,z=[];if(J===!0)k=Object.entries(M.columns).map(([B,L])=>({dbKey:L.name,tsKey:B,field:K$(L,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let D=Object.fromEntries(Object.entries(M.columns).map(([_,Q])=>[_,K$(Q,F)]));if(J.where){let _=typeof J.where==="function"?J.where(D,vw()):J.where;G=_&&jJ(_,F)}let B=[],L=[];if(J.columns){let _=!1;for(let[Q,b]of Object.entries(J.columns)){if(b===void 0)continue;if(Q in M.columns){if(!_&&b===!0)_=!0;L.push(Q)}}if(L.length>0)L=_?L.filter((Q)=>J.columns?.[Q]===!0):Object.keys(M.columns).filter((Q)=>!L.includes(Q))}else L=Object.keys(M.columns);for(let _ of L){let Q=M.columns[_];B.push({tsKey:_,value:Q})}let Z=[];if(J.with)Z=Object.entries(J.with).filter((_)=>!!_[1]).map(([_,Q])=>({tsKey:_,queryConfig:Q,relation:M.relations[_]}));let j;if(J.extras){j=typeof J.extras==="function"?J.extras(D,{sql:O}):J.extras;for(let[_,Q]of Object.entries(j))B.push({tsKey:_,value:U1(Q,F)})}for(let{tsKey:_,value:Q}of B)k.push({dbKey:V(Q,c.Aliased)?Q.fieldAlias:M.columns[_].name,tsKey:_,field:V(Q,DT)?K$(Q,F):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof J.orderBy==="function"?J.orderBy(D,Pw()):J.orderBy??[];if(!Array.isArray(E))E=[E];K=E.map((_)=>{if(V(_,DT))return K$(_,F);return jJ(_,F)}),X=J.limit,w=J.offset;for(let{tsKey:_,queryConfig:Q,relation:b}of Z){let h=cw(S,$,b),R=Ef(b.referencedTable),g=$[R],n=`${F}_${_}`,p=IJ(...h.fields.map((HS,y$)=>JW(K$(h.references[y$],n),K$(HS,F)))),OT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[g],tableConfig:S[g],queryConfig:V(b,a$)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:n,joinOn:p,nestedQueryRelation:b}),_T=O`${O.identifier(n)}.${O.identifier("data")}`.as(_);z.push({on:O`true`,table:new aT(OT.sql,{},n),alias:n,joinType:"left",lateral:!0}),k.push({dbKey:_,tsKey:_,field:_T,relationTableTsKey:g,isJson:!0,selection:OT.selection})}}if(k.length===0)throw new MW({message:`No fields selected for table "${M.tsName}" ("${F}")`});let U;if(G=IJ(A,G),W){let D=O`json_build_array(${O.join(k.map(({field:Z,tsKey:j,isJson:E})=>E?O`${O.identifier(`${F}_${j}`)}.${O.identifier("data")}`:V(Z,c.Aliased)?Z.sql:Z),O`, `)})`;if(V(W,mJ))D=O`coalesce(json_agg(${D}${K.length>0?O` order by ${O.join(K,O`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:D.as("data"),isJson:!0,relationTableTsKey:M.tsName,selection:k}];if(X!==void 0||w!==void 0||K.length>0)U=this.buildSelectQuery({table:fW(f,F),fields:{},fieldsFlat:[{path:[],field:O.raw("*")}],where:G,limit:X,offset:w,orderBy:K,setOperators:[]}),G=void 0,X=void 0,w=void 0,K=[];else U=fW(f,F);U=this.buildSelectQuery({table:V(U,MS)?U:new aT(U,{},F),fields:{},fieldsFlat:B.map(({field:Z})=>({path:[],field:V(Z,DT)?K$(Z,F):Z})),joins:z,where:G,limit:X,offset:w,orderBy:K,setOperators:[]})}else U=this.buildSelectQuery({table:fW(f,F),fields:{},fieldsFlat:k.map(({field:D})=>({path:[],field:V(D,DT)?K$(D,F):D})),joins:z,where:G,limit:X,offset:w,orderBy:K,setOperators:[]});return{tableTsKey:M.tsName,sql:U,selection:k}}}class JS{static[y]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,S){if(S==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(S===xT)return{...T[xT],selectedFields:new Proxy(T[xT].selectedFields,this)};if(typeof S==="symbol")return T[S];let f=(V(T,aT)?T._.selectedFields:V(T,US)?T[xT].selectedFields:T)[S];if(V(f,c.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let M=f.clone();return M.isSelectionField=!0,M}if(V(f,c)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${S}" 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(V(f,DT)){if(this.config.alias)return new Proxy(f,new zM(new Proxy(f.table,new xJ(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new JS(this.config))}}class r1{static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class _S{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let S=!!this.fields,$;if(this.fields)$=this.fields;else if(V(T,aT))$=Object.fromEntries(Object.keys(T._.selectedFields).map((f)=>[f,T[f]]));else if(V(T,gJ))$=T[xT].selectedFields;else if(V(T,c))$={};else $=g2(T);return new a1({table:T,fields:$,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class kK extends r1{static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:$,session:f,dialect:M,withList:J,distinct:F}){super();this.config={withList:J,table:T,fields:{...S},distinct:F,setOperators:[]},this.isPartialSelect=$,this.session=f,this.dialect=M,this._={selectedFields:S},this.tableName=x$(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,$)=>{let f=this.tableName,M=x$(S);if(typeof M==="string"&&this.config.joins?.some((J)=>J.alias===M))throw new Error(`Alias "${M}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof M==="string"&&!V(S,c)){let J=V(S,aT)?S._.selectedFields:V(S,US)?S[xT].selectedFields:S[v.Symbol.Columns];this.config.fields[M]=J}}if(typeof $==="function")$=$(new Proxy(this.config.fields,new JS({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:$,table:S,joinType:T,alias:M}),typeof M==="string")switch(T){case"left":{this.joinsNotNullableMap[M]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!0;break}case"inner":{this.joinsNotNullableMap[M]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,S){return($)=>{let f=typeof $==="function"?$(i7()):$;if(!bJ(this.getSelectedFields(),f.getSelectedFields()))throw new 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:T,isAll:S,rightSelect:f}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new JS({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new JS({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new JS({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(S)?S:[S]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new JS({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(S)?S:[S];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}else{let S=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,S={}){return this.config.lockingClause={strength:T,config:S},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}as(T){return new Proxy(new aT(this.getSQL(),this.config.fields,T),new JS({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new JS({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class a1 extends kK{static[y]="PgSelect";_prepare(T){let{session:S,config:$,dialect:f,joinsNotNullableMap:M,authToken:J}=this;if(!S)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return QT.startActiveSpan("drizzle.prepareQuery",()=>{let F=nS($.fields),W=S.prepareQuery(f.sqlToQuery(this.getSQL()),F,T,!0);return W.joinsNotNullableMap=M,W.setToken(J)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}c2(a1,[zS]);function QM(T,S){return($,f,...M)=>{let J=[f,...M].map((F)=>({type:T,isAll:S,rightSelect:F}));for(let F of J)if(!bJ($.getSelectedFields(),F.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return $.addSetOperators(J)}}var i7=()=>({union:d7,unionAll:u7,intersect:l7,intersectAll:r7,except:a7,exceptAll:e7}),d7=QM("union",!1),u7=QM("union",!0),l7=QM("intersect",!1),r7=QM("intersect",!0),a7=QM("except",!1),e7=QM("except",!0);class oJ{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=V(T,Bf)?T:void 0,this.dialectConfig=V(T,Bf)?void 0:T}$with(T){let S=this;return{as($){if(typeof $==="function")$=$(S);return new Proxy(new CJ($.getSQL(),$.getSelectedFields(),T,!0),new JS({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...T){let S=this;function $(J){return new _S({fields:J??void 0,session:void 0,dialect:S.getDialect(),withList:T})}function f(J){return new _S({fields:J??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function M(J,F){return new _S({fields:F??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:J}})}return{select:$,selectDistinct:f,selectDistinctOn:M}}select(T){return new _S({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new _S({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,S){return new _S({fields:S??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new Bf(this.dialectConfig);return this.dialect}}class jW{constructor(T,S,$,f,M){this.table=T,this.session=S,this.dialect=$,this.withList=f,this.overridingSystemValue_=M}static[y]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let S=T.map(($)=>{let f={},M=this.table[v.Symbol.Columns];for(let J of Object.keys($)){let F=$[J];f[J]=V(F,c)?F:new IS(F,M[J])}return f});return new e1(this.table,S,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let S=typeof T==="function"?T(new oJ):T;if(!V(S,c)&&!bJ(this.table[TW],S._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new e1(this.table,S,this.session,this.dialect,this.withList,!0)}}class e1 extends zS{constructor(T,S,$,f,M,J,F){super();this.session=$,this.dialect=f,this.config={table:T,values:S,withList:M,select:J,overridingSystemValue_:F}}static[y]="PgInsert";config;returning(T=this.config.table[v.Symbol.Columns]){return this.config.returning=nS(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=O`do nothing`;else{let S="";S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let $=T.where?O` where ${T.where}`:void 0;this.config.onConflict=O`(${O.raw(S)})${$} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let S=T.where?O` where ${T.where}`:void 0,$=T.targetWhere?O` where ${T.targetWhere}`:void 0,f=T.setWhere?O` where ${T.setWhere}`:void 0,M=this.dialect.buildUpdateSet(this.config.table,WW(this.config.table,T.set)),J="";return J=Array.isArray(T.target)?T.target.map((F)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(F))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=O`(${O.raw(J)})${$} do update set ${M}${S}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};$dynamic(){return this}}class s1 extends zS{constructor(T,S,$){super();this.session=S,this.dialect=$,this.config={view:T}}static[y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class IW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[y]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new XK(this.table,WW(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class XK extends zS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={set:S,table:T,withList:M,joins:[]},this.tableName=x$(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[y]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let S=x$(T);if(typeof S==="string")this.joinsNotNullableMap[S]=!0;return this.config.from=T,this}getTableLikeFields(T){if(V(T,MS))return T[v.Symbol.Columns];else if(V(T,aT))return T._.selectedFields;return T[xT].selectedFields}createJoin(T){return(S,$)=>{let f=x$(S);if(typeof f==="string"&&this.config.joins.some((M)=>M.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof $==="function"){let M=this.config.from&&!V(this.config.from,c)?this.getTableLikeFields(this.config.from):void 0;$=$(new Proxy(this.config.table[v.Symbol.Columns],new JS({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),M&&new Proxy(M,new JS({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:$,table:S,joinType:T,alias:f}),typeof f==="string")switch(T){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([M])=>[M,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([M])=>[M,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[v.Symbol.Columns]),this.config.from){let S=x$(this.config.from);if(typeof S==="string"&&this.config.from&&!V(this.config.from,c)){let $=this.getTableLikeFields(this.config.from);T[S]=$}for(let $ of this.config.joins){let f=x$($.table);if(typeof f==="string"&&!V($.table,c)){let M=this.getTableLikeFields($.table);T[f]=M}}}}return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){let S=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return S.joinsNotNullableMap=this.joinsNotNullableMap,S}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};$dynamic(){return this}}class tJ extends c{constructor(T){super(tJ.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=tJ.buildCount(T.source,T.filters)}sql;token;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,S){return O`(select count(*) from ${T}${O.raw(" where ").if(S)}${S})`}static buildCount(T,S){return O`select count(*) as count from ${T}${O.raw(" where ").if(S)}${S};`}setToken(T){return this.token=T,this}then(T,S){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,S)}catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}}class SA{constructor(T,S,$,f,M,J,F){this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F}static[y]="PgRelationalQueryBuilder";findMany(T){return new TA(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new TA(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class TA extends zS{constructor(T,S,$,f,M,J,F,W,A){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F,this.config=W,this.mode=A}static[y]="PgRelationalQuery";_prepare(T){return QT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:S,builtQuery:$}=this._toSQL();return this.session.prepareQuery($,void 0,T,!0,(f,M)=>{let J=f.map((F)=>zW(this.schema,this.tableConfig,F,S.selection,M));if(this.mode==="first")return J[0];return J})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),S=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:S}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class $A extends zS{constructor(T,S,$,f){super();this.execute=T,this.sql=S,this.query=$,this.mapBatchResult=f}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,S){return S?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class pJ{constructor(T,S,$){if(this.dialect=T,this.session=S,this._=$?{schema:$.schema,fullSchema:$.fullSchema,tableNamesMap:$.tableNamesMap,session:S}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:S},this.query={},this._.schema)for(let[f,M]of Object.entries(this._.schema))this.query[f]=new SA($.fullSchema,this._.schema,this._.tableNamesMap,$.fullSchema[f],M,T,S)}static[y]="PgDatabase";query;$with(T){let S=this;return{as($){if(typeof $==="function")$=$(new oJ(S.dialect));return new Proxy(new CJ($.getSQL(),$.getSelectedFields(),T,!0),new JS({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(T,S){return new tJ({source:T,filters:S,session:this.session})}with(...T){let S=this;function $(A){return new _S({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T})}function f(A){return new _S({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function M(A,k){return new _S({fields:k??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:{on:A}})}function J(A){return new IW(A,S.session,S.dialect,T)}function F(A){return new jW(A,S.session,S.dialect,T)}function W(A){return new xW(A,S.session,S.dialect,T)}return{select:$,selectDistinct:f,selectDistinctOn:M,update:J,insert:F,delete:W}}select(T){return new _S({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new _S({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,S){return new _S({fields:S??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new IW(T,this.session,this.dialect)}insert(T){return new jW(T,this.session,this.dialect)}delete(T){return new xW(T,this.session,this.dialect)}refreshMaterializedView(T){return new s1(T,this.session,this.dialect)}authToken;execute(T){let S=typeof T==="string"?O.raw(T):T.getSQL(),$=this.dialect.sqlToQuery(S),f=this.session.prepareQuery($,void 0,void 0,!1);return new $A(()=>f.execute(void 0,this.authToken),S,$,(M)=>f.mapResult(M,!0))}transaction(T,S){return this.session.transaction(T,S)}}class wK{constructor(T,S){this.unique=T,this.name=S}static[y]="PgIndexBuilderOn";on(...T){return new bW(T.map((S)=>{if(V(S,c))return S;S=S;let $=new NJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),$}),this.unique,!1,this.name)}onOnly(...T){return new bW(T.map((S)=>{if(V(S,c))return S;S=S;let $=new NJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=S.defaultConfig,$}),this.unique,!0,this.name)}using(T,...S){return new bW(S.map(($)=>{if(V($,c))return $;$=$;let f=new NJ($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),f}),this.unique,!0,this.name,T)}}class bW{static[y]="PgIndexBuilder";config;constructor(T,S,$,f,M="btree"){this.config={name:f,columns:T,unique:S,only:$,method:M}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new KK(this.config,T)}}class KK{static[y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function fA(T){return new wK(!0,T)}class MA{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,S){return T}setToken(T){return this.authToken=T,this}static[y]="PgPreparedQuery";joinsNotNullableMap}class JA{constructor(T){this.dialect=T}static[y]="PgSession";execute(T,S){return QT.startActiveSpan("drizzle.operation",()=>{return QT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(S).execute(void 0,S)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,S){let $=await this.execute(T,S);return Number($[0].count)}}class FA extends pJ{constructor(T,S,$,f=0){super(T,S,$);this.schema=$,this.nestedIndex=f}static[y]="PgTransaction";rollback(){throw new V1}getTransactionConfigSQL(T){let S=[];if(T.isolationLevel)S.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)S.push(T.accessMode);if(typeof T.deferrable==="boolean")S.push(T.deferrable?"deferrable":"not deferrable");return O.raw(S.join(" "))}setTransaction(T){return this.session.execute(O`set transaction ${this.getTransactionConfigSQL(T)}`)}}class YK extends MA{constructor(T,S,$,f,M,J,F){super({sql:S,params:$});this.client=T,this.queryString=S,this.params=$,this.logger=f,this.fields=M,this._isResponseInArrayMode=J,this.customResultMapper=F}static[y]="PostgresJsPreparedQuery";async execute(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=Q1(this.params,T);S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$);let{fields:f,queryString:M,client:J,joinsNotNullableMap:F,customResultMapper:W}=this;if(!f&&!W)return QT.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(M,$)});let A=await QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":M,"drizzle.query.params":JSON.stringify($)}),J.unsafe(M,$).values()});return QT.startActiveSpan("drizzle.mapResponse",()=>{return W?W(A):A.map((k)=>n2(f,k,F))})})}all(T={}){return QT.startActiveSpan("drizzle.execute",async(S)=>{let $=Q1(this.params,T);return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$),QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.client.unsafe(this.queryString,$)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class iJ extends JA{constructor(T,S,$,f={}){super(S);this.client=T,this.schema=$,this.options=f,this.logger=f.logger??new L1}static[y]="PostgresJsSession";logger;prepareQuery(T,S,$,f,M){return new YK(this.client,T.sql,T.params,this.logger,S,f,M)}query(T,S){return this.logger.logQuery(T,S),this.client.unsafe(T,S).values()}queryObjects(T,S){return this.client.unsafe(T,S)}transaction(T,S){return this.client.begin(async($)=>{let f=new iJ($,this.dialect,this.schema,this.options),M=new WA(this.dialect,f,this.schema);if(S)await M.setTransaction(S);return T(M)})}}class WA extends FA{constructor(T,S,$,f=0){super(T,S,$,f);this.session=S}static[y]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((S)=>{let $=new iJ(S,this.dialect,this.schema,this.session.options),f=new WA(this.dialect,$,this.schema);return T(f)})}}class yK extends pJ{static[y]="PostgresJsDatabase"}function UM(T,S={}){let $=(A)=>A;for(let A of["1184","1082","1083","1114"])T.options.parsers[A]=$,T.options.serializers[A]=$;T.options.serializers["114"]=$,T.options.serializers["3802"]=$;let f=new Bf({casing:S.casing}),M;if(S.logger===!0)M=new B1;else if(S.logger!==!1)M=S.logger;let J;if(S.schema){let A=nw(S.schema,gw);J={fullSchema:S.schema,schema:A.tables,tableNamesMap:A.tableNamesMap}}let F=new iJ(T,f,J,{logger:M}),W=new yK(f,F,J);return W.$client=T,W}function ZW(...T){if(typeof T[0]==="string"){let S=DM(T[0]);return UM(S,T[1])}if(o2(T[0])){let{connection:S,client:$,...f}=T[0];if($)return UM($,f);if(typeof S==="object"&&S.url!==void 0){let{url:J,...F}=S,W=DM(J,F);return UM(W,f)}let M=DM(S);return UM(M,f)}return UM(T[0],T[1])}((T)=>{function S($){return UM({},$)}T.mock=S})(ZW||(ZW={}));function OK(T){let S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[_,Q]of Object.entries(S))if(Q==="")delete S[_]}if(!!T.skipValidation)return S;let M=typeof T.client==="object"?T.client:{},J=typeof T.server==="object"?T.server:{},F=typeof T.shared==="object"?T.shared:{},W=rM(M),A=rM(J),k=rM(F),X=T.isServer??(typeof window==="undefined"||("Deno"in window)),w=W.merge(k),K=A.merge(k).merge(W),G=X?K.safeParse(S):w.safeParse(S),z=T.onValidationError??((_)=>{throw console.error("\u274C Invalid environment variables:",_.flatten().fieldErrors),new Error("Invalid environment variables")}),U=T.onInvalidAccess??((_)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return z(G.error);let D=(_)=>{if(!T.clientPrefix)return!0;return!_.startsWith(T.clientPrefix)&&!(_ in k.shape)},B=(_)=>{return X||!D(_)},L=(_)=>{return _==="__esModule"||_==="$$typeof"},Z=(T.extends??[]).reduce((_,Q)=>{return Object.assign(_,Q)},{}),j=Object.assign(G.data,Z);return new Proxy(j,{get(_,Q){if(typeof Q!=="string")return;if(L(Q))return;if(!B(Q))return U(Q);return Reflect.get(_,Q)}})}var s7="__vite_start_time"in globalThis,Ty=typeof window!=="undefined",Rm="vitest"in globalThis,I$=OK({isServer:!s7&&!Ty,server:{CI:zT.string().transform((T)=>!0).optional(),POSTGRES_USER:zT.string(),POSTGRES_PASSWORD:zT.string(),POSTGRES_DATABASE:zT.string(),POSTGRES_HOST:zT.string(),POSTGRES_PORT:zT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:zT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:zT.union([zT.literal("true"),zT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:zT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:zT.string().transform((T)=>JSON.parse(T)).pipe(zT.array(zT.string())),OPENAI_API_KEY:zT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:zT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:zT.union([zT.literal("true"),zT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var kA={};D4(kA,{users:()=>Lf,userChanges:()=>$y,untrackedUserColumnNames:()=>Sy,twoFactorMethod:()=>HK,trackedUserColumnName:()=>_K,trackableUserColumnNames:()=>zK,role:()=>GK,players:()=>AA,passwordResetAttempts:()=>My,loginHistory:()=>fy,games:()=>qW,banishedIps:()=>mW});function RK(T){return O`lower(${T})`}var GK=eF("role",["admin","user"]),Lf=r$("users",{id:bS().primaryKey().defaultRandom(),username:fS({length:16}).notNull(),email:fS({length:254}).notNull(),hash:fS({length:64}).notNull(),salt:fS({length:36}).notNull(),createdAt:f$({withTimezone:!0}).notNull().defaultNow(),createdIp:fS({length:45}).notNull(),isActive:ZJ().notNull().default(!1),verifiedAt:f$({withTimezone:!0}),userRole:GK().default("user")},(T)=>[fA("usernameUniqueIndex").on(RK(T.username)),fA("emailUniqueIndex").on(RK(T.email))]),Sy=["id","createdAt","createdIp","isActive","salt","verifiedAt"],zK=["username","email","hash","userRole"],_K=eF("trackedUserColumnName",zK),$y=r$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Lf.id),changedAt:f$({withTimezone:!0}).notNull().defaultNow(),changedIp:fS({length:45}).notNull(),changedColumn:_K().notNull(),oldValue:fS({length:255}),newValue:fS({length:255})}),qW=r$("games",{id:bS().primaryKey().defaultRandom()}),AA=r$("players",{userId:bS().notNull().references(()=>Lf.id),gameId:bS().notNull().references(()=>qW.id),score:XW().notNull()},(T)=>[qw({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),fy=r$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Lf.id),loginTime:f$({withTimezone:!0}).notNull().defaultNow(),ipAddress:fS({length:45}).notNull(),userAgent:fS({length:1024}),successful:ZJ().notNull().default(!1)}),HK=eF("twoFactorMethod",["email","phone"]),My=r$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Lf.id),requestedIp:fS({length:45}).notNull(),requestedAt:f$({withTimezone:!0}).notNull().defaultNow(),succeededIp:fS({length:45}),succeededAt:f$({withTimezone:!0}),verificationMethod:HK().notNull()}),mW=r$("banishedIps",{ip:fS({length:45}).primaryKey(),reason:fS({length:2048}).notNull(),banishedAt:f$({withTimezone:!0}).notNull().defaultNow(),banishedUntil:f$({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class XA{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Jy.resolve(__dirname,"notify_update.sql"));let T=[PS(Lf),PS(qW),PS(AA)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(S)=>{let $=S.split(","),f=$[0],M=$[1],J=`${f}("${M}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(T=!1,S={host:I$.POSTGRES_HOST,port:I$.POSTGRES_PORT,user:I$.POSTGRES_USER,password:I$.POSTGRES_PASSWORD,database:I$.POSTGRES_DATABASE}){this.options=S,this.sql=DM(S),this.drizzle=ZW(this.sql,{schema:kA,logger:T})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new fT);this.observers.get(T).subscribe("SINGLETON",S)}}import*as hW from"fs";import*as EK from"readline";function Fy(T){let $=T.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(f,M,J,F,W)=>{let k={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[J];return`${F}-${k}-${M}T${W}`});return new Date($)}async function DK(T,S="/var/log/nginx/access.log",$=new Date){let f=new Map;if(!hW.existsSync(S))return T.error(`Log file not found: ${S}`),f;let M=hW.createReadStream(S),J=EK.createInterface({input:M,crlfDelay:Number.POSITIVE_INFINITY}),F=new Date($.getTime()-3600000);return J.on("line",(W)=>{let A=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,k=W.match(A);if(k?.groups){let X=k.groups.ip,w=k.groups.dateTime,K=Fy(w);if(!Number.isNaN(K.getTime())){if(K>=F&&K<=$){let G=f.get(X);if(!G)G=[],f.set(X,G);G.push(W)}}else T.error(`Failed to parse date: ${w}`)}}),new Promise((W,A)=>{J.on("error",(k)=>{A(k)}),J.on("close",()=>{W(f)})})}var Wy=["Network security adjudicator, your job is to determine if an IP address should be banned.","The IP address in question created the following logs on our server today:","```nginx.log\n"].join(`
70
+ `);function QK(T){return Wy+T.join(`
71
+
72
+ `)}var UK={schema:zT.union([zT.object({shouldBanIp:zT.literal(!1)}),zT.object({shouldBanIp:zT.literal(!0),veryConciseReason:zT.string()})]),fallback:{shouldBanIp:!1}};var Yy=[".env","php"];async function VK({generator:T,logFilePath:S,logger:$,now:f}){let M=T.usdBudget,J=new XA({logQuery(j,E){$.info("\uD83D\uDCDD query",j,E)}}),F=await DK($,S,f),W=[],A=T.from(UK),k=0,X=0;for(let[j,E]of F){$.info(`\uD83D\uDD0D ruling on ${j}. logs:`),$.info(E.map((Q)=>`\t${Q}`).join(`
73
+ `));let _=!1;for(let Q of Yy)if(E.some((b)=>b.includes(Q))){W.push({ip:j,reason:`Always ban ${Q}`}),$.info(`\t\uD83E\uDDD1\u200D\u2696\uFE0F banning ${j}--always ban ${Q}
74
+ `),_=!0;break}if(_)continue;if(T.usdBudget>T.usdMinimum){let Q=QK(E),b=await A(Q);if(b.shouldBanIp)W.push({ip:j,reason:b.veryConciseReason}),$.info(`\t\uD83E\uDDD1\u200D\u2696\uFE0F banning ${j}--${b.veryConciseReason}
75
+ `);else X++,$.info(`\t\uD83D\uDD4A\uFE0F not banning ${j}
76
+ `);k++}else{$.warn("\uD83D\uDCB0 insufficient funds to process all logs"),$.warn(`\uD83D\uDCB0 got through ${k}/${F.size} ips
77
+ `);break}}let w=W.length;if(W.length>0)await J.drizzle.insert(mW).values(W).onConflictDoNothing();let K=[],G=zT.object({lastDay:zT.string()}),z=Ky(import.meta.dirname,"tribunal.cache.json");if(ky(z)){let j=await Xy(z,"utf-8");try{let E=JSON.parse(j),{lastDay:_}=G.parse(E);if(_){let Q=new Date(_);K.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:FW(mW.banishedAt,Q)}))}}catch(E){$.error(E)}}try{await Promise.all(K.map((j)=>new Promise((E,_)=>Ay(`iptables -D INPUT -s ${j.ip} -j DROP`).on("exit",(Q)=>{if(Q===0)$.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${j.ip}`),E();else _(new Error(`iptables exited with code ${Q}`))}))))}catch(j){if(j instanceof Error)$.error(j.message);else{let E=GM(j);$.error("iptables exited with error",E)}}await wy(z,JSON.stringify({lastDay:f}),"utf-8"),$.info(`\u2728 banned ${w} ips, didn't ban ${X} ips`);let D=M-T.usdBudget,B=D.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),L=M.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),Z=Math.round(D/M*100);$.info(`\uD83D\uDCB8 spent ${B}, ${Z}% of ${L} budget`)}var b$=new w0;Object.assign(console,b$.logger,{log:b$.logger.info});process.on("SIGINT",()=>{b$.logger.info("\u2757 received SIGINT; exiting gracefully"),vW()});process.on("SIGTERM",()=>{b$.logger.info("\u2757 received SIGTERM; exiting gracefully"),vW()});process.on("exit",()=>{b$.logger.info("\u2757 received exit; exiting gracefully"),vW()});b$.logger.info("\uD83D\uDEEB tribunal worker ready");var yy=new sX({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:I$.OPENAI_API_KEY,cachingMode:"off",logger:b$.logger});if(I$.OPENAI_API_KEY===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await VK({generator:yy,logFilePath:"/var/log/nginx/access.log",logger:b$.logger});vW();function vW(){b$.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}