tempest.games 0.1.19 → 0.1.20

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 zw=Object.create;var{getPrototypeOf:_w,defineProperty:oW,getOwnPropertyNames:Hw}=Object;var Ew=Object.prototype.hasOwnProperty;var Ry=(T,S,$)=>{$=T!=null?zw(_w(T)):{};let M=S||!T||!T.__esModule?oW($,"default",{value:T,enumerable:!0}):$;for(let f of Hw(T))if(!Ew.call(M,f))oW(M,f,{get:()=>T[f],enumerable:!0});return M};var Oy=(T,S)=>()=>(S||T((S={exports:{}}).exports,S),S.exports);var Dw=(T,S)=>{for(var $ in S)oW(T,$,{get:S[$],enumerable:!0,configurable:!0,set:(M)=>S[$]=()=>M})};function xM(T=Math.random){return T().toString(36).slice(2)}class Lf extends Promise{fate;resolve;reject;done=!1;constructor(T){let S,$;super((M,f)=>{S=M,$=f});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:M})=>S.toJson(M(T)),set:({set:M},f)=>{M(T,S.fromJson(f))}})};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 MT{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 gW extends MT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function F$(T,S,$){let M={key:S.key,type:"atom_family"},f=T.families.get(S.key);if(f)T.logger.error("\u2757","atom_family",S.key,`Overwriting an existing ${pS(f)} "${f.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new MT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},K=`${S.key}(${k})`,w=I(T),z=S.default,O={key:K,default:z instanceof Function?z(A):z};if(S.effects)O.effects=S.effects(A);let Q=ES(w,O,X);return J.next({type:"state_creation",token:Q}),Q},M,{subject:J,install:(A)=>F$(A,S),internalRoles:$});return T.families.set(S.key,W),T.defaults.set(S.key,S.default),M}function QA(T,S){if("mutable"in S)return Nf(T,S);return F$(T,S)}function R$(T,S,$){let M={key:S.key,type:"readonly_selector_family"},f=T.families.get(S.key);if(f)T.logger.error("\u2757","readonly_selector_family",S.key,`Overwriting an existing ${pS(f)} "${f.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new MT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},K=`${S.key}(${k})`,w=I(T),z=Cf(w,{key:K,get:S.get(A)},X);return J.next({type:"state_creation",token:z}),z},M,{internalRoles:$,subject:J,install:(A)=>R$(A,S),default:(A)=>{return S.get(A)({get:(...X)=>kT(T,...X),find:(X,K)=>YT(T,X,K),seek:(X,K)=>CT(T,X,K),json:(X)=>PT(T,X)})}});return T.families.set(S.key,W),M}function xf(T,S){if("set"in S)return jf(T,S);return R$(T,S)}var Qw={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function jM(T,S){let $=e(S),M=`${T.key}(${$})`,f=Qw[T.type],J={key:M,type:f};if(f==="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 M=e($);try{let f=[],J;if(S==="root")f.push(T.molecules.get('"root"')),J="all";else if(typeof S==="string"&&S.startsWith(Uw)){J="any";let X=e(S),K=T.molecules.get(X);if(!K)throw new Error(`Molecule ${X} not found in store "${T.config.name}"`);f.push(K)}else if($.startsWith("T$--")){J="all";for(let K of S){let w=e(K),z=T.molecules.get(w);if(!z)throw new Error(`Molecule ${w} not found in store "${T.config.name}"`);f.push(z)}}else{J="any";let K=e(S),w=T.molecules.get(K);if(!w)throw new Error(`Molecule ${K} not found in store "${T.config.name}"`);f.push(w)}let F=new IM(f,$);F._dependsOn=J,T.molecules.set(M,F);for(let X of f)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(f){if(f instanceof Error)T.logger.error("\u274C","molecule",M,"allocation failed:",f.message)}return $}function If(T,S){let $=e(S),M=T.molecules.get($);if(!M)throw new Error(`Molecule ${$} not found in store "${T.config.name}"`);for(let k of M.joins.values())k.relations.delete(M.key),k.molecules.delete(M.stringKey);let f;if(M.above.size===1)f=M.above.values().next().value.key;else f=[...M.above.values()].map(({key:k})=>k);let J=[];for(let k of M.tokens.values()){let X=k.family;J.push([X.key,T.valueMap.get(k.key)])}for(let k of M.tokens.values())OS(T,k);for(let k of M.below.values())if(k.dependsOn==="all")If(T,k.key);else if(k.above.delete(M.stringKey),k.above.size===0)If(T,k.key);M.below.clear();let F={type:"molecule_disposal",subType:"modern",key:M.key,values:J,provenance:f},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(M.stringKey);for(let k of M.above.values())k.below.delete(M.stringKey)}var Uw="T$";function bM(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,$,M,f,...J)=>{console[T](`${S} ${$} "${M}" ${f}`,...J)},Vw={error:iW("error"),info:iW("info"),warn:iW("warn")};class dW{T;S;$;constructor(T,S,$=Vw){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 xf(WT.STORE,T)}function bf(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),M=this.relations.get(S);if($)$.add(S);else $=new Set([S]),this.relations.set(T,$);if(M)M.add(T);else M=new Set([T]),this.relations.set(S,M)}deleteRelation(T,S){let $=this.relations.get(T);if($){if($.delete(S),$.size===0)this.relations.delete(T);let M=this.relations.get(S);if(M){if(M.delete(T),M.size===0)this.relations.delete(S)}}}replaceRelationsUnsafely(T,S){this.relations.set(T,new Set(S));for(let $ of S){let M=new Set().add(T);this.relations.set($,M)}}replaceRelationsSafely(T,S){let $=this.relations.get(T),M=this.isAType?.(T)?T:void 0,f=M===void 0?T:void 0;if($)for(let J of $){M??=J,f??=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(M,f))}}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(([$,M])=>[$,new Set(M)])),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=(M,f)=>$.has(M,f),this.addRelation=(M,f)=>{$.addRelation(M,f)},this.deleteRelation=(M,f)=>{$.deleteRelation(M,f)},this.replaceRelationsSafely=(M,f)=>{$.replaceRelationsSafely(M,f)},this.replaceRelationsUnsafely=(M,f)=>{$.replaceRelationsUnsafely(M,f)},this.getRelatedKeys=(M)=>$.getRelatedKeys(M),$.getContent)this.getContentInternal=(M)=>{return $.getContent(M)},this.setContent=(M,f)=>{$.setContent(M,f)},this.deleteContent=(M)=>{$.deleteContent(M)};for(let[M,f]of T.relations??[]){let J=this.isAType?.(M)?M:void 0,F=J===void 0?M:void 0;for(let W of f)J??=W,F??=W,this.addRelation(J,F)}for(let[M,f]of T.contents??[])this.setContent(M,f)}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],M=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 f=this.getRelatedKey(T);if(f&&f!==$)this.delete(T,f)}case"1:n":{let f=this.getRelatedKey($);if(f&&f!==T)this.delete(f,$)}}if(M){let f=this.makeContentKey(T,$);this.setContent(f,M)}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 M=this.getRelatedKeys(S);if(M)for(let f of M)this.delete(f,S)}if(typeof $==="string"&&S===void 0){let M=this.getRelatedKeys($);if(M)for(let f of M)this.delete($,f)}if(typeof $==="string"&&typeof S==="string"){this.deleteRelation($,S);let M=this.makeContentKey($,S);this.deleteContent(M)}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((M)=>`"${M}"`).join(", ")}). Only one related key was expected.`);let $;for(let M of S){$=M;break}return $}}replaceRelations(T,S,$){let M=!Array.isArray(S),f=M?Object.keys(S):S;if($?.reckless)this.replaceRelationsUnsafely(T,f);else this.replaceRelationsSafely(T,f);if(M)for(let J of f){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 M=this.getRelatedKeys(S);if(M)return[...M].map((f)=>{return[f,this.getContent(S,f)]})}if(S===void 0&&$!==void 0){let M=this.getRelatedKeys($);if(M)return[...M].map((f)=>{return[f,this.getContent(f,$)]})}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 Bw=(T)=>T[0].toUpperCase()+T.slice(1);function pS(T){return T.type.split("_").map(Bw).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 M=T[1];super(`${pS(S)} "${S.key}" member ${e(M)} not found in store "${$.config.name}".`)}}}function m$(T,S,$){return(...M)=>{let f=TT(T,$);if(f)return f.run(M,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)},ZM=(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),M=$.selectorAtoms.getRelatedKeys(T.key);if($.logger.info("\uD83E\uDDF9",T.type,T.key,M?`evicting ${M.size} states downstream:`:"no downstream states",M??"to evict"),M){if($.operation.open)$.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...$.operation.done].join(", ")} ] already done`);for(let f of M){if(xA($,f))continue;IA(f,$),ZM($,f)}}};function Lw(T,S){if(ZA(S.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var bA=(T,S,$)=>{let{key:M}=T,f=I($);if(!XT(f)||f.transactionMeta.phase!=="building"){$.logger.error("\uD83D\uDC1E","atom",M,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!Lw(M,S))return;let F={type:"atom_update",key:M,...S};if(T.family)F.family=T.family;f.transactionMeta.update.updates.push(F),$.logger.info("\uD83D\uDCC1","atom",M,"stowed (",S.oldValue,"->",S.newValue,")")};var qA=(T,S,$)=>{let M=h$(T,$),f=M;if(T.type==="mutable_atom"&&XT($)){let{parent:F}=$;f=Zf(T,F,$)}if(f=rJ(S)(f),$.logger.info("\uD83D\uDCDD","atom",T.key,"set to",f),f=qS(T.key,f,T.subject,$),mA(T.key,$))hA(T.key,$);ZM($,T.key),lW(T,$);let J={oldValue:M,newValue:f};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=Zf(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 $,M,f,J;if(S.length===2){if($=S[0],J=S[1],M=eJ(T,$)??null,M)f=$.family?iT($.family.subKey):null,$=YT(T,M,f)}else M=S[0],f=S[1],J=S[2],$=YT(T,M,f);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:M,newValue:f,oldValue:J}=S,F=T==="newValue"?f:J,W={key:M,type:"atom"};if(S.family)Object.assign(W,{family:S.family});ZT($,W,F)}function vA(T,S){let $=new MT,M={type:"molecule_family",key:S.key,dependsOn:S.dependsOn??"all"},f={...M,subject:$,new:S.new};return T.moleculeFamilies.set(S.key,f),M}function iS(T,S,$){let M=O$($,S,T.key);T.tokens.set(M.key,M);let f=XT($)&&$.transactionMeta.phase==="building",J=$.moleculeInProgress===T.key;if(!f&&!J)T.subject.next({type:"state_creation",token:M});return M}function TF(T){return{store:T}}function kT(T,...S){let $,M,f;if(S.length===1){if($=S[0],$.type!=="molecule"){if(M=eJ(T,$)??null,M)f=$.family?iT($.family.subKey):null,$=YT(T,M,f)}}else{M=S[0],f=S[1];let J;if(M.type==="molecule_family")J=CT(T,M,f)??jM(M,f);else J=YT(T,M,f);$=J}if("counterfeit"in $&&"family"in $){M=$.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."),M.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(M.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(M.key))return T.defaults.get($.family.key);let W=TT(M,T).default(J);return T.defaults.set(M.key,W),W}case"molecule_family":throw new DS(M,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 IM{S;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new MT;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 M of T)this.above.set(M.stringKey,M)}}function PA(T){return T[0].toUpperCase()+T.slice(1)}function G$(T,S,$,M,...f){let J=DA(T),F=I(T),W=e(M);F.moleculeInProgress=W;let A=Array.isArray(S)?S:[S],k=A.map((D)=>{if(D instanceof IM)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 IM(k,M,$);F.molecules.set(W,X);for(let D of k)D.below.set(X.stringKey,X);let K={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=xM())=>m$(D,B,I(T)),make:(D,B,L,...b)=>G$(I(J),D,B,L,...b),dispose:(D)=>{OS(I(J),D)},env:()=>TF(I(J)),bond:(D,B)=>{if(D.type==="join"){let{as:L}=B,b=qf(D,J);b.molecules.set(W,X),X.joins.set(D.key,b);let C=w.subject.subscribe(`join:${D.key}-${W}`,(G)=>{if(G.type==="molecule_disposal"){if(e(G.token.key)===W)C(),b.molecules.delete(W)}});if(L===null)return;let E=D.a===L?D.b:D.a,_=nA(D,M),U=_[`${E}KeysOf${PA(L)}`],q=_[`${E}EntriesOf${PA(L)}`],h={relatedKeys:U};if(q)h=Object.assign(h,{relatedEntries:q});return h}return iS(X,TT(D,J),I(J))},claim:(D,B)=>{let{exclusive:L}=B,b=I(T).molecules.get(e(D.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:(D,B,...L)=>G$(I(T),[X],TT(D,T),B,...L)},w=TT($,T),z=w.new;X.instance=new z(K,M,...f);let O={type:"molecule",key:M,family:$},Q={type:"molecule_creation",subType:"classic",token:O,family:$,context:A,params:f};if(nT(F))w.subject.next(Q);else if(XT(F)&&F.on.transactionApplying.state===null)F.transactionMeta.update.updates.push(Q);return F.moleculeInProgress=null,O}function rW(T,S,$){switch(S){case"newValue":{cA(T,$);break}case"oldValue":{OS($,T.token);break}}}function aW(T,S,$){switch(S){case"newValue":{OS($,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 M=S.families.get($.key);if(M)YT(S,M,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":OS($,T.token);break;case"modern":If($,T.key);break}break}}function sW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":OS($,T.token);break;case"modern":If($,T.key);break}break;case"oldValue":switch(T.subType){case"classic":{let M=G$($,T.context,T.family,T.token.key);for(let[f,J]of T.values){let F=`${f}(${e(M.key)})`,W=TT(M,$),A=W.tokens.has(F),k=$.families.get(f);if(k&&!A)iS(W,k,$);$.valueMap.set(F,J)}}break;case"modern":{tW($,T.provenance,T.key);for(let[M,f]of T.values){let J=$.families.get(M);if(J){YT($,J,T.key);let F=`${M}(${e(T.key)})`;$.valueMap.set(F,f)}}}}break}}function SF(T,S,$){let M=T==="newValue"?S.updates:[...S.updates].reverse();for(let f of M)switch(f.type){case"atom_update":case"selector_update":sJ(T,f,$);break;case"state_creation":rW(f,T,$);break;case"state_disposal":aW(f,T,$);break;case"molecule_creation":eW(f,T,$);break;case"molecule_disposal":sW(f,T,$);break;case"transaction_update":SF(T,f,$);break}}function oA(T,S,$){if(nT($)&&T)$.transactionMeta.epoch.set(T,S)}function gA(T,S,$){if(!nT($))return;let f=$.transactionMeta.actionContinuities.getRelatedKey(T);if(f!==void 0)$.transactionMeta.epoch.set(f,S)}var tA=(T,S)=>{let $=I(S),{parent:M}=$;if(M===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,M.child=null,M.on.transactionApplying.next($.transactionMeta);let{updates:f}=$.transactionMeta.update;if(S.logger.info("\uD83D\uDEC4","transaction",$.transactionMeta.update.key,`Applying transaction with ${f.length} updates:`,f),SF("newValue",$.transactionMeta.update,M),nT(M))gA($.transactionMeta.update.key,$.transactionMeta.update.epoch,M),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(M))M.transactionMeta.update.updates.push($.transactionMeta.update);M.on.transactionApplying.next(null)};function pA(T,S,$){if(!nT($))return;let{epoch:f,actionContinuities:J}=$.transactionMeta;if(J.set(T,S),!f.has(T))f.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 iA=(T,S,$,M)=>{let f=I($),J={parent:f,child:null,on:f.on,loggers:f.loggers,logger:f.logger,config:f.config,atoms:new mS(f.atoms),atomsThatAreDefault:new Set(f.atomsThatAreDefault),families:new mS(f.families),operation:{open:!1},readonlySelectors:new mS(f.readonlySelectors),timelines:new mS(f.timelines),timelineTopics:new BS(f.timelineTopics.toJSON()),trackers:new Map,transactions:new mS(f.transactions),selectorAtoms:new BS(f.selectorAtoms.toJSON()),selectorGraph:new BS(f.selectorGraph.toJSON(),{makeContentKey:(...k)=>k.sort().join(":")}),selectors:new mS(f.selectors),valueMap:new mS(f.valueMap),defaults:f.defaults,disposalTraces:$.disposalTraces.copy(),molecules:new mS(f.molecules),moleculeFamilies:new mS(f.moleculeFamilies),moleculeInProgress:f.moleculeInProgress,miscResources:new mS(f.miscResources)},F=dA(T,$),W={phase:"building",update:{type:"transaction_update",key:T,id:M,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=xM())=>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,K,...w)=>G$(A,k,X,K,...w),dispose:(...k)=>{OS(A,...k)},env:()=>TF(A)}},A=Object.assign(J,{transactionMeta:W});return f.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(M),S.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",A),A}},install:(J)=>uW(T,J),subject:new MT},M=I(S);M.transactions.set($.key,$);let f=XS($);return S.on.transactionCreation.next(f),f}function dA(T,S){let $=nT(S),M=$?S.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return $&&M!==void 0?S.transactionMeta.epoch.get(M):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 MT,atomDisposal:new MT,selectorCreation:new MT,selectorDisposal:new MT,timelineCreation:new MT,transactionCreation:new MT,transactionApplying:new gW(null),operationClose:new MT,moleculeCreationStart:new MT,moleculeCreationDone:new MT,moleculeDisposal:new MT};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[,M]of S.families){if(M.internalRoles?.includes("mutable")||M.internalRoles?.includes("join"))continue;M.install(this)}let $=new Set;for(let[,M]of S.atoms){if($.has(M.key))continue;if(M.install(this),M.type==="mutable_atom"){let f=PT(S,M),J=z$(M);$.add(f.key),$.add(J.key)}}for(let[,M]of S.readonlySelectors)M.install(this);for(let[,M]of S.selectors){if($.has(M.key))continue;M.install(this)}for(let[,M]of S.transactions)M.install(this);for(let[,M]of S.timelines)M.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 $,M=S;while(M!==null){switch(T.type){case"atom":case"mutable_atom":$=M.atoms.get(T.key);break;case"selector":$=M.selectors.get(T.key);break;case"readonly_selector":$=M.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":$=M.families.get(T.key);break;case"timeline":$=M.timelines.get(T.key);break;case"transaction":$=M.transactions.get(T.key);break;case"molecule":$=M.molecules.get(e(T.key));break;case"molecule_family":$=M.moleculeFamilies.get(T.key);break}if($)return $;M=M.child}throw new DS(T,S)}function MF(T,S){let $;$=TT(T,S);let{family:M}=T;for(let F of $.joins.values())F.relations.delete($.key),F.molecules.delete($.stringKey);let f=[];for(let F of $.above.values())f.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(M){let F=TT(M,S),W={type:"molecule_disposal",subType:"classic",token:T,family:M,context:f,values:J};if(T.family)W.family=T.family;for(let k of $.tokens.values())OS(S,k);for(let k of $.below.values())if(k.dependsOn==="all")MF(k,S);else if(k.above.delete($.stringKey),k.above.size===0)MF(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 O$(T,S,$){let M=T.families.get(S.key);if(M===void 0)throw new DS(S,T);let f=M($),J=I(T);if(f.family&&J.moleculeInProgress===null){if(nT(J))switch(f.type){case"atom":case"mutable_atom":T.on.atomCreation.next(f);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(f);break}else if(XT(J)&&J.on.transactionApplying.state===null)J.transactionMeta.update.updates.push({type:"state_creation",token:f})}return f}function CT(T,S,$){let M=e($),f=`${S.key}(${M})`,J=I(T),F;switch(S.type){case"atom_family":case"mutable_atom_family":F=J.atoms.get(f);break;case"selector_family":F=J.selectors.get(f);break;case"readonly_selector_family":F=J.readonlySelectors.get(f);break;case"molecule_family":F=J.molecules.get(e($))}if(F)return XS(F);return F}function YT(T,S,$){let M=CT(T,S,$);if(M)return M;let f=T.molecules.get(e($));if(f)return iS(f,S,T);if(T.config.lifespan==="immortal"){let J=jM(S,$);return T.logger.error("\u274C",J.type,J.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),J}return M=O$(T,S,$),M}function OS(T,...S){let $,M;if(S.length===1)$=S[0],M=$.key;else{let J=S[0],F=S[1];$=J.type==="molecule_family"?CT(T,J,F)??jM(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":MF($,T);break}let{stack:f}=new Error;if(f){let J=f?.split(`
8
+ `)?.slice(3)?.join(`
9
+ `);T.disposalTraces.add({key:$.key,trace:J})}}var fF=(T,S)=>I(S).atoms.has(T),Nw=(T,S)=>I(S).selectors.has(T),Cw=(T,S)=>I(S).readonlySelectors.has(T),rA=(T,S)=>fF(T,S)||Nw(T,S)||Cw(T,S);var JF=(T,S)=>{return I(S).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([M,{source:f}])=>f!==T).map(([M,{source:f}])=>f).filter((M)=>rA(M,S))};var S0=(T,S,$)=>{let M=[],f=JF(T,$);while(f.length>0){let J=f.shift();if(S.has(J))continue;if(S.add(J),!fF(J,$))f.push(...JF(J,$));else if(!M.includes(J))M.push(J)}return M},aA=(T,S)=>{let $=T.key,M=JF($,S),f=new Set;return M.flatMap((J)=>fF(J,S)?J:S0(J,f,S))};var eA=(T,S,$,M)=>{let f=I(M);if(S.type==="atom"||S.type==="mutable_atom")f.selectorAtoms.set({selectorKey:T,atomKey:S.key}),M.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${S.key}"`);else{let J=S0(S.key,$,M);M.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${J.map((F)=>`"${F}"`).join(", ")} ]`);for(let F of J)f.selectorAtoms=f.selectorAtoms.set({selectorKey:T,atomKey:F})}$.add(S.key)};var FF=(T,S,$)=>({get:(...M)=>{let f=I($),J;if(M.length===2){let[A,k]=M;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]=M;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,")"),f.selectorGraph.set({upstreamSelectorKey:J.key,downstreamSelectorKey:T},{source:J.key}),eA(T,J,S,$),W},set:(...M)=>{let f,J;if(M.length===2)f=M[0],J=M[1];else{let A=M[0],k=M[1];J=M[2];let X=$.config.lifespan==="ephemeral"?YT($,A,k):CT($,A,k);if(!X)throw new DS(A,k,$);f=X}let F=I($),W=TT(f,F);aJ(W,J,F)},find:(M,f)=>YT($,M,f),seek:(M,f)=>CT($,M,f),json:(M)=>PT($,M)});var Cf=(T,S,$)=>{let M=I(T),f=new MT,J=new Set,{get:F,find:W,seek:A,json:k}=FF(S.key,J,M),X=()=>{let O=S.get({get:F,find:W,seek:A,json:k});return qS(S.key,O,f,I(T)),J.clear(),O},K={...S,subject:f,install:(O)=>Cf(O,S,$),get:X,type:"readonly_selector",...$&&{family:$}};M.readonlySelectors.set(S.key,K);let w=X();T.logger.info("\u2728",K.type,K.key,"=",w);let z={key:S.key,type:"readonly_selector"};if($)z.family=$;return z};var mf=(T,S,$)=>{let M=I(T),f=new MT,J=new Set,F=FF(S.key,J,M),{find:W,get:A,seek:k,json:X}=F,K={find:W,get:A,seek:k,json:X},w=(B=S.get,L=I(T))=>{let b=B(K);return qS(S.key,b,f,L),J.clear(),b},O={...S,subject:f,install:(B)=>mf(B,S,$),get:w,set:(B)=>{let L=I(T),b=w(S.get,L),C=rJ(B)(b);if(T.logger.info("\uD83D\uDCDD","selector",S.key,"set (",b,"->",C,")"),qS(S.key,C,f,L),ZM(L,S.key),nT(L))f.next({newValue:C,oldValue:b});S.set(F,C)},type:"selector",...$&&{family:$}};M.selectors.set(S.key,O);let Q=w();T.logger.info("\u2728",O.type,O.key,"=",Q);let D={key:S.key,type:"selector"};if($)D.family=$;return D};function tS(T,S){if("set"in S){let f=mf(T,S,void 0);return T.on.selectorCreation.next(f),f}let M=Cf(T,S,void 0);return T.on.selectorCreation.next(M),M}function lA(T,S){let $=I(S),{key:M}=T,f=TT(T,$);if(!f.family)S.logger.error("\u274C","selector",M,"Standalone selectors cannot be disposed.");else{let J=$.molecules.get(f.family.subKey);if(J)J.tokens.delete(M);switch(T.type){case"selector":$.selectors.delete(M),TT({key:f.family.key,type:"selector_family"},S).subject.next({type:"state_disposal",token:T});break;case"readonly_selector":$.readonlySelectors.delete(M),TT({key:f.family.key,type:"readonly_selector_family"},S).subject.next({type:"state_disposal",token:T});break}if($.valueMap.delete(M),$.selectorAtoms.delete(M),$.selectorGraph.delete(M),S.logger.info("\uD83D\uDD25",T.type,M,"deleted"),XT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.selectorDisposal.next(T)}}function jf(T,S,$){let M={key:S.key,type:"selector_family"},f=T.families.get(S.key);if(f)T.logger.error("\u2757","selector_family",S.key,`Overwriting an existing ${pS(f)} "${f.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new MT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},K=`${S.key}(${k})`,w=I(T),z=mf(w,{key:K,get:S.get(A),set:S.set(A)},X);return J.next({type:"state_creation",token:z}),z},M,{internalRoles:$,subject:J,install:(A)=>jf(A,S),default:(A)=>{return S.get(A)({get:(...X)=>kT(T,...X),find:(X,K)=>YT(T,X,K),seek:(X,K)=>CT(T,X,K),json:(X)=>PT(T,X)})}});return T.families.set(S.key,W),M}function sA(T,S,$=WT.STORE){let M=jf($,{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 w=iS(X,T,$);return S.toJson(W(w))}if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${k}"`);let K=O$($,T,J);return S.toJson(W(K))},set:(J)=>({seek:F,set:W},A)=>{let k=F(T,J);if(k)W(k,S.fromJson(A));else{let X=e(J),K=$.molecules.get(X);if(K){let w=iS(K,T,$);W(w,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)CT($,M,iT(J.token.family.subKey))}),M}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 f0=(T,S)=>{let $=I(S);return aA(T,S).map((f)=>{let J=$.atoms.get(f);if(J===void 0)throw new Error(`Atom "${f}", 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",f,"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 KS(T,S,$,M){function f(K){if(M.operation.open){let w=M.on.operationClose.subscribe(`state subscription ${$}`,()=>{w(),S(K)})}else S(K)}let J=TT(T,M);M.logger.info("\uD83D\uDC40",J.type,J.key,`Adding subscription "${$}"`);let F=J.type==="selector"||J.type==="readonly_selector",W=null,A=f;if(F)W=f0(J,M),A=(K)=>{if(W)W.length=0,W.push(...f0(J,M));f(K)};let k=J.subject.subscribe($,A);return()=>{if(M.logger.info("\uD83D\uDE48",J.type,J.key,`Removing subscription "${$}"`),k(),W)for(let K of W)K()}}var $0=(T,S,$,M)=>{let f=TT(T,M);M.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${$}"`);let J=f.subject.subscribe($,S);return()=>{M.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${$}" from timeline`),J()}};var M0=(T,S,$,M)=>{let f=TT(T,M);M.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${$}"`);let J=f.subject.subscribe($,S);return()=>{M.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 M=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,f=ES(S,{key:$,default:null},M);if(S.parent?.valueMap.has($)){let J=S.parent.valueMap.get($);S.valueMap.set($,J)}return f}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,S,$){let M=`tracker:${$.config.name}:${XT($)?$.transactionMeta.update.key:"main"}:${T.key}`,f=kT($,T);this.unsubscribeFromInnerValue=f.subscribe(M,(J)=>{ZT($,S,J)}),this.unsubscribeFromState=KS(T,(J)=>{if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(M,(F)=>{ZT($,S,F)})},M,$)}updateCore(T,S,$){let M=`tracker:${$.config.name}:${XT($)?$.transactionMeta.update.key:"main"}:${T.key}`;KS(S,({newValue:f,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,(K)=>{if(X==="redo"&&f)K.do(f);else if(X==="undo"&&J)K.undo(J);return K})},M,$);return}}let W=$.on.operationClose.subscribe(M,()=>{W();let A=kT($,T),k=f===null?-1:A.getUpdateNumber(f),X=k-A.cacheUpdateNumber;if(f&&X===1)ZT($,T,(K)=>(K.do(f),K));else $.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${A.cacheUpdateNumber+1}, but got ${k}`)})},M,$)}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 hf(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let M=I(T),f=M.atoms.get(S.key);if(f&&f.type==="mutable_atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),XS(f);let J=new MT,F={...S,type:"mutable_atom",install:(k)=>{return k.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${k.config.name}"`),hf(k,S,$)},subject:J};if($)F.family=$;let W=S.default();M.atoms.set(F.key,F),WF(S.key,T),qS(S.key,W,J,M);let A=XS(F);if(S.effects){let k=0,X=[];for(let K of S.effects){let w=K({setSelf:(z)=>{ZT(T,A,z)},onSet:(z)=>KS(A,z,`effect[${k}]`,T)});if(w)X.push(w);++k}F.cleanup=()=>{for(let K of X)K()}}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`,(M)=>{if(M.token.family){let f=iT(M.token.family.subKey);CT(S,this.latestUpdateAtoms,f),new v$(M.token,S)}}),this.latestUpdateAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(M)=>{if(M.token.family){let f=iT(M.token.family.subKey),J=CT(S,this.mutableAtoms,f);if(J)new v$(J,S)}})}}function Nf(T,S,$){let M={key:S.key,type:"mutable_atom_family"},f=T.families.get(S.key);if(f)T.logger.error("\u2757","mutable_atom_family",S.key,`Overwriting an existing ${pS(f)} "${f.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new MT,W=Object.assign((A)=>{let k=e(A),X={key:S.key,subKey:k},K=`${S.key}(${k})`,w=I(T),z={key:K,default:()=>S.default(A),toJson:S.toJson,fromJson:S.fromJson,mutable:!0};if(S.effects)z.effects=S.effects(A);let O=hf(w,z,X);return J.next({type:"state_creation",token:O}),O},M,{subject:J,install:(A)=>Nf(A,S),toJson:S.toJson,fromJson:S.fromJson,internalRoles:$});return T.families.set(S.key,W),sA(W,S,T),new J0(W,T),M}var F0=(T,S)=>{let $=I(S),M=`${T.key}:JSON`;return $.families.get(M)};var PT=(T,S)=>{if(S.family){let M=I(T),J={key:`${S.family.key}:JSON`,type:"selector_family"},F=TT(J,M),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 Zf(T,S,$){let M=S.valueMap.get(T.key),f=$.valueMap.get(T.key);if(M===f){if(M===void 0)return typeof T.default==="function"?T.default():T.default;S.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let J=T.toJson(M),F=T.fromJson(J);return $.valueMap.set(T.key,F),new v$(T,S),F}return f}function qS(T,S,$,M){let f=M.valueMap.get(T);if(f instanceof Lf)f.use(S);if(S instanceof Promise){let J=new Lf(S);return M.valueMap.set(T,J),J.then((F)=>{qS(T,F,$,M),$.next({newValue:F,oldValue:J})}).catch((F)=>{M.logger.error("\uD83D\uDCA5","state",T,"rejected:",F)}),J}return M.valueMap.set(T,S),S}var LA=(T,S)=>{let $=S.valueMap.get(T.key);if(T.type==="mutable_atom"&&XT(S)){let{parent:M}=S;$=Zf(T,M,S)}return $},IA=(T,S)=>{let $=S.valueMap.get(T);if($ instanceof Lf){let M=$,f=S.selectors.get(T)??S.readonlySelectors.get(T);if(f)M.use(f.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 M=I(T),f=M.atoms.get(S.key);if(f&&f.type==="atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),XS(f);let J=new MT,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();M.atoms.set(F.key,F),WF(S.key,T),qS(S.key,W,J,M);let A=XS(F);if(S.effects){let k=0,X=[];for(let K of S.effects){let w=K({setSelf:(z)=>{ZT(T,A,z)},onSet:(z)=>KS(A,z,`effect[${k}]`,T)});if(w)X.push(w);++k}F.cleanup=()=>{for(let K of X)K()}}return A}function UA(T,S){if("mutable"in S){let f=hf(T,S,void 0);return T.on.atomCreation.next(f),f}let M=ES(T,S,void 0);return T.on.atomCreation.next(M),M}function T0(T,S){let $=I(S),{key:M}=T,f=TT(T,$);if(!f.family)S.logger.error("\u274C","atom",M,"Standalone atoms cannot be disposed.");else{f.cleanup?.();let J=S.valueMap.get(f.key);TT({key:f.family.key,type:"atom_family"},S).subject.next({type:"state_disposal",token:T,value:J});let W=$.molecules.get(f.family.subKey);if(W)W.tokens.delete(M);if($.atoms.delete(M),$.valueMap.delete(M),$.selectorAtoms.delete(M),$.atomsThatAreDefault.delete(M),S.timelineTopics.delete(M),T.type==="mutable_atom"){let A=z$(T);T0(A,S),S.trackers.delete(M)}if(S.logger.info("\uD83D\uDD25","atom",M,"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 MT;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 M of this.transactionUpdates)this.doStep(M);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),M=T.substring(S+1);switch($){case"add":this.add(JSON.parse(M));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(M));break;case"tx":for(let f of M.split(";"))this.doStep(f)}}getUpdateNumber(T){let S=T.indexOf("=");return Number(T.substring(0,S))}do(T){let S=T.indexOf("="),$=Number(T.substring(0,S)),M=$-this.cacheUpdateNumber;if(M>0){if(M===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(M)<this.cacheLimit){let J=this.cacheIdx+M;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),M=T.substring(S+1);switch($){case"add":this.delete(JSON.parse(M));break;case"del":this.add(JSON.parse(M));break;case"clear":{let f=JSON.parse(M);for(let J of f)this.add(J);break}case"tx":{let f=M.split(";");for(let J=f.length-1;J>=0;J--)this.undoStep(f[J])}}}undo(T){let S=T.indexOf("=");if(Number(T.substring(0,S))===this.cacheUpdateNumber){this.mode="playback";let M=T.substring(S+1);return this.undoStep(M),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 M=new A0(this.options,this.defaultContent,T);return this.alternates.set(S,M),M.alternates=this.alternates,M}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 U=this.toolkit.seek(E,_);if(U)return U;let q=this.store.molecules.get(e(_));if(q){let h=TT(E,$);return iS(q,h,$)}if($.config.lifespan==="immortal")throw new DS(E,_,$);return O$($,E,_)},this.toolkit={get:(...E)=>kT($,...E),set:(...E)=>{ZT($,...E)},find:this.retrieve,seek:(...E)=>CT($,...E),json:(E)=>PT($,E),dispose:(...E)=>{OS($,...E)}};let M=T.between[0],f=T.between[1],J=Nf($,{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,_,U)=>{let{set:q}=E,h=this.retrieve(J,_),G=this.retrieve(J,U);q(h,(o)=>o.add(U)),q(G,(o)=>o.add(_))},A=(E,_,U)=>{let{set:q}=E,h=this.retrieve(J,_),G=this.retrieve(J,U),o,n;q(h,(p)=>{if(p.delete(U),p.size===0)o=`"${_}"`;return p}),q(G,(p)=>{if(p.delete(_),p.size===0)n=`"${U}"`;return p})},k=(E,_,U)=>{let{get:q,set:h}=E,G=this.retrieve(J,_),o=q(G);for(let n of o){if(U.includes(n))continue;let RT=this.retrieve(J,n);h(RT,(_T)=>{return _T.delete(_),_T})}h(G,(n)=>{return n.transaction((p)=>{p.clear();for(let RT of U){let _T=F(E,RT),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(RT),l.size===0)y$.push(N)}if(!HS&&_T.size>0)_T.clear();for(let N of y$){let l=[RT,N].sort(),OT=`"${l[0]}:${l[1]}"`;this.molecules.delete(OT)}}if(!HS)_T.add(_);p.add(RT)}return!0}),n})},X=(E,_,U)=>{let{set:q}=E,h=this.retrieve(J,_);q(h,(G)=>{return G.transaction((o)=>{for(let n of U)o.add(n);return!0}),G});for(let G of U){let o=this.retrieve(J,G);q(o,(n)=>{return n.add(_),n})}return!0},K=(E,_,U)=>{let q=F(E,_);return U?q.has(U):q.size>0},w={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,_)=>K(this.toolkit,E,_)},z,O,Q;if(S){O=F$($,{key:`${T.key}/content`,default:S},["join","content"]),Q=vA($,{key:`${T.key}/content-molecules`,new:class h{o;constructor(G,o){this.key=o}}});let E=({get:h},G)=>h(this.retrieve(O,G)),_=({set:h},G,o)=>{h(this.retrieve(O,G),o)},U=(h,G)=>{let o=$.molecules.get(`"${G}"`);if(o)this.toolkit.dispose(o),this.molecules.delete(`"${G}"`)};z=Object.assign(w,{getContent:(h)=>{return E(this.toolkit,h)},setContent:(h,G)=>{_(this.toolkit,h,G)},deleteContent:(h)=>{U(this.toolkit,h)}})}else z=w;let D=new BS(T,{externalStore:z,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...E)=>{let _=E.sort(),U=`${_[0]}:${_[1]}`,[q,h]=_.map((G)=>this.molecules.get(e(G)));if($.config.lifespan==="immortal"&&q&&h){let G=I($),o=G$(G,[q,h],Q,U);this.molecules.set(`"${U}"`,TT(o,G))}return U}}),B=()=>R$($,{key:`${T.key}/singleRelatedKey`,get:(E)=>({get:_})=>{let U=this.retrieve(J,E),q=_(U);for(let h of q)return h;return null}},["join","keys"]),L=()=>{return R$($,{key:`${T.key}/multipleRelatedKeys`,get:(E)=>({get:_})=>{let U=F0(J,$),q=this.retrieve(U,E);return _(q).members}},["join","keys"])},b=()=>R$($,{key:`${T.key}/singleRelatedEntry`,get:(E)=>({get:_})=>{let U=this.retrieve(J,E),q=_(U);for(let h of q){let G=D.isAType?.(E)?E:void 0,o=G===void 0?E:void 0;G??=h,o??=h;let n=D.makeContentKey(G,o),p=this.retrieve(O,n),RT=_(p);return[h,RT]}return null}},["join","entries"]),C=()=>R$($,{key:`${T.key}/multipleRelatedEntries`,get:(E)=>({get:_})=>{let U=F0(J,$),q=this.retrieve(U,E);return _(q).members.map((G)=>{let o=D.isAType?.(E)?E:void 0,n=o===void 0?E:void 0;o??=G,n??=G;let p=D.makeContentKey(o,n),RT=this.retrieve(O,p),_T=_(RT);return[G,_T]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let E=B(),_=`${M}KeyOf${IT(f)}`,U=`${f}KeyOf${IT(M)}`,q={[_]:E,[U]:E},h;if(S){let G=b(),o=`${M}EntryOf${IT(f)}`,n=`${f}EntryOf${IT(M)}`,p={[o]:G,[n]:G};h=Object.assign(q,p)}else h=q;this.relations=D,this.states=h;break}case"1:n":{let E=B(),_=L(),U=`${M}KeyOf${IT(f)}`,q=`${f}KeysOf${IT(M)}`,h={[U]:E,[q]:_},G;if(S){let o=b(),n=C(),p=`${M}EntryOf${IT(f)}`,RT=`${f}EntriesOf${IT(M)}`,_T={[p]:o,[RT]:n};G=Object.assign(h,_T)}else G=h;this.relations=D,this.states=G;break}default:{let E=L(),_=`${M}KeysOf${IT(f)}`,U=`${f}KeysOf${IT(M)}`,q={[_]:E,[U]:E},h;if(S){let G=C(),o=`${M}EntriesOf${IT(f)}`,n=`${f}EntriesOf${IT(M)}`,p={[o]:G,[n]:G};h=Object.assign(q,p)}else h=q;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 qf(T,S){let $=W0(S),M=$.get(T.key);if(M===void 0){if(M=W0(WT.STORE).get(T.key)?.in(S),M===void 0)throw new Error(`Join "${T.key}" not found in store "${S.config.name}"`);$.set(T.key,M)}return M}function kF(T,S,$){let M=qf(T,$),f;switch(T.cardinality){case"1:1":{let J=`${T.a}KeyOf${IT(T.b)}`,F=`${T.b}KeyOf${IT(T.a)}`;f={get[J](){let A=M.states[J];return M.retrieve(A,S)},get[F](){let A=M.states[F];return M.retrieve(A,S)}};let W=`${T.a}EntryOf${IT(T.b)}`;if(W in M.states){let A=`${T.b}EntryOf${IT(T.a)}`;Object.assign(f,{get[W](){let k=M.states[W];return M.retrieve(k,S)},get[A](){let k=M.states[A];return M.retrieve(k,S)}})}break}case"1:n":{let J=`${T.a}KeyOf${IT(T.b)}`,F=`${T.b}KeysOf${IT(T.a)}`;f={get[J](){let A=M.states[J];return M.retrieve(A,S)},get[F](){let A=M.states[F];return M.retrieve(A,S)}};let W=`${T.a}EntryOf${IT(T.b)}`;if(W in M.states){let A=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(f,{get[W](){let k=M.states[W];return M.retrieve(k,S)},get[A](){let k=M.states[A];return M.retrieve(k,S)}})}break}case"n:n":{let J=`${T.a}KeysOf${IT(T.b)}`,F=`${T.b}KeysOf${IT(T.a)}`;f={get[J](){let A=M.states[J];return M.retrieve(A,S)},get[F](){let A=M.states[F];return M.retrieve(A,S)}};let W=`${T.a}EntriesOf${IT(T.b)}`;if(W in M.states){let A=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(f,{get[W](){let k=M.states[W];return M.retrieve(k,S)},get[A](){let k=M.states[A];return M.retrieve(k,S)}})}}}return f}function nA(T,S){return kF(T,S,WT.STORE)}function XF(T,S,$){let M=qf(T,$),f=I($);if(XT(f)){let{toolkit:J}=f.transactionMeta;M.transact(J,({relations:F})=>{S(F)})}else S(M.relations)}function xw(T,S){return qf(T,S).core.findRelatedKeysState}function Sk(T){return xw(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 KF{T;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new $k;static create(T,S){let $=new KF(T),{type:M,globals:f,actions:J,perspectives:F}=S($),W={type:M,key:T,globals:f,actions:J,perspectives:F};return KF.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[$,M]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:$,viewAtoms:M})}break}return this}}function p_(T){let{key:S,config:$}=T,M=KF.create(S,$),{actions:f}=M;for(let J of f)pA(S,J.key,WT.STORE);return oA(S,-1,WT.STORE),M}var r_=bM({key:"usersInRoomIndex",mutable:!0,default:()=>new dT,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),k0=bM({key:"roomIndex",default:()=>new dT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),jw={enteredAtEpoch:0},vf=AF({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},jw),a_=lJ({key:"usersInMyRoomView",get:(T)=>({find:S})=>{let $=Sk(vf);return[S($,T)]}});import{spawn as Iw}from"child_process";class qM{T;listeners;globalListeners;handleEvent(T,...S){for(let M of this.globalListeners)M(T,...S);let $=this.listeners.get(T);if($)for(let M of $)M(...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 qM{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((M,...f)=>{let J=JSON.stringify([M,...f])+"\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",(M)=>{let f=M.toString();if(f==="ALIVE")return;this.unprocessedEvents.push(...f.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",(M)=>{let f=M.toString();this.unprocessedLogs.push(...f.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 Mk extends qM{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...S)=>{return this.out.next(S),this});this.id=T,this.in=new MT,this.out=new MT,this.in.subscribe("socket",(S)=>{this.handleEvent(...S)})}dispose(){for(let T of this.disposalFunctions)T()}}class K0 extends qM{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 M=iT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",M),this.handleEvent(...M);while(this.unprocessedEvents.length>0){let f=this.unprocessedEvents.shift();if(f){if(this.unprocessedEvents.length===0)this.incompleteData=f;let J=iT(f);this.handleEvent(...J)}}this.incompleteData=""}catch(M){if(M instanceof Error)this.logger.error("\u2757",M.message,M.cause,M.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 Mk(`user:${T}`);this.relays.set(T,S),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let $ of this.relayServices){let M=$(S);if(M)S.disposalFunctions.push(M)}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 w0=s$({key:"roomArguments",default:["echo",["Hello World!"]]}),fk=lJ({key:"room",get:(T)=>async({get:S,find:$})=>{let M=$(w0,T),f=S(M),[J,F]=f,W=await new Promise((A)=>{let k=Iw(J,F,{env:process.env}),X=(K)=>{if(K.toString()==="ALIVE")k.stdout.off("data",X),A(k)};k.stdout.on("data",X)});return new X0(W,T)}});var VH=bf({key:"createRoom",do:({get:T,set:S,find:$},M,f,J)=>{let F=J?[f,J]:[f],W=$(w0,M);S(W,F),S(k0,(X)=>X.add(M));let A=$(fk,M);return T(A)}}),BH=bf({key:"joinRoom",do:(T,S,$,M)=>{let f={enteredAtEpoch:M};return XF(vf,(J)=>{J.set({room:S,user:$},f)},T.env().store),f}}),LH=bf({key:"leaveRoom",do:(T,S,$)=>{XF(vf,(M)=>{M.delete({room:S,user:$})},T.env().store)}}),NH=bf({key:"destroyRoom",do:(T,S)=>{XF(vf,($)=>{$.delete({room:S})},T.env().store),T.set(k0,($)=>($.delete(S),$))}});function Y0(T,S){return S.map(($)=>{switch($.type){case"transaction_update":{let M=Y0(T,$.updates);return{...$,updates:M}}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}}),mM=s$({key:"unacknowledgedUpdates",default:()=>[]});var Jk=s$({key:"sockets",default:null}),mH=bM({key:"socketsIndex",mutable:!0,default:()=>new dT,toJson:(T)=>T.toJSON(),fromJson:(T)=>dT.fromJSON(T)}),hH=bM({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,$,M){let f=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,K=YT(T,k,$),w=kT(T,K);T.logger.info("\uD83D\uDC41","atom",X.key,`${$} can see`,{viewAtoms:k,resourceAtoms:X,userView:w});for(let z of w){let O=z.type==="mutable_atom"?PT(T,z):z,Q=kT(T,O);F.push(O,Q)}}let W=nT(T)?T.transactionMeta.epoch.get(f)??null:null;M?.emit(`continuity-init:${f}`,W,F)}}function Wk(T,S,$){let M=S.key;return function f(J){T.logger.info("\uD83D\uDECE\uFE0F","continuity",M,"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(w){if(w instanceof Error)T.logger.error("\u274C","continuity",M,`failed to run transaction ${F} from ${$} with update ${W}`,w.message)}performance.mark(X);let K=performance.measure(A,k,X);T?.logger.info("\uD83D\uDE80","transaction",F,W,$,K.duration)}}function Ak(T,S,$,M){let f=S.key;return function J(F){if(T.logger.info("\uD83D\uDC4D","continuity",f,`${$} acknowledged epoch ${F}`),M[0]?.epoch===F)ZT(T,mM,$,(A)=>{return A.shift(),T.logger.info("\uD83D\uDC4D","continuity",f,`${$} unacknowledged update queue now has`,A.length,"items"),A})}}function kk(T,S,$,M){let f=S.key,J=[];for(let F of S.actions){let W=M0(F,(A)=>{try{let k=S.globals.map((w)=>{if(w.type==="atom")return w.key;return z$(w).key}).concat(S.perspectives.flatMap((w)=>{let{viewAtoms:z}=w,O=YT(T,z,$);return kT(T,O).map((D)=>{return D.type==="mutable_atom"?"*"+D.key:D.key})})),X=Y0(k,A.updates),K={...A,updates:X};ZT(T,mM,$,(w)=>{if(K)w.push(K),w.sort((z,O)=>z.epoch-O.epoch),T.logger.info("\uD83D\uDC4D","continuity",f,`${$} unacknowledged update queue now has`,w.length,"items");return w}),M?.emit(`tx-new:${f}`,K)}catch(k){if(k instanceof Error)T.logger.error("\u274C","continuity",f,`${$} failed to send update from transaction ${F.key} to ${$}`,k.message)}},`sync-continuity:${f}:${$}`,T);J.push(W)}return J}function Xk(T,S,$,M){let f=S.key,J=[];for(let F of S.perspectives){let{viewAtoms:W}=F,A=YT(T,W,$),k=KS(A,({oldValue:X,newValue:K})=>{let w=X.map((D)=>D.key),z=K.map((D)=>D.key),O=X.filter((D)=>!z.includes(D.key)),Q=K.filter((D)=>!w.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:w,newKeys:z,revealed:Q,concealed:O}),Q.length>0)M?.emit(`reveal:${f}`,Q);if(O.length>0)M?.emit(`conceal:${f}`,O)},`sync-continuity:${f}:${$}:perspective:${F.resourceAtoms.key}`,T);J.push(k)}return J}function YE({socket:T,store:S=WT.STORE}){return function $(M){let f=T,J=M.key,F=kF(y0,`socket::${f.id}`,S).userKeyOfSocket,W=kT(S,F);if(!W)return S.logger.error("\u274C","continuity",J,`Tried to create a synchronizer for a socket (${f.id}) that is not connected to a user.`),()=>{};let A=kF(y0,W,S).socketKeyOfUser,k=KS(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);f=kT(S,L);for(let C of X)f?.emit(`tx-new:${J}`,C)},`sync-continuity:${J}:${W}`,S),X=kT(S,mM,W),K=[],w=Xk(S,M,W,f),z=kk(S,M,W,f);K.push(...w,...z);let O=Fk(S,M,W,T);f.off(`get:${J}`,O),f.on(`get:${J}`,O);let Q=Wk(S,M,W);f.off(`tx-run:${J}`,Q),f.on(`tx-run:${J}`,Q);let D=Ak(S,M,W,X);return f?.on(`ack:${J}`,D),()=>{for(let B of K)B();f?.off(`ack:${J}`,D),f?.off(`get:${J}`,O),f?.off(`tx-run:${J}`,Q)}}}var wk=Symbol("Let zodToJsonSchema decide on which parser to use"),Kk={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"?{...Kk,name:T}:{...Kk,...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(([M,f])=>[f._def,{def:f._def,path:[...S.basePath,S.definitionPath,M],jsonSchema:void 0}]))}};function R0(T,S,$,M){if(!M?.errorMessages)return;if($)T.errorMessage={...T.errorMessage,[S]:$}}function KT(T,S,$,M,f){T[S]=$,R0(T,S,M,f)}var yT;(function(T){T.assertEqual=(f)=>f;function S(f){}T.assertIs=S;function $(f){throw new Error}T.assertNever=$,T.arrayToEnum=(f)=>{let J={};for(let F of f)J[F]=F;return J},T.getValidEnumValues=(f)=>{let J=T.objectKeys(f).filter((W)=>typeof f[f[W]]!=="number"),F={};for(let W of J)F[W]=f[W];return T.objectValues(F)},T.objectValues=(f)=>{return T.objectKeys(f).map(function(J){return f[J]})},T.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{let J=[];for(let F in f)if(Object.prototype.hasOwnProperty.call(f,F))J.push(F);return J},T.find=(f,J)=>{for(let F of f)if(J(F))return F;return},T.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&isFinite(f)&&Math.floor(f)===f;function M(f,J=" | "){return f.map((F)=>typeof F==="string"?`'${F}'`:F).join(J)}T.joinValues=M,T.jsonStringifyReplacer=(f,J)=>{if(typeof J==="bigint")return J.toString();return J}})(yT||(yT={}));var G0;(function(T){T.mergeShapes=(S,$)=>{return{...S,...$}}})(G0||(G0={}));var g=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 g.undefined;case"string":return g.string;case"number":return isNaN(T)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":if(Array.isArray(T))return g.array;if(T===null)return g.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return g.promise;if(typeof Map!=="undefined"&&T instanceof Map)return g.map;if(typeof Set!=="undefined"&&T instanceof Set)return g.set;if(typeof Date!=="undefined"&&T instanceof Date)return g.date;return g.object;default:return g.unknown}},j=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"]),bw=(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(f){return f.message},$={_errors:[]},M=(f)=>{for(let J of f.issues)if(J.code==="invalid_union")J.unionErrors.map(M);else if(J.code==="invalid_return_type")M(J.returnTypeError);else if(J.code==="invalid_arguments")M(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 M(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 M of this.issues)if(M.path.length>0)S[M.path[0]]=S[M.path[0]]||[],S[M.path[0]].push(T(M));else $.push(T(M));return{formErrors:$,fieldErrors:S}}get formErrors(){return this.flatten()}}LS.create=(T)=>{return new LS(T)};var nM=(T,S)=>{let $;switch(T.code){case j.invalid_type:if(T.received===g.undefined)$="Required";else $=`Expected ${T.expected}, received ${T.received}`;break;case j.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(T.expected,yT.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:$=`Unrecognized key(s) in object: ${yT.joinValues(T.keys,", ")}`;break;case j.invalid_union:$="Invalid input";break;case j.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${yT.joinValues(T.options)}`;break;case j.invalid_enum_value:$=`Invalid enum value. Expected ${yT.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 yT.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,yT.assertNever(T)}return{message:$}},Gk=nM;function Zw(T){Gk=T}function wF(){return Gk}var YF=(T)=>{let{data:S,path:$,errorMaps:M,issueData:f}=T,J=[...$,...f.path||[]],F={...f,path:J};if(f.message!==void 0)return{...f,path:J,message:f.message};let W="",A=M.filter((k)=>!!k).slice().reverse();for(let k of A)W=k(F,{data:S,defaultError:W}).message;return{...f,path:J,message:W}},qw=[];function P(T,S){let $=wF(),M=YF({issueData:S,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$,$===nM?void 0:nM].filter((f)=>!!f)});T.common.issues.push(M)}class wS{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 M of S){if(M.status==="aborted")return ST;if(M.status==="dirty")T.dirty();$.push(M.value)}return{status:T.value,value:$}}static async mergeObjectAsync(T,S){let $=[];for(let M of S){let f=await M.key,J=await M.value;$.push({key:f,value:J})}return wS.mergeObjectSync(T,$)}static mergeObjectSync(T,S){let $={};for(let M of S){let{key:f,value:J}=M;if(f.status==="aborted")return ST;if(J.status==="aborted")return ST;if(f.status==="dirty")T.dirty();if(J.status==="dirty")T.dirty();if(f.value!=="__proto__"&&(typeof J.value!=="undefined"||M.alwaysSet))$[f.value]=J.value}return{status:T.value,value:$}}}var ST=Object.freeze({status:"aborted"}),vM=(T)=>({status:"dirty",value:T}),GS=(T)=>({status:"valid",value:T}),z0=(T)=>T.status==="aborted",_0=(T)=>T.status==="dirty",cf=(T)=>T.status==="valid",of=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function yF(T,S,$,M){if($==="a"&&!M)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?M:$==="a"?M.call(T):M?M.value:S.get(T)}function zk(T,S,$,M,f){if(M==="m")throw new TypeError("Private method is not writable");if(M==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return M==="a"?f.call(T,$):f?f.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 Pf,nf;class rS{constructor(T,S,$,M){this._cachedPath=[],this.parent=T,this.data=S,this._path=$,this._key=M}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 Rk=(T,S)=>{if(cf(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:M,description:f}=T;if(S&&($||M))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(S)return{errorMap:S,description:f};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:M)!==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:f}}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 wS,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(of(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 M={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)},f=this._parseSync({data:T,path:M.path,parent:M});return Rk(M,f)}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)},M=this._parse({data:T,path:$.path,parent:$}),f=await(of(M)?M:Promise.resolve(M));return Rk($,f)}refine(T,S){let $=(M)=>{if(typeof S==="string"||typeof S==="undefined")return{message:S};else if(typeof S==="function")return S(M);else return S};return this._refinement((M,f)=>{let J=T(M),F=()=>f.addIssue({code:j.custom,...$(M)});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(($,M)=>{if(!T($))return M.addIssue(typeof S==="function"?S($,M):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 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 MM.create(this,this._def)}or(T){return tM.create([this,T],this._def)}and(T){return pM.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 lM({...fT(this._def),innerType:this,defaultValue:S,typeName:x.ZodDefault})}brand(){return new OF({typeName:x.ZodBranded,type:this,...fT(this._def)})}catch(T){let S=typeof T==="function"?T:()=>T;return new rM({...fT(this._def),innerType:this,catchValue:S,typeName:x.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return lf.create(this,T)}readonly(){return aM.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var mw=/^c[^\s-]{8,}$/i,hw=/^[0-9a-z]+$/,vw=/^[0-9A-HJKMNP-TV-Z]{26}$/,Pw=/^[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,nw=/^[a-z0-9_-]{21}$/i,cw=/^[-+]?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)?)??$/,ow=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",O0,tw=/^(?:(?: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])$/,pw=/^(([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})))$/,iw=/^([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])))",dw=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 uw(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 lw(T,S){if((S==="v4"||!S)&&tw.test(T))return!0;if((S==="v6"||!S)&&pw.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)!==g.string){let f=this._getOrReturnCtx(T);return P(f,{code:j.invalid_type,expected:g.string,received:f.parsedType}),ST}let $=new wS,M=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(T.data.length<f.value)M=this._getOrReturnCtx(T,M),P(M,{code:j.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),$.dirty()}else if(f.kind==="max"){if(T.data.length>f.value)M=this._getOrReturnCtx(T,M),P(M,{code:j.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),$.dirty()}else if(f.kind==="length"){let J=T.data.length>f.value,F=T.data.length<f.value;if(J||F){if(M=this._getOrReturnCtx(T,M),J)P(M,{code:j.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(F)P(M,{code:j.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});$.dirty()}}else if(f.kind==="email"){if(!ow.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"email",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="emoji"){if(!O0)O0=new RegExp(gw,"u");if(!O0.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"emoji",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="uuid"){if(!Pw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"uuid",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="nanoid"){if(!nw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"nanoid",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="cuid"){if(!mw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"cuid",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="cuid2"){if(!hw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"cuid2",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="ulid"){if(!vw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"ulid",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="url")try{new URL(T.data)}catch(J){M=this._getOrReturnCtx(T,M),P(M,{validation:"url",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"regex",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="trim")T.data=T.data.trim();else if(f.kind==="includes"){if(!T.data.includes(f.value,f.position))M=this._getOrReturnCtx(T,M),P(M,{code:j.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),$.dirty()}else if(f.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(f.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(f.kind==="startsWith"){if(!T.data.startsWith(f.value))M=this._getOrReturnCtx(T,M),P(M,{code:j.invalid_string,validation:{startsWith:f.value},message:f.message}),$.dirty()}else if(f.kind==="endsWith"){if(!T.data.endsWith(f.value))M=this._getOrReturnCtx(T,M),P(M,{code:j.invalid_string,validation:{endsWith:f.value},message:f.message}),$.dirty()}else if(f.kind==="datetime"){if(!Ek(f).test(T.data))M=this._getOrReturnCtx(T,M),P(M,{code:j.invalid_string,validation:"datetime",message:f.message}),$.dirty()}else if(f.kind==="date"){if(!dw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{code:j.invalid_string,validation:"date",message:f.message}),$.dirty()}else if(f.kind==="time"){if(!uw(f).test(T.data))M=this._getOrReturnCtx(T,M),P(M,{code:j.invalid_string,validation:"time",message:f.message}),$.dirty()}else if(f.kind==="duration"){if(!cw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"duration",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="ip"){if(!lw(T.data,f.version))M=this._getOrReturnCtx(T,M),P(M,{validation:"ip",code:j.invalid_string,message:f.message}),$.dirty()}else if(f.kind==="base64"){if(!iw.test(T.data))M=this._getOrReturnCtx(T,M),P(M,{validation:"base64",code:j.invalid_string,message:f.message}),$.dirty()}else yT.assertNever(f);return{status:$.value,value:T.data}}_regex(T,S,$){return this.refinement((M)=>T.test(M),{validation:S,code:j.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:x.ZodString,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...fT(T)})};function rw(T,S){let $=(T.toString().split(".")[1]||"").length,M=(S.toString().split(".")[1]||"").length,f=$>M?$:M,J=parseInt(T.toFixed(f).replace(".","")),F=parseInt(S.toFixed(f).replace(".",""));return J%F/Math.pow(10,f)}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)!==g.number){let f=this._getOrReturnCtx(T);return P(f,{code:j.invalid_type,expected:g.number,received:f.parsedType}),ST}let $=void 0,M=new wS;for(let f of this._def.checks)if(f.kind==="int"){if(!yT.isInteger(T.data))$=this._getOrReturnCtx(T,$),P($,{code:j.invalid_type,expected:"integer",received:"float",message:f.message}),M.dirty()}else if(f.kind==="min"){if(f.inclusive?T.data<f.value:T.data<=f.value)$=this._getOrReturnCtx(T,$),P($,{code:j.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),M.dirty()}else if(f.kind==="max"){if(f.inclusive?T.data>f.value:T.data>=f.value)$=this._getOrReturnCtx(T,$),P($,{code:j.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),M.dirty()}else if(f.kind==="multipleOf"){if(rw(T.data,f.value)!==0)$=this._getOrReturnCtx(T,$),P($,{code:j.not_multiple_of,multipleOf:f.value,message:f.message}),M.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(T.data))$=this._getOrReturnCtx(T,$),P($,{code:j.not_finite,message:f.message}),M.dirty()}else yT.assertNever(f);return{status:M.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,$,M){return new c$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:d.toString(M)}]})}_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:x.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...fT(T)})};class o$ 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)!==g.bigint){let f=this._getOrReturnCtx(T);return P(f,{code:j.invalid_type,expected:g.bigint,received:f.parsedType}),ST}let $=void 0,M=new wS;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?T.data<f.value:T.data<=f.value)$=this._getOrReturnCtx(T,$),P($,{code:j.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),M.dirty()}else if(f.kind==="max"){if(f.inclusive?T.data>f.value:T.data>=f.value)$=this._getOrReturnCtx(T,$),P($,{code:j.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),M.dirty()}else if(f.kind==="multipleOf"){if(T.data%f.value!==BigInt(0))$=this._getOrReturnCtx(T,$),P($,{code:j.not_multiple_of,multipleOf:f.value,message:f.message}),M.dirty()}else yT.assertNever(f);return{status:M.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,$,M){return new o$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:d.toString(M)}]})}_addCheck(T){return new o$({...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}}o$.create=(T)=>{var S;return new o$({checks:[],typeName:x.ZodBigInt,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...fT(T)})};class cM extends JT{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==g.boolean){let $=this._getOrReturnCtx(T);return P($,{code:j.invalid_type,expected:g.boolean,received:$.parsedType}),ST}return GS(T.data)}}cM.create=(T)=>{return new cM({typeName:x.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...fT(T)})};class TM extends JT{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==g.date){let f=this._getOrReturnCtx(T);return P(f,{code:j.invalid_type,expected:g.date,received:f.parsedType}),ST}if(isNaN(T.data.getTime())){let f=this._getOrReturnCtx(T);return P(f,{code:j.invalid_date}),ST}let $=new wS,M=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(T.data.getTime()<f.value)M=this._getOrReturnCtx(T,M),P(M,{code:j.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),$.dirty()}else if(f.kind==="max"){if(T.data.getTime()>f.value)M=this._getOrReturnCtx(T,M),P(M,{code:j.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),$.dirty()}else yT.assertNever(f);return{status:$.value,value:new Date(T.data.getTime())}}_addCheck(T){return new TM({...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}}TM.create=(T)=>{return new TM({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:x.ZodDate,...fT(T)})};class gf extends JT{_parse(T){if(this._getType(T)!==g.symbol){let $=this._getOrReturnCtx(T);return P($,{code:j.invalid_type,expected:g.symbol,received:$.parsedType}),ST}return GS(T.data)}}gf.create=(T)=>{return new gf({typeName:x.ZodSymbol,...fT(T)})};class oM extends JT{_parse(T){if(this._getType(T)!==g.undefined){let $=this._getOrReturnCtx(T);return P($,{code:j.invalid_type,expected:g.undefined,received:$.parsedType}),ST}return GS(T.data)}}oM.create=(T)=>{return new oM({typeName:x.ZodUndefined,...fT(T)})};class gM extends JT{_parse(T){if(this._getType(T)!==g.null){let $=this._getOrReturnCtx(T);return P($,{code:j.invalid_type,expected:g.null,received:$.parsedType}),ST}return GS(T.data)}}gM.create=(T)=>{return new gM({typeName:x.ZodNull,...fT(T)})};class SM extends JT{constructor(){super(...arguments);this._any=!0}_parse(T){return GS(T.data)}}SM.create=(T)=>{return new SM({typeName:x.ZodAny,...fT(T)})};class n$ extends JT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return GS(T.data)}}n$.create=(T)=>{return new n$({typeName:x.ZodUnknown,...fT(T)})};class W$ extends JT{_parse(T){let S=this._getOrReturnCtx(T);return P(S,{code:j.invalid_type,expected:g.never,received:S.parsedType}),ST}}W$.create=(T)=>{return new W$({typeName:x.ZodNever,...fT(T)})};class tf extends JT{_parse(T){if(this._getType(T)!==g.undefined){let $=this._getOrReturnCtx(T);return P($,{code:j.invalid_type,expected:g.void,received:$.parsedType}),ST}return GS(T.data)}}tf.create=(T)=>{return new tf({typeName:x.ZodVoid,...fT(T)})};class uS extends JT{_parse(T){let{ctx:S,status:$}=this._processInputParams(T),M=this._def;if(S.parsedType!==g.array)return P(S,{code:j.invalid_type,expected:g.array,received:S.parsedType}),ST;if(M.exactLength!==null){let J=S.data.length>M.exactLength.value,F=S.data.length<M.exactLength.value;if(J||F)P(S,{code:J?j.too_big:j.too_small,minimum:F?M.exactLength.value:void 0,maximum:J?M.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:M.exactLength.message}),$.dirty()}if(M.minLength!==null){if(S.data.length<M.minLength.value)P(S,{code:j.too_small,minimum:M.minLength.value,type:"array",inclusive:!0,exact:!1,message:M.minLength.message}),$.dirty()}if(M.maxLength!==null){if(S.data.length>M.maxLength.value)P(S,{code:j.too_big,maximum:M.maxLength.value,type:"array",inclusive:!0,exact:!1,message:M.maxLength.message}),$.dirty()}if(S.common.async)return Promise.all([...S.data].map((J,F)=>{return M.type._parseAsync(new rS(S,J,S.path,F))})).then((J)=>{return wS.mergeArray($,J)});let f=[...S.data].map((J,F)=>{return M.type._parseSync(new rS(S,J,S.path,F))});return wS.mergeArray($,f)}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:x.ZodArray,...fT(S)})};function hM(T){if(T instanceof qT){let S={};for(let $ in T.shape){let M=T.shape[$];S[$]=lS.create(hM(M))}return new qT({...T._def,shape:()=>S})}else if(T instanceof uS)return new uS({...T._def,type:hM(T.element)});else if(T instanceof lS)return lS.create(hM(T.unwrap()));else if(T instanceof H$)return H$.create(hM(T.unwrap()));else if(T instanceof A$)return A$.create(T.items.map((S)=>hM(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)!==g.object){let A=this._getOrReturnCtx(T);return P(A,{code:j.invalid_type,expected:g.object,received:A.parsedType}),ST}let{status:$,ctx:M}=this._processInputParams(T),{shape:f,keys:J}=this._getCached(),F=[];if(!(this._def.catchall instanceof W$&&this._def.unknownKeys==="strip")){for(let A in M.data)if(!J.includes(A))F.push(A)}let W=[];for(let A of J){let k=f[A],X=M.data[A];W.push({key:{status:"valid",value:A},value:k._parse(new rS(M,X,M.path,A)),alwaysSet:A in M.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:M.data[k]}});else if(A==="strict"){if(F.length>0)P(M,{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=M.data[k];W.push({key:{status:"valid",value:k},value:A._parse(new rS(M,X,M.path,k)),alwaysSet:k in M.data})}}if(M.common.async)return Promise.resolve().then(async()=>{let A=[];for(let k of W){let X=await k.key,K=await k.value;A.push({key:X,value:K,alwaysSet:k.alwaysSet})}return A}).then((A)=>{return wS.mergeObjectSync($,A)});else return wS.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 M,f,J,F;let W=(J=(f=(M=this._def).errorMap)===null||f===void 0?void 0:f.call(M,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:x.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 hM(this)}partial(T){let S={};return yT.objectKeys(this.shape).forEach(($)=>{let M=this.shape[$];if(T&&!T[$])S[$]=M;else S[$]=M.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 f=this.shape[$];while(f instanceof lS)f=f._def.innerType;S[$]=f}}),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:x.ZodObject,...fT(S)})};qT.strictCreate=(T,S)=>{return new qT({shape:()=>T,unknownKeys:"strict",catchall:W$.create(),typeName:x.ZodObject,...fT(S)})};qT.lazycreate=(T,S)=>{return new qT({shape:T,unknownKeys:"strip",catchall:W$.create(),typeName:x.ZodObject,...fT(S)})};class tM extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$=this._def.options;function M(f){for(let F of f)if(F.result.status==="valid")return F.result;for(let F of f)if(F.result.status==="dirty")return S.common.issues.push(...F.ctx.common.issues),F.result;let J=f.map((F)=>new LS(F.ctx.common.issues));return P(S,{code:j.invalid_union,unionErrors:J}),ST}if(S.common.async)return Promise.all($.map(async(f)=>{let J={...S,common:{...S.common,issues:[]},parent:null};return{result:await f._parseAsync({data:S.data,path:S.path,parent:J}),ctx:J}})).then(M);else{let f=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"&&!f)f={result:k,ctx:A};if(A.common.issues.length)J.push(A.common.issues)}if(f)return S.common.issues.push(...f.ctx.common.issues),f.result;let F=J.map((W)=>new LS(W));return P(S,{code:j.invalid_union,unionErrors:F}),ST}}get options(){return this._def.options}}tM.create=(T,S)=>{return new tM({options:T,typeName:x.ZodUnion,...fT(S)})};var _$=(T)=>{if(T instanceof iM)return _$(T.schema);else if(T instanceof hS)return _$(T.innerType());else if(T instanceof dM)return[T.value];else if(T instanceof g$)return T.options;else if(T instanceof uM)return yT.objectValues(T.enum);else if(T instanceof lM)return _$(T._def.innerType);else if(T instanceof oM)return[void 0];else if(T instanceof gM)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 OF)return _$(T.unwrap());else if(T instanceof aM)return _$(T.unwrap());else if(T instanceof rM)return _$(T._def.innerType);else return[]};class RF extends JT{_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==g.object)return P(S,{code:j.invalid_type,expected:g.object,received:S.parsedType}),ST;let $=this.discriminator,M=S.data[$],f=this.optionsMap.get(M);if(!f)return P(S,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),ST;if(S.common.async)return f._parseAsync({data:S.data,path:S.path,parent:S});else return f._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 M=new Map;for(let f of S){let J=_$(f.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(M.has(F))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String(F)}`);M.set(F,f)}}return new RF({typeName:x.ZodDiscriminatedUnion,discriminator:T,options:S,optionsMap:M,...fT($)})}}function H0(T,S){let $=P$(T),M=P$(S);if(T===S)return{valid:!0,data:T};else if($===g.object&&M===g.object){let f=yT.objectKeys(S),J=yT.objectKeys(T).filter((W)=>f.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($===g.array&&M===g.array){if(T.length!==S.length)return{valid:!1};let f=[];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};f.push(A.data)}return{valid:!0,data:f}}else if($===g.date&&M===g.date&&+T===+S)return{valid:!0,data:T};else return{valid:!1}}class pM extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T),M=(f,J)=>{if(z0(f)||z0(J))return ST;let F=H0(f.value,J.value);if(!F.valid)return P($,{code:j.invalid_intersection_types}),ST;if(_0(f)||_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(([f,J])=>M(f,J));else return M(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}pM.create=(T,S,$)=>{return new pM({left:T,right:S,typeName:x.ZodIntersection,...fT($)})};class A$ extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==g.array)return P($,{code:j.invalid_type,expected:g.array,received:$.parsedType}),ST;if($.data.length<this._def.items.length)return P($,{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)P($,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.dirty();let f=[...$.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(f).then((J)=>{return wS.mergeArray(S,J)});else return wS.mergeArray(S,f)}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:x.ZodTuple,rest:null,...fT(S)})};class pf 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!==g.object)return P($,{code:j.invalid_type,expected:g.object,received:$.parsedType}),ST;let M=[],f=this._def.keyType,J=this._def.valueType;for(let F in $.data)M.push({key:f._parse(new rS($,F,$.path,F)),value:J._parse(new rS($,$.data[F],$.path,F)),alwaysSet:F in $.data});if($.common.async)return wS.mergeObjectAsync(S,M);else return wS.mergeObjectSync(S,M)}get element(){return this._def.valueType}static create(T,S,$){if(S instanceof JT)return new pf({keyType:T,valueType:S,typeName:x.ZodRecord,...fT($)});return new pf({keyType:dS.create(),valueType:T,typeName:x.ZodRecord,...fT(S)})}}class df 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!==g.map)return P($,{code:j.invalid_type,expected:g.map,received:$.parsedType}),ST;let M=this._def.keyType,f=this._def.valueType,J=[...$.data.entries()].map(([F,W],A)=>{return{key:M._parse(new rS($,F,$.path,[A,"key"])),value:f._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}}}}df.create=(T,S,$)=>{return new df({valueType:S,keyType:T,typeName:x.ZodMap,...fT($)})};class $M extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==g.set)return P($,{code:j.invalid_type,expected:g.set,received:$.parsedType}),ST;let M=this._def;if(M.minSize!==null){if($.data.size<M.minSize.value)P($,{code:j.too_small,minimum:M.minSize.value,type:"set",inclusive:!0,exact:!1,message:M.minSize.message}),S.dirty()}if(M.maxSize!==null){if($.data.size>M.maxSize.value)P($,{code:j.too_big,maximum:M.maxSize.value,type:"set",inclusive:!0,exact:!1,message:M.maxSize.message}),S.dirty()}let f=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)=>f._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 $M({...this._def,minSize:{value:T,message:d.toString(S)}})}max(T,S){return new $M({...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)}}$M.create=(T,S)=>{return new $M({valueType:T,minSize:null,maxSize:null,typeName:x.ZodSet,...fT(S)})};class PM extends JT{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==g.function)return P(S,{code:j.invalid_type,expected:g.function,received:S.parsedType}),ST;function $(F,W){return YF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,wF(),nM].filter((A)=>!!A),issueData:{code:j.invalid_arguments,argumentsError:W}})}function M(F,W){return YF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,wF(),nM].filter((A)=>!!A),issueData:{code:j.invalid_return_type,returnTypeError:W}})}let f={errorMap:S.common.contextualErrorMap},J=S.data;if(this._def.returns instanceof MM){let F=this;return GS(async function(...W){let A=new LS([]),k=await F._def.args.parseAsync(W,f).catch((w)=>{throw A.addIssue($(W,w)),A}),X=await Reflect.apply(J,this,k);return await F._def.returns._def.type.parseAsync(X,f).catch((w)=>{throw A.addIssue(M(X,w)),A})})}else{let F=this;return GS(function(...W){let A=F._def.args.safeParse(W,f);if(!A.success)throw new LS([$(W,A.error)]);let k=Reflect.apply(J,this,A.data),X=F._def.returns.safeParse(k,f);if(!X.success)throw new LS([M(k,X.error)]);return X.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new PM({...this._def,args:A$.create(T).rest(n$.create())})}returns(T){return new PM({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,S,$){return new PM({args:T?T:A$.create([]).rest(n$.create()),returns:S||n$.create(),typeName:x.ZodFunction,...fT($)})}}class iM 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})}}iM.create=(T,S)=>{return new iM({getter:T,typeName:x.ZodLazy,...fT(S)})};class dM extends JT{_parse(T){if(T.data!==this._def.value){let S=this._getOrReturnCtx(T);return P(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}}dM.create=(T,S)=>{return new dM({value:T,typeName:x.ZodLiteral,...fT(S)})};function Dk(T,S){return new g$({values:T,typeName:x.ZodEnum,...fT(S)})}class g$ extends JT{constructor(){super(...arguments);Pf.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:j.invalid_type}),ST}if(!yF(this,Pf,"f"))zk(this,Pf,new Set(this._def.values),"f");if(!yF(this,Pf,"f").has(T.data)){let S=this._getOrReturnCtx(T),$=this._def.values;return P(S,{received:S.data,code:j.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 g$.create(T,{...this._def,...S})}exclude(T,S=this._def){return g$.create(this.options.filter(($)=>!T.includes($)),{...this._def,...S})}}Pf=new WeakMap;g$.create=Dk;class uM extends JT{constructor(){super(...arguments);nf.set(this,void 0)}_parse(T){let S=yT.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(T);if($.parsedType!==g.string&&$.parsedType!==g.number){let M=yT.objectValues(S);return P($,{expected:yT.joinValues(M),received:$.parsedType,code:j.invalid_type}),ST}if(!yF(this,nf,"f"))zk(this,nf,new Set(yT.getValidEnumValues(this._def.values)),"f");if(!yF(this,nf,"f").has(T.data)){let M=yT.objectValues(S);return P($,{received:$.data,code:j.invalid_enum_value,options:M}),ST}return GS(T.data)}get enum(){return this._def.values}}nf=new WeakMap;uM.create=(T,S)=>{return new uM({values:T,typeName:x.ZodNativeEnum,...fT(S)})};class MM extends JT{unwrap(){return this._def.type}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==g.promise&&S.common.async===!1)return P(S,{code:j.invalid_type,expected:g.promise,received:S.parsedType}),ST;let $=S.parsedType===g.promise?S.data:Promise.resolve(S.data);return GS($.then((M)=>{return this._def.type.parseAsync(M,{path:S.path,errorMap:S.common.contextualErrorMap})}))}}MM.create=(T,S)=>{return new MM({type:T,typeName:x.ZodPromise,...fT(S)})};class hS extends JT{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),M=this._def.effect||null,f={addIssue:(J)=>{if(P($,J),J.fatal)S.abort();else S.dirty()},get path(){return $.path}};if(f.addIssue=f.addIssue.bind(f),M.type==="preprocess"){let J=M.transform($.data,f);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 vM(W.value);if(S.value==="dirty")return vM(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 vM(F.value);if(S.value==="dirty")return vM(F.value);return F}}if(M.type==="refinement"){let J=(F)=>{let W=M.refinement(F,f);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(M.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!cf(J))return J;let F=M.transform(J.value,f);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(!cf(J))return J;return Promise.resolve(M.transform(J.value,f)).then((F)=>({status:S.value,value:F}))});yT.assertNever(M)}}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 lS extends JT{_parse(T){if(this._getType(T)===g.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:x.ZodOptional,...fT(S)})};class H$ extends JT{_parse(T){if(this._getType(T)===g.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:x.ZodNullable,...fT(S)})};class lM extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$=S.data;if(S.parsedType===g.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:S.path,parent:S})}removeDefault(){return this._def.innerType}}lM.create=(T,S)=>{return new lM({innerType:T,typeName:x.ZodDefault,defaultValue:typeof S.default==="function"?S.default:()=>S.default,...fT(S)})};class rM extends JT{_parse(T){let{ctx:S}=this._processInputParams(T),$={...S,common:{...S.common,issues:[]}},M=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(of(M))return M.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new LS($.common.issues)},input:$.data})}});else return{status:"valid",value:M.status==="valid"?M.value:this._def.catchValue({get error(){return new LS($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}rM.create=(T,S)=>{return new rM({innerType:T,typeName:x.ZodCatch,catchValue:typeof S.catch==="function"?S.catch:()=>S.catch,...fT(S)})};class uf extends JT{_parse(T){if(this._getType(T)!==g.nan){let $=this._getOrReturnCtx(T);return P($,{code:j.invalid_type,expected:g.nan,received:$.parsedType}),ST}return{status:"valid",value:T.data}}}uf.create=(T)=>{return new uf({typeName:x.ZodNaN,...fT(T)})};var aw=Symbol("zod_brand");class OF 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 lf extends JT{_parse(T){let{status:S,ctx:$}=this._processInputParams(T);if($.common.async)return(async()=>{let f=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(f.status==="aborted")return ST;if(f.status==="dirty")return S.dirty(),vM(f.value);else return this._def.out._parseAsync({data:f.value,path:$.path,parent:$})})();else{let M=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(M.status==="aborted")return ST;if(M.status==="dirty")return S.dirty(),{status:"dirty",value:M.value};else return this._def.out._parseSync({data:M.value,path:$.path,parent:$})}}static create(T,S){return new lf({in:T,out:S,typeName:x.ZodPipeline})}}class aM extends JT{_parse(T){let S=this._def.innerType._parse(T),$=(M)=>{if(cf(M))M.value=Object.freeze(M.value);return M};return of(S)?S.then((M)=>$(M)):$(S)}unwrap(){return this._def.innerType}}aM.create=(T,S)=>{return new aM({innerType:T,typeName:x.ZodReadonly,...fT(S)})};function Qk(T,S={},$){if(T)return SM.create().superRefine((M,f)=>{var J,F;if(!T(M)){let W=typeof S==="function"?S(M):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;f.addIssue({code:"custom",...k,fatal:A})}});return SM.create()}var ew={object:qT.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 sw=(T,S={message:`Input not instance of ${T.name}`})=>Qk(($)=>$ instanceof T,S),Uk=dS.create,Vk=c$.create,T6=uf.create,S6=o$.create,Bk=cM.create,$6=TM.create,M6=gf.create,f6=oM.create,J6=gM.create,F6=SM.create,W6=n$.create,A6=W$.create,k6=tf.create,X6=uS.create,rf=qT.create,K6=qT.strictCreate,w6=tM.create,Y6=RF.create,y6=pM.create,R6=A$.create,O6=pf.create,G6=df.create,z6=$M.create,_6=PM.create,H6=iM.create,E6=dM.create,D6=g$.create,Q6=uM.create,U6=MM.create,Ok=hS.create,V6=lS.create,B6=H$.create,L6=hS.createWithPreprocess,N6=lf.create,C6=()=>Uk().optional(),x6=()=>Vk().optional(),j6=()=>Bk().optional(),I6={string:(T)=>dS.create({...T,coerce:!0}),number:(T)=>c$.create({...T,coerce:!0}),boolean:(T)=>cM.create({...T,coerce:!0}),bigint:(T)=>o$.create({...T,coerce:!0}),date:(T)=>TM.create({...T,coerce:!0})},b6=ST,zT=Object.freeze({__proto__:null,defaultErrorMap:nM,setErrorMap:Zw,getErrorMap:wF,makeIssue:YF,EMPTY_PATH:qw,addIssueToContext:P,ParseStatus:wS,INVALID:ST,DIRTY:vM,OK:GS,isAborted:z0,isDirty:_0,isValid:cf,isAsync:of,get util(){return yT},get objectUtil(){return G0},ZodParsedType:g,getParsedType:P$,ZodType:JT,datetimeRegex:Ek,ZodString:dS,ZodNumber:c$,ZodBigInt:o$,ZodBoolean:cM,ZodDate:TM,ZodSymbol:gf,ZodUndefined:oM,ZodNull:gM,ZodAny:SM,ZodUnknown:n$,ZodNever:W$,ZodVoid:tf,ZodArray:uS,ZodObject:qT,ZodUnion:tM,ZodDiscriminatedUnion:RF,ZodIntersection:pM,ZodTuple:A$,ZodRecord:pf,ZodMap:df,ZodSet:$M,ZodFunction:PM,ZodLazy:iM,ZodLiteral:dM,ZodEnum:g$,ZodNativeEnum:uM,ZodPromise:MM,ZodEffects:hS,ZodTransformer:hS,ZodOptional:lS,ZodNullable:H$,ZodDefault:lM,ZodCatch:rM,ZodNaN:uf,BRAND:aw,ZodBranded:OF,ZodPipeline:lf,ZodReadonly:aM,custom:Qk,Schema:JT,ZodSchema:JT,late:ew,get ZodFirstPartyTypeKind(){return x},coerce:I6,any:F6,array:X6,bigint:S6,boolean:Bk,date:$6,discriminatedUnion:Y6,effect:Ok,enum:D6,function:_6,instanceof:sw,intersection:y6,lazy:H6,literal:E6,map:G6,nan:T6,nativeEnum:Q6,never:A6,null:J6,nullable:B6,number:Vk,object:rf,oboolean:j6,onumber:x6,optional:V6,ostring:C6,pipeline:N6,preprocess:L6,promise:U6,record:O6,set:z6,strictObject:K6,string:Uk,symbol:M6,transformer:Ok,tuple:R6,undefined:f6,union:w6,unknown:W6,void:k6,NEVER:b6,ZodIssueCode:j,quotelessJson:bw,ZodError:LS});function Lk(){return{}}function Nk(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)KT($,"minItems",T.minLength.value,T.minLength.message,S);if(T.maxLength)KT($,"maxItems",T.maxLength.value,T.maxLength.message,S);if(T.exactLength)KT($,"minItems",T.exactLength.value,T.exactLength.message,S),KT($,"maxItems",T.exactLength.value,T.exactLength.message,S);return $}function Ck(T,S){let $={type:"integer",format:"int64"};if(!T.checks)return $;for(let M of T.checks)switch(M.kind){case"min":if(S.target==="jsonSchema7")if(M.inclusive)KT($,"minimum",M.value,M.message,S);else KT($,"exclusiveMinimum",M.value,M.message,S);else{if(!M.inclusive)$.exclusiveMinimum=!0;KT($,"minimum",M.value,M.message,S)}break;case"max":if(S.target==="jsonSchema7")if(M.inclusive)KT($,"maximum",M.value,M.message,S);else KT($,"exclusiveMaximum",M.value,M.message,S);else{if(!M.inclusive)$.exclusiveMaximum=!0;KT($,"maximum",M.value,M.message,S)}break;case"multipleOf":KT($,"multipleOf",M.value,M.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 M=$??S.dateStrategy;if(Array.isArray(M))return{anyOf:M.map((f,J)=>E0(T,S,f))};switch(M){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Z6(T,S)}}var Z6=(T,S)=>{let $={type:"integer",format:"unix-time"};if(S.target==="openApi3")return $;for(let M of T.checks)switch(M.kind){case"min":KT($,"minimum",M.value,M.message,S);break;case"max":KT($,"maximum",M.value,M.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 q6=(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),M=S.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,f=[];return $.forEach((J)=>{if(q6(J)){if(f.push(...J.allOf),J.unevaluatedProperties===void 0)M=void 0}else{let F=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...A}=J;F=A}else M=void 0;f.push(F)}}),f.length?{allOf:f,...M}: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,fM={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 M(f){return S.patternStrategy==="escape"?m6(f):f}if(T.checks)for(let f of T.checks)switch(f.kind){case"min":KT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,f.value):f.value,f.message,S);break;case"max":KT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,f.value):f.value,f.message,S);break;case"email":switch(S.emailStrategy){case"format:email":aS($,"email",f.message,S);break;case"format:idn-email":aS($,"idn-email",f.message,S);break;case"pattern:zod":eS($,fM.email,f.message,S);break}break;case"url":aS($,"uri",f.message,S);break;case"uuid":aS($,"uuid",f.message,S);break;case"regex":eS($,f.regex,f.message,S);break;case"cuid":eS($,fM.cuid,f.message,S);break;case"cuid2":eS($,fM.cuid2,f.message,S);break;case"startsWith":eS($,RegExp(`^${M(f.value)}`),f.message,S);break;case"endsWith":eS($,RegExp(`${M(f.value)}$`),f.message,S);break;case"datetime":aS($,"date-time",f.message,S);break;case"date":aS($,"date",f.message,S);break;case"time":aS($,"time",f.message,S);break;case"duration":aS($,"duration",f.message,S);break;case"length":KT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,f.value):f.value,f.message,S),KT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,f.value):f.value,f.message,S);break;case"includes":{eS($,RegExp(M(f.value)),f.message,S);break}case"ip":{if(f.version!=="v6")aS($,"ipv4",f.message,S);if(f.version!=="v4")aS($,"ipv6",f.message,S);break}case"emoji":eS($,fM.emoji,f.message,S);break;case"ulid":{eS($,fM.ulid,f.message,S);break}case"base64":{switch(S.base64Strategy){case"format:binary":{aS($,"binary",f.message,S);break}case"contentEncoding:base64":{KT($,"contentEncoding","base64",f.message,S);break}case"pattern:zod":{eS($,fM.base64,f.message,S);break}}break}case"nanoid":eS($,fM.nanoid,f.message,S);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(f)}return $}var m6=(T)=>Array.from(T).map((S)=>/[a-zA-Z0-9]/.test(S)?S:`\\${S}`).join(""),aS=(T,S,$,M)=>{if(T.format||T.anyOf?.some((f)=>f.format)){if(!T.anyOf)T.anyOf=[];if(T.format){if(T.anyOf.push({format:T.format,...T.errorMessage&&M.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,...$&&M.errorMessages&&{errorMessage:{format:$}}})}else KT(T,"format",S,$,M)},eS=(T,S,$,M)=>{if(T.pattern||T.allOf?.some((f)=>f.pattern)){if(!T.allOf)T.allOf=[];if(T.pattern){if(T.allOf.push({pattern:T.pattern,...T.errorMessage&&M.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,M),...$&&M.errorMessages&&{errorMessage:{pattern:$}}})}else KT(T,"pattern",hk(S,M),$,M)},hk=(T,S)=>{let $=typeof T==="function"?T():T;if(!S.applyRegexFlags||!$.flags)return $.source;let M={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},f=M.i?$.source.toLowerCase():$.source,J="",F=!1,W=!1,A=!1;for(let k=0;k<f.length;k++){if(F){J+=f[k],F=!1;continue}if(M.i){if(W){if(f[k].match(/[a-z]/)){if(A)J+=f[k],J+=`${f[k-2]}-${f[k]}`.toUpperCase(),A=!1;else if(f[k+1]==="-"&&f[k+2]?.match(/[a-z]/))J+=f[k],A=!0;else J+=`${f[k]}${f[k].toUpperCase()}`;continue}}else if(f[k].match(/[a-z]/)){J+=`[${f[k]}${f[k].toUpperCase()}]`;continue}}if(M.m){if(f[k]==="^"){J+=`(^|(?<=[\r
10
+ ]))`;continue}else if(f[k]==="$"){J+=`($|(?=[\r
11
+ ]))`;continue}}if(M.s&&f[k]==="."){J+=W?`${f[k]}\r
12
+ `:`[${f[k]}\r
13
+ ]`;continue}if(J+=f[k],f[k]==="\\")F=!0;else if(W&&f[k]==="]")W=!1;else if(!W&&f[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===x.ZodEnum)return{type:"object",required:T.keyType._def.values,properties:T.keyType._def.values.reduce((M,f)=>({...M,[f]:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"properties",f]})??{}}),{}),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:M,...f}=zF(T.keyType._def,S);return{...$,propertyNames:f}}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:M,...f}=GF(T.keyType._def,S);return{...$,propertyNames:f}}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"]})||{},M=s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[$,M],minItems:2,maxItems:2}}}function Pk(T){let S=T.values,M=Object.keys(T.values).filter((J)=>{return typeof S[S[J]]!=="number"}).map((J)=>S[J]),f=Array.from(new Set(M.map((J)=>typeof J)));return{type:f.length===1?f[0]==="string"?"string":"number":["string","number"],enum:M}}function nk(){return{not:{}}}function ck(T){return T.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var af={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gk(T,S){if(S.target==="openApi3")return ok(T,S);let $=T.options instanceof Map?Array.from(T.options.values()):T.options;if($.every((M)=>(M._def.typeName in af)&&(!M._def.checks||!M._def.checks.length))){let M=$.reduce((f,J)=>{let F=af[J._def.typeName];return F&&!f.includes(F)?[...f,F]:f},[]);return{type:M.length>1?M:M[0]}}else if($.every((M)=>M._def.typeName==="ZodLiteral"&&!M.description)){let M=$.reduce((f,J)=>{let F=typeof J._def.value;switch(F){case"string":case"number":case"boolean":return[...f,F];case"bigint":return[...f,"integer"];case"object":if(J._def.value===null)return[...f,"null"];case"symbol":case"undefined":case"function":default:return f}},[]);if(M.length===$.length){let f=M.filter((J,F,W)=>W.indexOf(J)===F);return{type:f.length>1?f:f[0],enum:$.reduce((J,F)=>{return J.includes(F._def.value)?J:[...J,F._def.value]},[])}}}else if($.every((M)=>M._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((M,f)=>[...M,...f._def.values.filter((J)=>!M.includes(J))],[])};return ok(T,S)}var ok=(T,S)=>{let $=(T.options instanceof Map?Array.from(T.options.values()):T.options).map((M,f)=>s(M._def,{...S,currentPath:[...S.currentPath,"anyOf",`${f}`]})).filter((M)=>!!M&&(!S.strictUnions||typeof M==="object"&&Object.keys(M).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:af[T.innerType._def.typeName],nullable:!0};return{type:[af[T.innerType._def.typeName],"null"]}}if(S.target==="openApi3"){let M=s(T.innerType._def,{...S,currentPath:[...S.currentPath]});if(M&&"$ref"in M)return{allOf:[M],nullable:!0};return M&&{...M,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 M of T.checks)switch(M.kind){case"int":$.type="integer",R0($,"type",M.message,S);break;case"min":if(S.target==="jsonSchema7")if(M.inclusive)KT($,"minimum",M.value,M.message,S);else KT($,"exclusiveMinimum",M.value,M.message,S);else{if(!M.inclusive)$.exclusiveMinimum=!0;KT($,"minimum",M.value,M.message,S)}break;case"max":if(S.target==="jsonSchema7")if(M.inclusive)KT($,"maximum",M.value,M.message,S);else KT($,"exclusiveMaximum",M.value,M.message,S);else{if(!M.inclusive)$.exclusiveMaximum=!0;KT($,"maximum",M.value,M.message,S)}break;case"multipleOf":KT($,"multipleOf",M.value,M.message,S);break}return $}function h6(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((M,[f,J])=>{if(J===void 0||J._def===void 0)return M;let F=s(J._def,{...S,currentPath:[...S.currentPath,"properties",f],propertyPath:[...S.currentPath,"properties",f]});if(F===void 0)return M;return{properties:{...M.properties,[f]:F},required:J.isOptional()?M.required:[...M.required,f]}},{properties:{},required:[]}),additionalProperties:h6(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"]}),M=s(T.out._def,{...S,currentPath:[...S.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,M].filter((f)=>f!==void 0)}};function lk(T,S){return s(T.type._def,S)}function rk(T,S){let M={type:"array",uniqueItems:!0,items:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items"]})};if(T.minSize)KT(M,"minItems",T.minSize.value,T.minSize.message,S);if(T.maxSize)KT(M,"maxItems",T.maxSize.value,T.maxSize.message,S);return M}function ak(T,S){if(T.rest)return{type:"array",minItems:T.items.length,items:T.items.map(($,M)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${M}`]})).reduce(($,M)=>M===void 0?$:[...$,M],[]),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(($,M)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${M}`]})).reduce(($,M)=>M===void 0?$:[...$,M],[])}}function ek(){return{not:{}}}function sk(){return{}}var TX=(T,S)=>{return s(T.innerType._def,S)};function s(T,S,$=!1){let M=S.seen.get(T);if(S.override){let F=S.override?.(T,S,M,$);if(F!==wk)return F}if(M&&!$){let F=v6(M,S);if(F!==void 0)return F}let f={def:T,path:S.currentPath,jsonSchema:void 0};S.seen.set(T,f);let J=n6(T,T.typeName,S);if(J)c6(T,S,J);return f.jsonSchema=J,J}var v6=(T,S)=>{switch(S.$refStrategy){case"root":return{$ref:T.path.join("/")};case"relative":return{$ref:P6(S.currentPath,T.path)};case"none":case"seen":{if(T.path.length<S.currentPath.length&&T.path.every(($,M)=>S.currentPath[M]===$))return console.warn(`Recursive reference detected at ${S.currentPath.join("/")}! Defaulting to any`),{};return S.$refStrategy==="seen"?{}:void 0}}},P6=(T,S)=>{let $=0;for(;$<T.length&&$<S.length;$++)if(T[$]!==S[$])break;return[(T.length-$).toString(),...S.slice($)].join("/")},n6=(T,S,$)=>{switch(S){case x.ZodString:return zF(T,$);case x.ZodNumber:return pk(T,$);case x.ZodObject:return ik(T,$);case x.ZodBigInt:return Ck(T,$);case x.ZodBoolean:return xk();case x.ZodDate:return E0(T,$);case x.ZodUndefined:return ek();case x.ZodNull:return ck($);case x.ZodArray:return Nk(T,$);case x.ZodUnion:case x.ZodDiscriminatedUnion:return gk(T,$);case x.ZodIntersection:return qk(T,$);case x.ZodTuple:return ak(T,$);case x.ZodRecord:return _F(T,$);case x.ZodLiteral:return mk(T,$);case x.ZodEnum:return Zk(T);case x.ZodNativeEnum:return Pk(T);case x.ZodNullable:return tk(T,$);case x.ZodOptional:return dk(T,$);case x.ZodMap:return vk(T,$);case x.ZodSet:return rk(T,$);case x.ZodLazy:return s(T.getter()._def,$);case x.ZodPromise:return lk(T,$);case x.ZodNaN:case x.ZodNever:return nk();case x.ZodEffects:return bk(T,$);case x.ZodAny:return Lk();case x.ZodUnknown:return sk();case x.ZodDefault:return Ik(T,$);case x.ZodBranded:return GF(T,$);case x.ZodReadonly:return TX(T,$);case x.ZodCatch:return jk(T,$);case x.ZodPipeline:return uk(T,$);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return((M)=>{return})(S)}},c6=(T,S,$)=>{if(T.description){if($.description=T.description,S.markdownDescription)$.markdownDescription=T.description}return $};var SX=(T,S)=>{let $=yk(S),M=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,f=typeof S==="string"?S:S?.nameStrategy==="title"?void 0:S?.name,J=s(T._def,f===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,f]},!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=f===void 0?M?{...J,[$.definitionPath]:M}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,f].join("/"),[$.definitionPath]:{...M,[f]: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 MX(T,S){return function $({schema:M,fallback:f}){let J=$X(M);return async function F(W,A=3){let k,X=[];while(X.length<A){k=await T(W,J,f,X);let K=M.safeParse(k);if(K.success)return K.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
+ `,K.error.toString()),X.push({response:k,error:K.error})}return S?.error(`safegen was unable to generate well-formed data after ${A} failed attempts.`),f}}}function fX(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 rY}from"crypto";var HF="RFC3986",EF={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},JX="RFC1738";var o6=Array.isArray,k$=(()=>{let T=[];for(let S=0;S<256;++S)T.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return T})();var Q0=1024,FX=(T,S,$,M,f)=>{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+=Q0){let A=J.length>=Q0?J.slice(W,W+Q0):J,k=[];for(let X=0;X<A.length;++X){let K=A.charCodeAt(X);if(K===45||K===46||K===95||K===126||K>=48&&K<=57||K>=65&&K<=90||K>=97&&K<=122||f===JX&&(K===40||K===41)){k[k.length]=A.charAt(X);continue}if(K<128){k[k.length]=k$[K];continue}if(K<2048){k[k.length]=k$[192|K>>6]+k$[128|K&63];continue}if(K<55296||K>=57344){k[k.length]=k$[224|K>>12]+k$[128|K>>6&63]+k$[128|K&63];continue}X+=1,K=65536+((K&1023)<<10|A.charCodeAt(X)&1023),k[k.length]=k$[240|K>>18]+k$[128|K>>12&63]+k$[128|K>>6&63]+k$[128|K&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 U0(T,S){if(o6(T)){let $=[];for(let M=0;M<T.length;M+=1)$.push(S(T[M]));return $}return S(T)}var g6=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,t6=Array.prototype.push,kX=function(T,S){t6.apply(T,X$(S)?S:[S])},p6=Date.prototype.toISOString,uT={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 p6.call(T)},skipNulls:!1,strictNullHandling:!1};function i6(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}var V0={};function XX(T,S,$,M,f,J,F,W,A,k,X,K,w,z,O,Q,D,B){let L=T,b=B,C=0,E=!1;while((b=b.get(V0))!==void 0&&!E){let G=b.get(T);if(C+=1,typeof G!=="undefined")if(G===C)throw new RangeError("Cyclic object value");else E=!0;if(typeof b.get(V0)==="undefined")C=0}if(typeof k==="function")L=k(S,L);else if(L instanceof Date)L=w?.(L);else if($==="comma"&&X$(L))L=U0(L,function(G){if(G instanceof Date)return w?.(G);return G});if(L===null){if(J)return A&&!Q?A(S,uT.encoder,D,"key",z):S;L=""}if(i6(L)||WX(L)){if(A){let G=Q?S:A(S,uT.encoder,D,"key",z);return[O?.(G)+"="+O?.(A(L,uT.encoder,D,"value",z))]}return[O?.(S)+"="+O?.(String(L))]}let _=[];if(typeof L==="undefined")return _;let U;if($==="comma"&&X$(L)){if(Q&&A)L=U0(L,A);U=[{value:L.length>0?L.join(",")||null:void 0}]}else if(X$(k))U=k;else{let G=Object.keys(L);U=X?G.sort(X):G}let q=W?String(S).replace(/\./g,"%2E"):String(S),h=M&&X$(L)&&L.length===1?q+"[]":q;if(f&&X$(L)&&L.length===0)return h+"[]";for(let G=0;G<U.length;++G){let o=U[G],n=typeof o==="object"&&typeof o.value!=="undefined"?o.value:L[o];if(F&&n===null)continue;let p=K&&W?o.replace(/\./g,"%2E"):o,RT=X$(L)?typeof $==="function"?$(h,p):h:h+(K?"."+p:"["+p+"]");B.set(T,C);let _T=new WeakMap;_T.set(V0,B),kX(_,XX(n,RT,$,M,f,J,F,W,$==="comma"&&Q&&X$(L)?null:A,k,X,K,w,z,O,Q,D,_T))}return _}function d6(T=uT){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||uT.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(!g6.call(EF,T.format))throw new TypeError("Unknown format option provided.");$=T.format}let M=EF[$],f=uT.filter;if(typeof T.filter==="function"||X$(T.filter))f=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=uT.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:uT.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:uT.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:uT.allowEmptyArrays,arrayFormat:J,charset:S,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:uT.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?uT.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:uT.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:uT.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:uT.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:uT.encodeValuesOnly,filter:f,format:$,formatter:M,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:uT.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:uT.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:uT.strictNullHandling}}function B0(T,S={}){let $=T,M=d6(S),f,J;if(typeof M.filter==="function")J=M.filter,$=J("",$);else if(X$(M.filter))J=M.filter,f=J;let F=[];if(typeof $!=="object"||$===null)return"";let W=AX[M.arrayFormat],A=W==="comma"&&M.commaRoundTrip;if(!f)f=Object.keys($);if(M.sort)f.sort(M.sort);let k=new WeakMap;for(let w=0;w<f.length;++w){let z=f[w];if(M.skipNulls&&$[z]===null)continue;kX(F,XX($[z],z,W,A,M.allowEmptyArrays,M.strictNullHandling,M.skipNulls,M.encodeDotInKeys,M.encode?M.encoder:null,M.filter,M.sort,M.allowDots,M.serializeDate,M.format,M.formatter,M.encodeValuesOnly,M.charset,k))}let X=F.join(M.delimiter),K=M.addQueryPrefix===!0?"?":"";if(M.charsetSentinel)if(M.charset==="iso-8859-1")K+="utf8=%26%2310003%3B&";else K+="utf8=%E2%9C%93&";return X.length>0?K+X:""}var JM="4.72.0";var KX=!1,FM=void 0,L0=void 0,l6=void 0,r6=void 0,a6=void 0,N0=void 0,e6=void 0,DF=void 0,C0=void 0,x0=void 0,j0=void 0,QF=void 0,I0=void 0;function wX(T,S={auto:!1}){if(KX)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(FM)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${FM}'\``);KX=S.auto,FM=T.kind,L0=T.fetch,l6=T.Request,r6=T.Response,a6=T.Headers,N0=T.FormData,e6=T.Blob,DF=T.File,C0=T.ReadableStream,x0=T.getMultipartRequestOptions,j0=T.getDefaultAgent,QF=T.fileFromPath,I0=T.isFsReadStream}class b0{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",$,M,f,J;try{$=fetch,M=Request,f=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:M,Response:f,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 b0(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 TY}from"fs";function yX(){let T=YX();function S($){return $ instanceof TY}return{...T,isFsReadStream:S}}if(!FM)wX(yX(),{auto:!0});class $T extends Error{}class oT extends $T{constructor(T,S,$,M){super(`${oT.makeMessage(T,S,$)}`);this.status=T,this.headers=M,this.request_id=M?.["x-request-id"];let f=S;this.error=f,this.code=f?.code,this.param=f?.param,this.type=f?.type}static makeMessage(T,S,$){let M=S?.message?typeof S.message==="string"?S.message:JSON.stringify(S.message):S?JSON.stringify(S):$;if(T&&M)return`${T} ${M}`;if(T)return`${T} status code (no body)`;if(M)return M;return"(no status code or body)"}static generate(T,S,$,M){if(!T)return new WM({message:$,cause:IF(S)});let f=S?.error;if(T===400)return new UF(T,f,$,M);if(T===401)return new VF(T,f,$,M);if(T===403)return new BF(T,f,$,M);if(T===404)return new LF(T,f,$,M);if(T===409)return new NF(T,f,$,M);if(T===422)return new CF(T,f,$,M);if(T===429)return new xF(T,f,$,M);if(T>=500)return new jF(T,f,$,M);return new oT(T,f,$,M)}}class SS extends oT{constructor({message:T}={}){super(void 0,void 0,T||"Request was aborted.",void 0);this.status=void 0}}class WM extends oT{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 AM extends WM{constructor({message:T}={}){super({message:T??"Request timed out."})}}class UF extends oT{constructor(){super(...arguments);this.status=400}}class VF extends oT{constructor(){super(...arguments);this.status=401}}class BF extends oT{constructor(){super(...arguments);this.status=403}}class LF extends oT{constructor(){super(...arguments);this.status=404}}class NF extends oT{constructor(){super(...arguments);this.status=409}}class CF extends oT{constructor(){super(...arguments);this.status=422}}class xF extends oT{constructor(){super(...arguments);this.status=429}}class jF extends oT{}class ef extends $T{constructor(){super("Could not parse response content as the length limit was reached")}}class sf 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]||""),M=S.split(t$.NEWLINE_REGEXP);if($)M.pop();if(M.length===1&&!$)return this.buffer.push(M[0]),[];if(this.buffer.length>0)M=[this.buffer.join("")+M[0],...M.slice(1)],this.buffer=[];if(!$)this.buffer=[M.pop()||""];return M}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([`
19
+ `,"\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*M(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let f=!1;try{for await(let J of $Y(T,S)){if(f)continue;if(J.data.startsWith("[DONE]")){f=!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 oT(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 oT(void 0,F.error,F.message,void 0);yield{event:J.event,data:F}}}f=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!f)S.abort()}}return new NS(M,S)}static fromReadableStream(T,S){let $=!1;async function*M(){let J=new t$,F=OX(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*f(){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 M()){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(f,S)}[Symbol.asyncIterator](){return this.iterator()}tee(){let T=[],S=[],$=this.iterator(),M=(f)=>{return{next:()=>{if(f.length===0){let J=$.next();T.push(J),S.push(J)}return f.shift()}}};return[new NS(()=>M(T),this.controller),new NS(()=>M(S),this.controller)]}toReadableStream(){let T=this,S,$=new TextEncoder;return new C0({async start(){S=T[Symbol.asyncIterator]()},async pull(M){try{let{value:f,done:J}=await S.next();if(J)return M.close();let F=$.encode(JSON.stringify(f)+`
20
+ `);M.enqueue(F)}catch(f){M.error(f)}},async cancel(){await S.return?.()}})}}async function*$Y(T,S){if(!T.body)throw S.abort(),new $T("Attempted to iterate over a response with no body");let $=new RX,M=new t$,f=OX(T.body);for await(let J of MY(f))for(let F of M.decode(J)){let W=$.decode(F);if(W)yield W}for(let J of M.flush()){let F=$.decode(J);if(F)yield F}}async function*MY(T){let S=new Uint8Array;for await(let $ of T){if($==null)continue;let M=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,f=new Uint8Array(S.length+M.length);f.set(S),f.set(M,S.length),S=f;let J;while((J=fY(S))!==-1)yield S.slice(0,J),S=S.slice(J)}if(S.length>0)yield S}function fY(T){for(let M=0;M<T.length-2;M++){if(T[M]===10&&T[M+1]===10)return M+2;if(T[M]===13&&T[M+1]===13)return M+2;if(T[M]===13&&T[M+1]===10&&M+3<T.length&&T[M+2]===13&&T[M+3]===10)return M+4}return-1}class RX{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 f={event:this.event,data:this.data.join(`
21
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],f}if(this.chunks.push(T),T.startsWith(":"))return null;let[S,$,M]=JY(T,":");if(M.startsWith(" "))M=M.substring(1);if(S==="event")this.event=M;else if(S==="data")this.data.push(M);return null}}function JY(T,S){let $=T.indexOf(S);if($!==-1)return[T.substring(0,$),S,T.substring($+S.length)];return[T,"",""]}function OX(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",FY=(T)=>{return zX(T)||GX(T)||I0(T)};async function m0(T,S,$){if(T=await T,zX(T))return T;if(GX(T)){let f=await T.blob();S||(S=new URL(T.url).pathname.split(/[\\/]/).pop()??"unknown_file");let J=TJ(f)?[await f.arrayBuffer()]:[f];return new DF(J,S,$)}let M=await WY(T);if(S||(S=kY(T)??"unknown_file"),!$?.type){let f=M[0]?.type;if(typeof f==="string")$={...$,type:f}}return new DF(M,S,$)}async function WY(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(XY(T))for await(let $ of T)S.push($);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${AY(T)}`);return S}function AY(T){return`[${Object.getOwnPropertyNames(T).map(($)=>`"${$}"`).join(", ")}]`}function kY(T){return Z0(T.name)||Z0(T.filename)||Z0(T.path)?.split(/[\\/]/).pop()}var Z0=(T)=>{if(typeof T==="string")return T;if(typeof Buffer!=="undefined"&&T instanceof Buffer)return String(T);return},XY=(T)=>T!=null&&typeof T==="object"&&typeof T[Symbol.asyncIterator]==="function",h0=(T)=>T&&typeof T==="object"&&T.body&&T[Symbol.toStringTag]==="MultipartBody";var vS=async(T)=>{let S=await _X(T.body);return x0(S,T)},_X=async(T)=>{let S=new N0;return await Promise.all(Object.entries(T||{}).map(([$,M])=>q0(S,$,M))),S};var q0=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(FY($)){let M=await m0($);T.append(S,M)}else if(Array.isArray($))await Promise.all($.map((M)=>q0(T,S+"[]",M)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([M,f])=>q0(T,`${S}[${M}]`,f)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};var wY=function(T,S,$,M,f){if(M==="m")throw new TypeError("Private method is not writable");if(M==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return M==="a"?f.call(T,$):f?f.value=$:S.set(T,$),$},YY=function(T,S,$,M){if($==="a"&&!M)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?M:$==="a"?M.call(T):M?M.value:S.get(T)},bF;async function VX(T){let{response:S}=T;if(T.options.stream){if(eM("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 eM("response",S.status,S.url,S.headers,J),BX(J,S)}let f=await S.text();return eM("response",S.status,S.url,S.headers,f),f}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 P0{constructor({baseURL:T,maxRetries:S=2,timeout:$=600000,httpAgent:M,fetch:f}){this.baseURL=T,this.maxRetries=v0("maxRetries",S),this.timeout=v0("timeout",$),this.httpAgent=M,this.fetch=f??L0}authHeaders(T){return{}}defaultHeaders(T){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...zY(),...this.authHeaders(T)}}validateHeaders(T,S){}defaultIdempotencyKey(){return`stainless-node-retry-${DY()}`}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(M)=>{let f=M&&TJ(M?.body)?new DataView(await M.body.arrayBuffer()):M?.body instanceof DataView?M.body:M?.body instanceof ArrayBuffer?new DataView(M.body):M&&ArrayBuffer.isView(M?.body)?new DataView(M.body.buffer):M?.body;return{method:T,path:S,...M,body:f}}))}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:M,query:f,headers:J={}}=T,F=ArrayBuffer.isView(T.body)||T.__binaryRequest&&typeof T.body==="string"?T.body:h0(T.body)?T.body.body:T.body?JSON.stringify(T.body,null,2):null,W=this.calculateContentLength(F),A=this.buildURL(M,f);if("timeout"in T)v0("timeout",T.timeout);let k=T.timeout??this.timeout,X=T.httpAgent??this.httpAgent??j0(A),K=k+1000;if(typeof X?.options?.timeout==="number"&&K>(X.options.timeout??0))X.options.timeout=K;if(this.idempotencyHeader&&$!=="get"){if(!T.idempotencyKey)T.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=T.idempotencyKey}let w=this.buildHeaders({options:T,headers:J,contentLength:W,retryCount:S});return{req:{method:$,...F&&{body:F},headers:w,...X&&{agent:X},signal:T.signal??null},url:A,timeout:k}}buildHeaders({options:T,headers:S,contentLength:$,retryCount:M}){let f={};if($)f["content-length"]=$;let J=this.defaultHeaders(T);if(QX(f,J),QX(f,S),h0(T.body)&&FM!=="node")delete f["content-type"];if(UX(J,"x-stainless-retry-count")===void 0&&UX(S,"x-stainless-retry-count")===void 0)f["x-stainless-retry-count"]=String(M);return this.validateHeaders(f,S),f}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,$,M){return oT.generate(T,S,$,M)}request(T,S=null){return new ZF(this.makeRequest(T,S))}async makeRequest(T,S){let $=await T,M=$.maxRetries??this.maxRetries;if(S==null)S=M;await this.prepareOptions($);let{req:f,url:J,timeout:F}=this.buildRequest($,{retryCount:M-S});if(await this.prepareRequest(f,{url:J,options:$}),eM("request",J,$,f.headers),$.signal?.aborted)throw new SS;let W=new AbortController,A=await this.fetchWithTimeout(J,f,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 AM;throw new WM({cause:A})}let k=yY(A.headers);if(!A.ok){if(S&&this.shouldRetry(A)){let Q=`retrying, ${S} attempts remaining`;return eM(`response (error; ${Q})`,A.status,J,k),this.retryRequest($,S,k)}let X=await A.text().catch((Q)=>IF(Q).message),K=_Y(X),w=K?void 0:X;throw eM(`response (error; ${S?"(error; no more retries left)":"(error; not retryable)"})`,A.status,J,k,w),this.makeStatusError(A.status,K,w,k)}return{response:A,options:$,controller:W}}requestAPIList(T,S){let $=this.makeRequest(S,null);return new LX(this,$,T)}buildURL(T,S){let $=EY(T)?new URL(T):new URL(this.baseURL+(this.baseURL.endsWith("/")&&T.startsWith("/")?T.slice(1):T)),M=this.defaultQuery();if(!NX(M))S={...M,...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,$,M){let{signal:f,...J}=S||{};if(f)f.addEventListener("abort",()=>M.abort());let F=setTimeout(()=>M.abort(),$);return this.getRequestClient().fetch.call(void 0,T,{signal:M.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 M,f=$?.["retry-after-ms"];if(f){let F=parseFloat(f);if(!Number.isNaN(F))M=F}let J=$?.["retry-after"];if(J&&!M){let F=parseFloat(J);if(!Number.isNaN(F))M=F*1000;else M=Date.parse(J)-Date.now()}if(!(M&&0<=M&&M<60000)){let F=T.maxRetries??this.maxRetries;M=this.calculateDefaultRetryTimeoutMillis(S,F)}return await E$(M),this.makeRequest(T,S-1)}calculateDefaultRetryTimeoutMillis(T,S){let f=S-T,J=Math.min(0.5*Math.pow(2,f),8),F=1-Math.random()*0.25;return J*F*1000}getUserAgent(){return`${this.constructor.name}/JS ${JM}`}}class qF{constructor(T,S,$,M){bF.set(this,void 0),wY(this,bF,T,"f"),this.options=M,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[M,f]of $)T.url.searchParams.set(M,f);S.query=void 0,S.path=T.url.toString()}return await YY(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(M)=>new $(T,M.response,await VX(M),M.options))}async*[Symbol.asyncIterator](){let T=await this;for await(let S of T)yield S}}var yY=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get(S,$){let M=$.toString();return S[M.toLowerCase()]||S[M]}})},RY={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(RY,S))},OY=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":JM,"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":JM,"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":JM,"X-Stainless-OS":EX(process.platform),"X-Stainless-Arch":HX(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let T=GY();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":JM,"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":JM,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function GY(){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 M=$.exec(navigator.userAgent);if(M){let f=M[1]||0,J=M[2]||0,F=M[3]||0;return{browser:S,version:`${f}.${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,zY=()=>{return DX??(DX=OY())},_Y=(T)=>{try{return JSON.parse(T)}catch(S){return}},HY=new RegExp("^(?:[a-z]+:)?//","i"),EY=(T)=>{return HY.test(T)},E$=(T)=>new Promise((S)=>setTimeout(S,T)),v0=(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 M=$.toLowerCase();if(!M)continue;let f=S[$];if(f===null)delete T[M];else if(f!==void 0)T[M]=f}}function eM(T,...S){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true")console.log(`OpenAI:DEBUG:${T}`,...S)}var DY=()=>{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"},QY=(T)=>{return typeof T?.get==="function"};var UX=(T,S)=>{let $=S.toLowerCase();if(QY(T)){let M=S[0]?.toUpperCase()+S.substring(1).replace(/([^\w])(\w)/g,(f,J,F)=>J+F.toUpperCase());for(let f of[S,$,S.toUpperCase(),M]){let J=T.get(f);if(J)return J}}for(let[M,f]of Object.entries(T))if(M.toLowerCase()===$){if(Array.isArray(f)){if(f.length<=1)return f[0];return console.warn(`Received ${f.length} entries for the ${S} header, using the first entry.`),f[0]}return f}return};function $J(T){return T!=null&&typeof T==="object"&&!Array.isArray(T)}class n0 extends qF{constructor(T,S,$,M){super(T,S,$,M);this.data=$.data||[],this.object=$.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class vT extends qF{constructor(T,S,$,M){super(T,S,$,M);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 MJ extends i{create(T,S){return this._client.post("/chat/completions",{body:T,...S,stream:T.stream??!1})}}class XM extends i{constructor(){super(...arguments);this.completions=new MJ(this._client)}}XM.Completions=MJ;class fJ 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 D$ extends i{constructor(){super(...arguments);this.transcriptions=new JJ(this._client),this.translations=new FJ(this._client),this.speech=new fJ(this._client)}}D$.Transcriptions=JJ;D$.Translations=FJ;D$.Speech=fJ;class KM 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",sM,{query:T,...S})}cancel(T,S){return this._client.post(`/batches/${T}/cancel`,S)}}class sM extends vT{}KM.BatchesPage=sM;class Tf 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{}Tf.AssistantsPage=WJ;function c0(T){return typeof T.parse==="function"}var p$=(T)=>{return T?.role==="assistant"},o0=(T)=>{return T?.role==="function"},g0=(T)=>{return T?.role==="tool"};var sS=function(T,S,$,M,f){if(M==="m")throw new TypeError("Private method is not writable");if(M==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return M==="a"?f.call(T,$):f?f.value=$:S.set(T,$),$},mT=function(T,S,$,M){if($==="a"&&!M)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?M:$==="a"?M.call(T):M?M.value:S.get(T)},t0,mF,hF,AJ,kJ,vF,XJ,Q$,KJ,PF,nF,Sf,jX;class wJ{constructor(){t0.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,()=>{}),Q$.set(this,{}),KJ.set(this,!1),PF.set(this,!1),nF.set(this,!1),Sf.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,t0,"m",jX).bind(this))},0)}_connected(){if(this.ended)return;mT(this,hF,"f").call(this),this._emit("connect")}get ended(){return mT(this,KJ,"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,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 M=$.findIndex((f)=>f.listener===S);if(M>=0)$.splice(M,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(sS(this,Sf,!0,"f"),T!=="error")this.once("error",$);this.once(T,S)})}async done(){sS(this,Sf,!0,"f"),await mT(this,kJ,"f")}_emit(T,...S){if(mT(this,KJ,"f"))return;if(T==="end")sS(this,KJ,!0,"f"),mT(this,vF,"f").call(this);let $=mT(this,Q$,"f")[T];if($)mT(this,Q$,"f")[T]=$.filter((M)=>!M.once),$.forEach(({listener:M})=>M(...S));if(T==="abort"){let M=S[0];if(!mT(this,Sf,"f")&&!$?.length)Promise.reject(M);mT(this,AJ,"f").call(this,M),mT(this,XJ,"f").call(this,M),this._emit("end");return}if(T==="error"){let M=S[0];if(!mT(this,Sf,"f")&&!$?.length)Promise.reject(M);mT(this,AJ,"f").call(this,M),mT(this,XJ,"f").call(this,M),this._emit("end")}}_emitFinal(){}}mF=new WeakMap,hF=new WeakMap,AJ=new WeakMap,kJ=new WeakMap,vF=new WeakMap,XJ=new WeakMap,Q$=new WeakMap,KJ=new WeakMap,PF=new WeakMap,nF=new WeakMap,Sf=new WeakMap,t0=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 p0(T){return T?.$brand==="auto-parseable-response-format"}function wM(T){return T?.$brand==="auto-parseable-tool"}function IX(T,S){if(!S||!i0(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((M)=>{if(M.finish_reason==="length")throw new ef;if(M.finish_reason==="content_filter")throw new sf;return{...M,message:{...M.message,tool_calls:M.message.tool_calls?.map((f)=>xY(S,f))??[],parsed:M.message.content&&!M.message.refusal?CY(S,M.message.content):null}}});return{...T,choices:$}}function CY(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 xY(T,S){let $=T.tools?.find((M)=>M.function?.name===S.function.name);return{...S,function:{...S.function,parsed_arguments:wM($)?$.$parseRaw(S.function.arguments):$?.function.strict?JSON.parse(S.function.arguments):null}}}function bX(T,S){if(!T)return!1;let $=T.tools?.find((M)=>M.function?.name===S.function.name);return wM($)||$?.function.strict||!1}function i0(T){if(p0(T.response_format))return!0;return T.tools?.some((S)=>wM(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,$,M){if($==="a"&&!M)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?M:$==="a"?M.call(T):M?M.value:S.get(T)},YS,d0,cF,u0,l0,r0,mX,a0,qX=10;class yJ extends wJ{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)||g0(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",d0).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",u0).call(this)}async finalFunctionCallResult(){return await this.done(),QS(this,YS,"m",l0).call(this)}async totalUsage(){return await this.done(),QS(this,YS,"m",r0).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",d0).call(this);if($)this._emit("finalContent",$);let M=QS(this,YS,"m",u0).call(this);if(M)this._emit("finalFunctionCall",M);let f=QS(this,YS,"m",l0).call(this);if(f!=null)this._emit("finalFunctionCallResult",f);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",QS(this,YS,"m",r0).call(this))}async _createChatCompletion(T,S,$){let M=$?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}QS(this,YS,"m",mX).call(this,S);let f=await T.chat.completions.create({...S,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(YJ(f,S))}async _runChatCompletion(T,S,$){for(let M of S.messages)this._addMessage(M,!1);return await this._createChatCompletion(T,S,$)}async _runFunctions(T,S,$){let{function_call:f="auto",stream:J,...F}=S,W=typeof f!=="string"&&f?.name,{maxChatCompletions:A=qX}=$||{},k={};for(let K of S.functions)k[K.name||K.function.name]=K;let X=S.functions.map((K)=>({name:K.name||K.function.name,parameters:K.parameters,description:K.description}));for(let K of S.messages)this._addMessage(K,!1);for(let K=0;K<A;++K){let z=(await this._createChatCompletion(T,{...F,function_call:f,functions:X,messages:[...this.messages]},$)).choices[0]?.message;if(!z)throw new $T("missing message in ChatCompletion response");if(!z.function_call)return;let{name:O,arguments:Q}=z.function_call,D=k[O];if(!D){let C=`Invalid function_call: ${JSON.stringify(O)}. Available options are: ${X.map((E)=>JSON.stringify(E.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:O,content:C});continue}else if(W&&W!==O){let C=`Invalid function_call: ${JSON.stringify(O)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"function",name:O,content:C});continue}let B;try{B=c0(D)?await D.parse(Q):Q}catch(C){this._addMessage({role:"function",name:O,content:C instanceof Error?C.message:String(C)});continue}let L=await D.function(B,this),b=QS(this,YS,"m",a0).call(this,L);if(this._addMessage({role:"function",name:O,content:b}),W)return}}async _runTools(T,S,$){let{tool_choice:f="auto",stream:J,...F}=S,W=typeof f!=="string"&&f?.function?.name,{maxChatCompletions:A=qX}=$||{},k=S.tools.map((w)=>{if(wM(w)){if(!w.$callback)throw new $T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:w.$callback,name:w.function.name,description:w.function.description||"",parameters:w.function.parameters,parse:w.$parseRaw,strict:!0}}}return w}),X={};for(let w of k)if(w.type==="function")X[w.function.name||w.function.function.name]=w.function;let K="tools"in S?k.map((w)=>w.type==="function"?{type:"function",function:{name:w.function.name||w.function.function.name,parameters:w.function.parameters,description:w.function.description,strict:w.function.strict}}:w):void 0;for(let w of S.messages)this._addMessage(w,!1);for(let w=0;w<A;++w){let O=(await this._createChatCompletion(T,{...F,tool_choice:f,tools:K,messages:[...this.messages]},$)).choices[0]?.message;if(!O)throw new $T("missing message in ChatCompletion response");if(!O.tool_calls?.length)return;for(let Q of O.tool_calls){if(Q.type!=="function")continue;let D=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((q)=>JSON.stringify(q)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:D,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:D,content:U});continue}let C;try{C=c0(b)?await b.parse(L):L}catch(U){let q=U instanceof Error?U.message:String(U);this._addMessage({role:"tool",tool_call_id:D,content:q});continue}let E=await b.function(C,this),_=QS(this,YS,"m",a0).call(this,E);if(this._addMessage({role:"tool",tool_call_id:D,content:_}),W)return}}return}}YS=new WeakSet,d0=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:M,...f}=$,J={...f,content:$.content??null,refusal:$.refusal??null};if(M)J.function_call=M;return J}}throw new $T("stream ended without producing a ChatCompletionMessage with role=assistant")},u0=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},l0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(o0($)&&$.content!=null)return $.content;if(g0($)&&$.content!=null&&typeof $.content==="string"&&this.messages.some((M)=>M.role==="assistant"&&M.tool_calls?.some((f)=>f.type==="function"&&f.id===$.tool_call_id)))return $.content}return},r0=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.")},a0=function T(S){return typeof S==="string"?S:S===void 0?"undefined":JSON.stringify(S)};class $f extends yJ{static runFunctions(T,S,$){let M=new $f,f={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return M._run(()=>M._runFunctions(T,S,f)),M}static runTools(T,S,$){let M=new $f,f={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return M._run(()=>M._runTools(T,S,f)),M}_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 jY(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 IY(T.trim(),S)}var IY=(T,S)=>{let $=T.length,M=0,f=(w)=>{throw new hX(`${w} at position ${M}`)},J=(w)=>{throw new vX(`${w} at position ${M}`)},F=()=>{if(K(),M>=$)f("Unexpected end of input");if(T[M]==='"')return W();if(T[M]==="{")return A();if(T[M]==="[")return k();if(T.substring(M,M+4)==="null"||sT.NULL&S&&$-M<4&&"null".startsWith(T.substring(M)))return M+=4,null;if(T.substring(M,M+4)==="true"||sT.BOOL&S&&$-M<4&&"true".startsWith(T.substring(M)))return M+=4,!0;if(T.substring(M,M+5)==="false"||sT.BOOL&S&&$-M<5&&"false".startsWith(T.substring(M)))return M+=5,!1;if(T.substring(M,M+8)==="Infinity"||sT.INFINITY&S&&$-M<8&&"Infinity".startsWith(T.substring(M)))return M+=8,1/0;if(T.substring(M,M+9)==="-Infinity"||sT.MINUS_INFINITY&S&&1<$-M&&$-M<9&&"-Infinity".startsWith(T.substring(M)))return M+=9,-1/0;if(T.substring(M,M+3)==="NaN"||sT.NAN&S&&$-M<3&&"NaN".startsWith(T.substring(M)))return M+=3,NaN;return X()},W=()=>{let w=M,z=!1;M++;while(M<$&&(T[M]!=='"'||z&&T[M-1]==="\\"))z=T[M]==="\\"?!z:!1,M++;if(T.charAt(M)=='"')try{return JSON.parse(T.substring(w,++M-Number(z)))}catch(O){J(String(O))}else if(sT.STR&S)try{return JSON.parse(T.substring(w,M-Number(z))+'"')}catch(O){return JSON.parse(T.substring(w,T.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},A=()=>{M++,K();let w={};try{while(T[M]!=="}"){if(K(),M>=$&&sT.OBJ&S)return w;let z=W();K(),M++;try{let O=F();Object.defineProperty(w,z,{value:O,writable:!0,enumerable:!0,configurable:!0})}catch(O){if(sT.OBJ&S)return w;else throw O}if(K(),T[M]===",")M++}}catch(z){if(sT.OBJ&S)return w;else f("Expected '}' at end of object")}return M++,w},k=()=>{M++;let w=[];try{while(T[M]!=="]")if(w.push(F()),K(),T[M]===",")M++}catch(z){if(sT.ARR&S)return w;f("Expected ']' at end of array")}return M++,w},X=()=>{if(M===0){if(T==="-"&&sT.NUM&S)f("Not sure what '-' is");try{return JSON.parse(T)}catch(z){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(O){}J(String(z))}}let w=M;if(T[M]==="-")M++;while(T[M]&&!",]}".includes(T[M]))M++;if(M==$&&!(sT.NUM&S))f("Unterminated number literal");try{return JSON.parse(T.substring(w,M))}catch(z){if(T.substring(w,M)==="-"&&sT.NUM&S)f("Not sure what '-' is");try{return JSON.parse(T.substring(w,T.lastIndexOf("e")))}catch(O){J(String(O))}}},K=()=>{while(M<$&&`
22
+ \r\t`.includes(T[M]))M++};return F()},e0=(T)=>jY(T,sT.ALL^sT.NUM);var Mf=function(T,S,$,M,f){if(M==="m")throw new TypeError("Private method is not writable");if(M==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return M==="a"?f.call(T,$):f?f.value=$:S.set(T,$),$},HT=function(T,S,$,M){if($==="a"&&!M)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?M:$==="a"?M.call(T):M?M.value:S.get(T)},lT,U$,ff,i$,s0,oF,T1,S1,$1,gF,M1,PX;class YM extends yJ{constructor(T){super();lT.add(this),U$.set(this,void 0),ff.set(this,void 0),i$.set(this,void 0),Mf(this,U$,T,"f"),Mf(this,ff,[],"f")}get currentChatCompletionSnapshot(){return HT(this,i$,"f")}static fromReadableStream(T){let S=new YM(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){let M=new YM(S);return M._run(()=>M._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),M}async _createChatCompletion(T,S,$){super._createChatCompletion;let M=$?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}HT(this,lT,"m",s0).call(this);let f=await T.chat.completions.create({...S,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let J of f)HT(this,lT,"m",T1).call(this,J);if(f.controller.signal?.aborted)throw new SS;return this._addChatCompletion(HT(this,lT,"m",gF).call(this))}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}HT(this,lT,"m",s0).call(this),this._connected();let M=NS.fromReadableStream(T,this.controller),f;for await(let J of M){if(f&&f!==J.id)this._addChatCompletion(HT(this,lT,"m",gF).call(this));HT(this,lT,"m",T1).call(this,J),f=J.id}if(M.controller.signal?.aborted)throw new SS;return this._addChatCompletion(HT(this,lT,"m",gF).call(this))}[(U$=new WeakMap,ff=new WeakMap,i$=new WeakMap,lT=new WeakSet,s0=function T(){if(this.ended)return;Mf(this,i$,void 0,"f")},oF=function T(S){let $=HT(this,ff,"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,ff,"f")[S.index]=$,$},T1=function T(S){if(this.ended)return;let $=HT(this,lT,"m",PX).call(this,S);this._emit("chunk",S,$);for(let M of S.choices){let f=$.choices[M.index];if(M.delta.content!=null&&f.message?.role==="assistant"&&f.message?.content)this._emit("content",M.delta.content,f.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:f.message.content,parsed:f.message.parsed});if(M.delta.refusal!=null&&f.message?.role==="assistant"&&f.message?.refusal)this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:f.message.refusal});if(M.logprobs?.content!=null&&f.message?.role==="assistant")this._emit("logprobs.content.delta",{content:M.logprobs?.content,snapshot:f.logprobs?.content??[]});if(M.logprobs?.refusal!=null&&f.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:M.logprobs?.refusal,snapshot:f.logprobs?.refusal??[]});let J=HT(this,lT,"m",oF).call(this,f);if(f.finish_reason){if(HT(this,lT,"m",$1).call(this,f),J.current_tool_call_index!=null)HT(this,lT,"m",S1).call(this,f,J.current_tool_call_index)}for(let F of M.delta.tool_calls??[]){if(J.current_tool_call_index!==F.index){if(HT(this,lT,"m",$1).call(this,f),J.current_tool_call_index!=null)HT(this,lT,"m",S1).call(this,f,J.current_tool_call_index)}J.current_tool_call_index=F.index}for(let F of M.delta.tool_calls??[]){let W=f.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)}}},S1=function T(S,$){if(HT(this,lT,"m",oF).call(this,S).done_tool_calls.has($))return;let f=S.message.tool_calls?.[$];if(!f)throw new Error("no tool call snapshot");if(!f.type)throw new Error("tool call snapshot missing `type`");if(f.type==="function"){let J=HT(this,U$,"f")?.tools?.find((F)=>F.type==="function"&&F.function.name===f.function.name);this._emit("tool_calls.function.arguments.done",{name:f.function.name,index:$,arguments:f.function.arguments,parsed_arguments:wM(J)?J.$parseRaw(f.function.arguments):J?.function.strict?JSON.parse(f.function.arguments):null})}else cX(f.type)},$1=function T(S){let $=HT(this,lT,"m",oF).call(this,S);if(S.message.content&&!$.content_done){$.content_done=!0;let M=HT(this,lT,"m",M1).call(this);this._emit("content.done",{content:S.message.content,parsed:M?M.$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})},gF=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 Mf(this,i$,void 0,"f"),Mf(this,ff,[],"f"),bY(S,HT(this,U$,"f"))},M1=function T(){let S=HT(this,U$,"f")?.response_format;if(p0(S))return S;return null},PX=function T(S){var $,M,f,J;let F=HT(this,i$,"f"),{choices:W,...A}=S;if(!F)F=Mf(this,i$,{...A,choices:[]},"f");else Object.assign(F,A);for(let{delta:k,finish_reason:X,index:K,logprobs:w=null,...z}of S.choices){let O=F.choices[K];if(!O)O=F.choices[K]={finish_reason:X,index:K,message:{},logprobs:w,...z};if(w)if(!O.logprobs)O.logprobs=Object.assign({},w);else{let{content:E,refusal:_,...U}=w;if(nX(U),Object.assign(O.logprobs,U),E)($=O.logprobs).content??($.content=[]),O.logprobs.content.push(...E);if(_)(M=O.logprobs).refusal??(M.refusal=[]),O.logprobs.refusal.push(..._)}if(X){if(O.finish_reason=X,HT(this,U$,"f")&&i0(HT(this,U$,"f"))){if(X==="length")throw new ef;if(X==="content_filter")throw new sf}}if(Object.assign(O,z),!k)continue;let{content:Q,refusal:D,function_call:B,role:L,tool_calls:b,...C}=k;if(nX(C),Object.assign(O.message,C),D)O.message.refusal=(O.message.refusal||"")+D;if(L)O.message.role=L;if(B)if(!O.message.function_call)O.message.function_call=B;else{if(B.name)O.message.function_call.name=B.name;if(B.arguments)(f=O.message.function_call).arguments??(f.arguments=""),O.message.function_call.arguments+=B.arguments}if(Q){if(O.message.content=(O.message.content||"")+Q,!O.message.refusal&&HT(this,lT,"m",M1).call(this))O.message.parsed=e0(O.message.content)}if(b){if(!O.message.tool_calls)O.message.tool_calls=[];for(let{index:E,id:_,type:U,function:q,...h}of b){let G=(J=O.message.tool_calls)[E]??(J[E]={});if(Object.assign(G,h),_)G.id=_;if(U)G.type=U;if(q)G.function??(G.function={name:q.name??"",arguments:""});if(q?.name)G.function.name=q.name;if(q?.arguments){if(G.function.arguments+=q.arguments,bX(HT(this,U$,"f"),G))G.function.parsed_arguments=e0(G.function.arguments)}}}}return F},Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("chunk",(M)=>{let f=S.shift();if(f)f.resolve(M);else T.push(M)}),this.on("end",()=>{$=!0;for(let M of S)M.resolve(void 0);S.length=0}),this.on("abort",(M)=>{$=!0;for(let f of S)f.reject(M);S.length=0}),this.on("error",(M)=>{$=!0;for(let f of S)f.reject(M);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((f,J)=>S.push({resolve:f,reject:J})).then((f)=>f?{value:f,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 bY(T,S){let{id:$,choices:M,created:f,model:J,system_fingerprint:F,...W}=T,A={...W,id:$,choices:M.map(({message:k,finish_reason:X,index:K,logprobs:w,...z})=>{if(!X)throw new $T(`missing finish_reason for choice ${K}`);let{content:O=null,function_call:Q,tool_calls:D,...B}=k,L=k.role;if(!L)throw new $T(`missing role for choice ${K}`);if(Q){let{arguments:b,name:C}=Q;if(b==null)throw new $T(`missing function_call.arguments for choice ${K}`);if(!C)throw new $T(`missing function_call.name for choice ${K}`);return{...z,message:{content:O,function_call:{arguments:b,name:C},role:L,refusal:k.refusal??null},finish_reason:X,index:K,logprobs:w}}if(D)return{...z,index:K,finish_reason:X,logprobs:w,message:{...B,role:L,content:O,refusal:k.refusal??null,tool_calls:D.map((b,C)=>{let{function:E,type:_,id:U,...q}=b,{arguments:h,name:G,...o}=E||{};if(U==null)throw new $T(`missing choices[${K}].tool_calls[${C}].id
23
+ ${tF(T)}`);if(_==null)throw new $T(`missing choices[${K}].tool_calls[${C}].type
24
+ ${tF(T)}`);if(G==null)throw new $T(`missing choices[${K}].tool_calls[${C}].function.name
25
+ ${tF(T)}`);if(h==null)throw new $T(`missing choices[${K}].tool_calls[${C}].function.arguments
26
+ ${tF(T)}`);return{...q,id:U,type:_,function:{...o,name:G,arguments:h}}})}};return{...z,message:{...B,content:O,role:L,refusal:k.refusal??null},finish_reason:X,index:K,logprobs:w}}),created:f,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 yM extends YM{static fromReadableStream(T){let S=new yM(null);return S._run(()=>S._fromReadableStream(T)),S}static runFunctions(T,S,$){let M=new yM(null),f={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return M._run(()=>M._runFunctions(T,S,f)),M}static runTools(T,S,$){let M=new yM(S),f={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return M._run(()=>M._runTools(T,S,f)),M}}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 yM.runFunctions(this._client,T,S);return $f.runFunctions(this._client,T,S)}runTools(T,S){if(T.stream)return yM.runTools(this._client,T,S);return $f.runTools(this._client,T,S)}stream(T,S){return YM.createChatCompletion(this._client,T,S)}}class RJ extends i{constructor(){super(...arguments);this.completions=new pF(this._client)}}(function(T){T.Completions=pF})(RJ||(RJ={}));var u=function(T,S,$,M){if($==="a"&&!M)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?M:$==="a"?M.call(T):M?M.value:S.get(T)},CS=function(T,S,$,M,f){if(M==="m")throw new TypeError("Private method is not writable");if(M==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return M==="a"?f.call(T,$):f?f.value=$:S.set(T,$),$},$S,f1,K$,iF,T$,OM,Jf,RM,lF,xS,dF,uF,zJ,OJ,GJ,oX,gX,tX,pX,iX,dX,uX;class jS extends wJ{constructor(){super(...arguments);$S.add(this),f1.set(this,[]),K$.set(this,{}),iF.set(this,{}),T$.set(this,void 0),OM.set(this,void 0),Jf.set(this,void 0),RM.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)}[(f1=new WeakMap,K$=new WeakMap,iF=new WeakMap,T$=new WeakMap,OM=new WeakMap,Jf=new WeakMap,RM=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",(M)=>{let f=S.shift();if(f)f.resolve(M);else T.push(M)}),this.on("end",()=>{$=!0;for(let M of S)M.resolve(void 0);S.length=0}),this.on("abort",(M)=>{$=!0;for(let f of S)f.reject(M);S.length=0}),this.on("error",(M)=>{$=!0;for(let f of S)f.reject(M);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((f,J)=>S.push({resolve:f,reject:J})).then((f)=>f?{value:f,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 M=NS.fromReadableStream(T,this.controller);for await(let f of M)u(this,$S,"m",OJ).call(this,f);if(M.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,$,M,f){let J=new jS;return J._run(()=>J._runToolAssistantStream(T,S,$,M,{...f,headers:{...f?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(T,S,$,M,f){let J=f?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let F={...M,stream:!0},W=await T.submitToolOutputs(S,$,F,{...f,signal:this.controller.signal});this._connected();for await(let A of W)u(this,$S,"m",OJ).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 M=new jS;return M._run(()=>M._threadAssistantStream(T,S,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),M}static createAssistantStream(T,S,$,M){let f=new jS;return f._run(()=>f._runAssistantStream(T,S,$,{...M,headers:{...M?.headers,"X-Stainless-Helper-Method":"stream"}})),f}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,K$,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,iF,"f"))}async finalRun(){if(await this.done(),!u(this,OM,"f"))throw Error("Final run was not received.");return u(this,OM,"f")}async _createThreadAssistantStream(T,S,$){let M=$?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}let f={...S,stream:!0},J=await T.createAndRun(f,{...$,signal:this.controller.signal});this._connected();for await(let F of J)u(this,$S,"m",OJ).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,$,M){let f=M?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}let J={...$,stream:!0},F=await T.create(S,J,{...M,signal:this.controller.signal});this._connected();for await(let W of F)u(this,$S,"m",OJ).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[$,M]of Object.entries(S)){if(!T.hasOwnProperty($)){T[$]=M;continue}let f=T[$];if(f===null||f===void 0){T[$]=M;continue}if($==="index"||$==="type"){T[$]=M;continue}if(typeof f==="string"&&typeof M==="string")f+=M;else if(typeof f==="number"&&typeof M==="number")f+=M;else if($J(f)&&$J(M))f=this.accumulateDelta(f,M);else if(Array.isArray(f)&&Array.isArray(M)){if(f.every((J)=>typeof J==="string"||typeof J==="number")){f.push(...M);continue}for(let J of M){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=f[F];if(W==null)f.push(J);else f[F]=this.accumulateDelta(W,J)}continue}else throw Error(`Unhandled record type: ${$}, deltaValue: ${M}, accValue: ${f}`);T[$]=f}return T}_addRun(T){return T}async _threadAssistantStream(T,S,$){return await this._createThreadAssistantStream(S,T,$)}async _runAssistantStream(T,S,$,M){return await this._createAssistantStream(S,T,$,M)}async _runToolAssistantStream(T,S,$,M,f){return await this._createToolAssistantStream($,T,S,M,f)}}OJ=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",gX).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",oX).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,OM,"f"))throw Error("Final run has not been received");return u(this,OM,"f")},oX=function T(S){let[$,M]=u(this,$S,"m",iX).call(this,S,u(this,T$,"f"));CS(this,T$,$,"f"),u(this,iF,"f")[$.id]=$;for(let f of M){let J=$.content[f.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 f of S.data.delta.content){if(f.type=="text"&&f.text){let J=f.text,F=$.content[f.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(f.index!=u(this,Jf,"f")){if(u(this,RM,"f"))switch(u(this,RM,"f").type){case"text":this._emit("textDone",u(this,RM,"f").text,u(this,T$,"f"));break;case"image_file":this._emit("imageFileDone",u(this,RM,"f").image_file,u(this,T$,"f"));break}CS(this,Jf,f.index,"f")}CS(this,RM,$.content[f.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,Jf,"f")!==void 0){let f=S.data.content[u(this,Jf,"f")];if(f)switch(f.type){case"image_file":this._emit("imageFileDone",f.image_file,u(this,T$,"f"));break;case"text":this._emit("textDone",f.text,u(this,T$,"f"));break}}if(u(this,T$,"f"))this._emit("messageDone",S.data);CS(this,T$,void 0,"f")}},gX=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 M=S.data.delta;if(M.step_details&&M.step_details.type=="tool_calls"&&M.step_details.tool_calls&&$.step_details.type=="tool_calls")for(let J of M.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,f1,"f").push(S),this._emit("event",S)},pX=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 M=S.data;if(M.delta){let f=jS.accumulateDelta($,M.delta);u(this,K$,"f")[S.data.id]=f}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")},iX=function T(S,$){let M=[];switch(S.event){case"thread.message.created":return[S.data,M];case"thread.message.delta":if(!$)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let f=S.data;if(f.delta.content)for(let J of f.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,M.push(J);return[$,M];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if($)return[$,M];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,OM,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 Ff 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,$,M){return this._client.post(`/threads/${T}/messages/${S}`,{body:$,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.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{}Ff.MessagesPage=_J;class Wf extends i{retrieve(T,S,$,M={},f){if(BT(M))return this.retrieve(T,S,$,{},M);return this._client.get(`/threads/${T}/runs/${S}/steps/${$}`,{query:M,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S,$={},M){if(BT($))return this.list(T,S,{},$);return this._client.getAPIList(`/threads/${T}/runs/${S}/steps`,HJ,{query:$,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers}})}}class HJ extends vT{}Wf.RunStepsPage=HJ;class d$ extends i{constructor(){super(...arguments);this.steps=new Wf(this._client)}create(T,S,$){let{include:M,...f}=S;return this._client.post(`/threads/${T}/runs`,{query:{include:M},body:f,...$,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,$,M){return this._client.post(`/threads/${T}/runs/${S}`,{body:$,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.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 M=await this.create(T,S,$);return await this.poll(T,M.id,$)}createAndStream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}async poll(T,S,$){let M={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)M["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:f,response:J}=await this.retrieve(T,S,{...$,headers:{...$?.headers,...M}}).withResponse();switch(f.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 E$(F);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return f}}}stream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}submitToolOutputs(T,S,$,M){return this._client.post(`/threads/${T}/runs/${S}/submit_tool_outputs`,{body:$,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers},stream:$.stream??!1})}async submitToolOutputsAndPoll(T,S,$,M){let f=await this.submitToolOutputs(T,S,$,M);return await this.poll(T,f.id,M)}submitToolOutputsStream(T,S,$,M){return jS.createToolAssistantStream(T,S,this._client.beta.threads.runs,$,M)}}class EJ extends vT{}d$.RunsPage=EJ;d$.Steps=Wf;d$.RunStepsPage=HJ;class V$ extends i{constructor(){super(...arguments);this.runs=new d$(this._client),this.messages=new Ff(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)}}V$.Runs=d$;V$.RunsPage=EJ;V$.Messages=Ff;V$.MessagesPage=_J;var lX=async(T)=>{let S=await Promise.allSettled(T),$=S.filter((f)=>f.status==="rejected");if($.length){for(let f of $)console.error(f.reason);throw new Error(`${$.length} promise(s) failed - see the above errors`)}let M=[];for(let f of S)if(f.status==="fulfilled")M.push(f.value);return M};class Af 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`,GM,{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 M=await this.create(T,S,$);return await this.poll(T,M.id,$)}async poll(T,S,$){let M={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)M["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let f=await this.retrieve(T,S,{...$,headers:M}).withResponse(),J=f.data;switch(J.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=f.response.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await E$(F);break;case"failed":case"completed":return J}}}async upload(T,S,$){let M=await this._client.files.create({file:S,purpose:"assistants"},$);return this.create(T,{file_id:M.id},$)}async uploadAndPoll(T,S,$){let M=await this.upload(T,S,$);return await this.poll(T,M.id,$)}}class GM extends vT{}Af.VectorStoreFilesPage=GM;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 M=await this.create(T,S);return await this.poll(T,M.id,$)}listFiles(T,S,$={},M){if(BT($))return this.listFiles(T,S,{},$);return this._client.getAPIList(`/vector_stores/${T}/file_batches/${S}/files`,GM,{query:$,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers}})}async poll(T,S,$){let M={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)M["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:f,response:J}=await this.retrieve(T,S,{...$,headers:M}).withResponse();switch(f.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 E$(F);break;case"failed":case"cancelled":case"completed":return f}}}async uploadAndPoll(T,{files:S,fileIds:$=[]},M){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 f=M?.maxConcurrency??5,J=Math.min(f,S.length),F=this._client,W=S.values(),A=[...$];async function k(K){for(let w of K){let z=await F.files.create({file:w,purpose:"assistants"},M);A.push(z.id)}}let X=Array(J).fill(W).map(k);return await lX(X),await this.createAndPoll(T,{file_ids:A})}}class B$ extends i{constructor(){super(...arguments);this.files=new Af(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{}B$.VectorStoresPage=QJ;B$.Files=Af;B$.VectorStoreFilesPage=GM;B$.FileBatches=DJ;class S$ extends i{constructor(){super(...arguments);this.vectorStores=new B$(this._client),this.chat=new RJ(this._client),this.assistants=new Tf(this._client),this.threads=new V$(this._client)}}S$.VectorStores=B$;S$.VectorStoresPage=QJ;S$.Assistants=Tf;S$.AssistantsPage=WJ;S$.Threads=V$;class kf extends i{create(T,S){return this._client.post("/completions",{body:T,...S,stream:T.stream??!1})}}class Xf extends i{create(T,S){return this._client.post("/embeddings",{body:T,...S})}}class zM 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",Kf,{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 M=new Set(["processed","error","deleted"]),f=Date.now(),J=await this.retrieve(T);while(!J.status||!M.has(J.status))if(await E$(S),J=await this.retrieve(T),Date.now()-f>$)throw new AM({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class Kf extends vT{}zM.FileObjectsPage=Kf;class wf 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{}wf.FineTuningJobCheckpointsPage=UJ;class L$ extends i{constructor(){super(...arguments);this.checkpoints=new wf(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{}L$.FineTuningJobsPage=VJ;L$.FineTuningJobEventsPage=BJ;L$.Checkpoints=wf;L$.FineTuningJobCheckpointsPage=UJ;class N$ extends i{constructor(){super(...arguments);this.jobs=new L$(this._client)}}N$.Jobs=L$;N$.FineTuningJobsPage=VJ;N$.FineTuningJobEventsPage=BJ;class Yf 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 _M extends i{retrieve(T,S){return this._client.get(`/models/${T}`,S)}list(T){return this._client.getAPIList("/models",yf,T)}del(T,S){return this._client.delete(`/models/${T}`,S)}}class yf extends n0{}_M.ModelsPage=yf;class Rf 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 HM 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,...$})}}HM.Parts=LJ;var rX;class wT extends P0{constructor({baseURL:T=SJ("OPENAI_BASE_URL"),apiKey:S=SJ("OPENAI_API_KEY"),organization:$=SJ("OPENAI_ORG_ID")??null,project:M=SJ("OPENAI_PROJECT_ID")??null,...f}={}){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:M,...f,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.
27
+
28
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
29
+ If you understand the risks and have appropriate mitigations in place,
30
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
31
+
32
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
33
+
34
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
35
+ `);super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new kf(this),this.chat=new XM(this),this.embeddings=new Xf(this),this.files=new zM(this),this.images=new Yf(this),this.audio=new D$(this),this.moderations=new Rf(this),this.models=new _M(this),this.fineTuning=new N$(this),this.beta=new S$(this),this.batches=new KM(this),this.uploads=new HM(this),this._options=J,this.apiKey=S,this.organization=$,this.project=M}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 B0(T,{arrayFormat:"brackets"})}}rX=wT;wT.OpenAI=rX;wT.DEFAULT_TIMEOUT=600000;wT.OpenAIError=$T;wT.APIError=oT;wT.APIConnectionError=WM;wT.APIConnectionTimeoutError=AM;wT.APIUserAbortError=SS;wT.NotFoundError=LF;wT.ConflictError=NF;wT.RateLimitError=xF;wT.BadRequestError=UF;wT.AuthenticationError=VF;wT.InternalServerError=jF;wT.PermissionDeniedError=BF;wT.UnprocessableEntityError=CF;wT.toFile=m0;wT.fileFromPath=QF;wT.Completions=kf;wT.Chat=XM;wT.Embeddings=Xf;wT.Files=zM;wT.FileObjectsPage=Kf;wT.Images=Yf;wT.Audio=D$;wT.Moderations=Rf;wT.Models=_M;wT.ModelsPage=yf;wT.FineTuning=N$;wT.Beta=S$;wT.Batches=KM;wT.BatchesPage=sM;wT.Uploads=HM;var aX=wT;import{createHash as dY}from"crypto";import*as rT from"fs";import*as C$ from"path";function uY(T){let S=T.replace(lY,"-");if(S.length<=64)return S;let $=dY("sha256").update(T).digest("hex");return S.slice(-64)+"+"+$}var lY=/[^a-zA-Z0-9\-._]/g;class J1{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 M=C$.join(this.baseDir,`${T}/${S}.input.json`);if(!rT.existsSync(M))throw new Error(`Squirrel: input file for key "${T}" does not exist`);let f=rT.readFileSync(M,"utf-8"),J=JSON.stringify($,null,"\t");if(J!==f)throw new Error(`Squirrel: the content of the cached input file ${M} does not match the input provided.
36
+
37
+ Provided:
38
+ ${J}
39
+
40
+ Cached:
41
+ ${f}`);let F=C$.join(this.baseDir,`${T}/${S}.output.json`);return JSON.parse(rT.readFileSync(F,"utf-8"))}async write(T,S,$,M){let f=C$.join(this.baseDir,T),J=C$.join(f,`${S}.input.json`),F=C$.join(f,`${S}.output.json`),W=JSON.stringify($,null,"\t");if(!rT.existsSync(this.baseDir))rT.mkdirSync(this.baseDir);if(!rT.existsSync(f))rT.mkdirSync(f);if(rT.writeFileSync(J,W),rT.existsSync(F))rT.unlinkSync(F);let A=await M(...$);return rT.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(...M)=>{let f=$;if(this.mode!=="off"){let J=this.filenameCache.get($);if(!J)J=uY($),this.filenameCache.set($,f),f=J;this.filesTouched.get(T)?.add(f)}switch(this.mode){case"off":return S(...M);case"read":return this.read(T,f,M);case"write":return this.write(T,f,M,S);case"read-write":try{return this.read(T,f,M)}catch(J){if(J instanceof Error)return this.write(T,f,M,S);throw J}}}}}}}flush(...T){for(let[S,$]of this.filesTouched.entries())if(T.length===0||T.includes(S)){let M=C$.join(this.baseDir,S),f=rT.readdirSync(M);for(let J of f){let F=J.replace(".input.json","").replace(".output.json","");if(!$.has(F))console.log(`\uD83D\uDCA5 Flushing ${F}`),rT.unlinkSync(C$.join(M,J))}}}}function aY(T,...S){let[$,M,f,J]=S,F=[{role:"user",content:fX(M)},{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 eY(T="NO_API_KEY_PROVIDED"){let S=rY("sha256").update(T).digest("hex");return async function $(M,f){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({...M,stream:!1,response_format:{type:"json_object"}},f),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,K=k-X,w=A.completion_tokens,z=k*F1[M.model].promptPricePerToken+K*F1[M.model].promptPricePerTokenCached+w*F1[M.model].completionPricePerToken;return{data:JSON.parse(W),usdPrice:z}}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{usdFloor;usdBudget;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;constructor({model:T,usdBudget:S,usdMinimum:$,apiKey:M,cachingMode:f,cacheKey:J="openai-safegen",logger:F}){this.usdBudget=S,this.usdFloor=$,this.squirrel=new J1(f),this.getUnknownJsonFromOpenAi=eY(M),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(J,this.getUnknownJsonFromOpenAi),this.from=MX(async(...W)=>{if(this.usdBudget<this.usdFloor)return F?.warn("SafeGen budget exhausted"),W[1];let A=aY(T,...W),k=W[0],X=W[3],K=await this.getUnknownJsonFromOpenAiSquirreled.for(`${k.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${X.length}`).get(A);return this.usdBudget-=K.usdPrice,K.data})}from};import{exec as Ay}from"child_process";import{existsSync as ky}from"fs";import{readFile as Xy,writeFile as Ky}from"fs/promises";import{resolve as wy}from"path";var W1=(T)=>{let S=ES(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let $=new Map;for(let[M,f]of T.atoms)if(!M.includes("\uD83D\uDD0D")){let J=XS(f);if(f.family){let F=$.get(f.family.key);if(!F||!("familyMembers"in F))F={key:f.family.key,familyMembers:new Map},$.set(f.family.key,F);F.familyMembers.set(f.family.subKey,J)}else $.set(M,J)}return $},effects:[({setSelf:$})=>{T.on.atomCreation.subscribe("introspection",(M)=>{if(M.key.includes("\uD83D\uDD0D"))return;$((f)=>{if(M.family){let{key:J,subKey:F}=M.family,W=f.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},f.set(J,W);W.familyMembers.set(F,M)}else f.set(M.key,M);return f})}),T.on.atomDisposal.subscribe("introspection",(M)=>{$((f)=>{if(M.family){let{key:J,subKey:F}=M.family,W=f.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)f.delete(J)}}else f.delete(M.key);return f})})}]},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 M of[T.readonlySelectors,T.selectors])for(let[f,J]of M)if(!f.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(f,F)}return $},effects:[({setSelf:$})=>{T.on.selectorCreation.subscribe("introspection",(M)=>{if(M.key.includes("\uD83D\uDD0D"))return;$((f)=>{if(M.family){let{key:J,subKey:F}=M.family,W=f.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},f.set(J,W);W.familyMembers.set(F,M)}else f.set(M.key,M);return f})}),T.on.selectorDisposal.subscribe("introspection",(M)=>{$((f)=>{if(M.family){let{key:J,subKey:F}=M.family,W=f.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)f.delete(J)}}else f.delete(M.key);return f})})}]},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(M){try{if(T instanceof $)return{type:S,data:T}}catch(f){}}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 K1=new rF({object:X1,array:(T)=>Array.isArray(T)}),sY=new rF({...k1.supported,...K1.supported}),Of=(T)=>{if(T===void 0)return"undefined";let S=sY.refine(T);if(S)return S.type;return Object.getPrototypeOf(T).constructor.name};class T2{T;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),M=[...S.values()].filter((W)=>("familyMembers"in W)),f=[...$.values()].filter((W)=>("familyMembers"in W)),J=performance.now(),F=[];if(T.atomFamilies)for(let W of M){let A=W.familyMembers.values();for(let k of A){let K=this.statesCreatedAt.get(k.key)??this.auditorCreatedAt,w=J-K;F.push([k,w])}}if(T.selectorFamilies)for(let W of f){let A=W.familyMembers.values();for(let k of A){let K=this.statesCreatedAt.get(k.key)??this.auditorCreatedAt,w=J-K;F.push([k,w])}}return F}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var w1=(T,S)=>{let $=(M,f)=>{let F=((A,k)=>{let X=S(A,k);if(X)return X;return null})(M,f);if(F?.jobComplete??F?.pathComplete)return F;let W=Array.isArray(f)?f.map((A,k)=>[k,A]):X1(f)?Object.entries(f):[];for(let[A,k]of W){let X=$([...M,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 M="",f=[],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 K=$(A,X);if(K.summary!=="No Change")F.push([k,K])}}}),w1(S,(W,A)=>{let k;for(k of W)if(T[k]===void 0)f.push([k,JSON.stringify(A)])}),M=`\uFF5E${F.length} \uFF0B${f.length} \uFF0D${J.length}`,{summary:M,added:f,removed:J,changed:F}}function M7(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 M of Object.keys(T.supported)){let f=$[M];this.leafDiffers[M]=f}for(let M of Object.keys(S.supported)){let f=$[M];this.treeDiffers[M]=f}}diff(T,S){if(T===S)return{summary:"No Change"};let $=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),M=this.leafRefinery.refine(S)??this.treeRefinery.refine(S);if($!==null&&M!==null){if($.type===M.type){if($.type in this.leafDiffers)return this.leafDiffers[$.type]($.data,M.data);if($.type in this.treeDiffers)return this.treeDiffers[$.type]($.data,M.data,(W,A)=>this.diff(W,A))}}let f=Of(T),J=Of(S);if(f===J)return{summary:`${f} \u2192 ${J}`};return{summary:`Type change: ${f} \u2192 ${J}`}}}var xN=new $2(k1,K1,{number:T7,string:S7,boolean:$7,null:()=>({summary:"No Change"}),object:S2,array:M7});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:M,foreignColumns:f}=T();return{name:$,columns:M,foreignTable:f[0].table,foreignColumns:f}},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 M2(T,this)}}class M2{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(),M=S.map((F)=>F.name),f=$.map((F)=>F.name),J=[this.table[$$],...M,$[0].table[$$],...f];return T??`${J.join("_")}_fk`}}function aF(T,...S){return T(...S)}function f2(T,S){return`${T[$$]}_${S.join("_")}_unique`}function J2(T,S,$){for(let M=S;M<T.length;M++){let f=T[M];if(f==="\\"){M++;continue}if(f==='"')return[T.slice(S,M).replace(/\\/g,""),M+1];if($)continue;if(f===","||f==="}")return[T.slice(S,M).replace(/\\/g,""),M]}return[T.slice(S).replace(/\\/g,""),T.length]}function F2(T,S=0){let $=[],M=S,f=!1;while(M<T.length){let J=T[M];if(J===","){if(f||M===S)$.push("");f=!0,M++;continue}if(f=!1,J==="\\"){M+=2;continue}if(J==='"'){let[A,k]=J2(T,M+1,!0);$.push(A),M=k;continue}if(J==="}")return[$,M+1];if(J==="{"){let[A,k]=F2(T,M+1);$.push(A),M=k;continue}let[F,W]=J2(T,M,!1);$.push(F),M=W}return[$,M]}function W2(T){let[S]=F2(T,1);return S}function R1(T){return`{${T.map((S)=>{if(Array.isArray(S))return R1(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:M})=>{return aF((f,J)=>{let F=new y1(()=>{let W=f();return{columns:[T],foreignColumns:[W]}});if(J.onUpdate)F.onUpdate(J.onUpdate);if(J.onDelete)F.onDelete(J.onDelete);return F.build(S)},$,M)})}buildExtraConfigColumn(T){return new A2(T,this.config)}}class Z extends DT{constructor(T,S){if(!S.uniqueName)S.uniqueName=f2(T,[S.name]);super(T,S);this.table=T}static[y]="PgColumn"}class A2 extends Z{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,$,M){this.name=T,this.keyAsName=S,this.type=$,this.indexConfig=M}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 O1(T,this.config,S)}}class O1 extends Z{constructor(T,S,$,M){super(T,S);this.baseColumn=$,this.range=M,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((M)=>M===null?null:V(this.baseColumn,O1)?this.baseColumn.mapToDriverValue(M,!0):this.baseColumn.mapToDriverValue(M));if(S)return $;return R1($)}}var G1=Symbol.for("drizzle:isPgEnum");function X2(T){return!!T&&typeof T==="function"&&G1 in T&&T[G1]===!0}class K2 extends t{static[y]="PgEnumColumnBuilder";constructor(T,S){super(T,"string","PgEnumColumn");this.config.enum=S}build(T){return new w2(T,this.config)}}class w2 extends Z{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 f7(T,S,void 0)}function f7(T,S,$){let M=Object.assign((f)=>new K2(f??"",M),{enumName:T,enumValues:S,schema:$,[G1]:!0});return M}class aT{static[y]="Subquery";constructor(T,S,$,M=!1){this._={brand:"Subquery",sql:T,selectedFields:S,alias:$,isWith:M}}}class CJ extends aT{static[y]="WithSubquery"}var Y2="0.36.3";var z1,_1,QT={startActiveSpan(T,S){if(!z1)return S();if(!_1)_1=z1.trace.getTracer("drizzle-orm",Y2);return aF(($,M)=>M.startActiveSpan(T,(f)=>{try{return S(f)}catch(J){throw f.setStatus({code:$.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{f.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"),R2=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:R2};[$$];[H1];[sF];[TW];[y2];[E1];[SW]=!1;[J7]=!0;[R2]=void 0;constructor(T,S,$){this[$$]=this[H1]=T,this[sF]=S,this[E1]=$}}function PS(T){return T[$$]}function EM(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:M,escapeName:f,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:f(k.value),params:[]};if(k===void 0)return{sql:"",params:[]};if(Array.isArray(k)){let X=[new eT("(")];for(let[K,w]of k.entries())if(X.push(w),K<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],K=k[v.Symbol.Name];return{sql:X===void 0?f(K):f(X)+"."+f(K),params:[]}}if(V(k,DT)){let X=M.getColumnCasing(k);if(S.invokeSource==="indexes")return{sql:f(X),params:[]};let K=k.table[v.Symbol.Schema];return{sql:k.table[SW]||K===void 0?f(k.table[v.Symbol.Name])+"."+f(X):f(K)+"."+f(k.table[v.Symbol.Name])+"."+f(X),params:[]}}if(V(k,US)){let X=k[xT].schema,K=k[xT].name;return{sql:X===void 0?f(K):f(X)+"."+f(K),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 K=["none"];if(F)K=[F(k.encoder)];return{sql:J(A.value++,X),params:[X],typings:K}}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:f(k.fieldAlias),params:[]};if(V(k,aT)){if(k._.isWith)return{sql:f(k._.alias),params:[]};return this.buildQueryFromSourceParams([new eT("("),k._.sql,new eT(") "),new $W(k._.alias)],$)}if(X2(k)){if(k.schema)return{sql:f(k.schema)+"."+f(k.enumName),params:[]};return{sql:f(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 O2(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 R(T,...S){let $=[];if(S.length>0||T.length>0&&T[0]!=="")$.push(new eT(T[0]));for(let[M,f]of S.entries())$.push(f,new eT(T[M+1]));return new c($)}((T)=>{function S(){return new c([])}T.empty=S;function $(A){return new c(A)}T.fromList=$;function M(A){return new c([new eT(A)])}T.raw=M;function f(A,k){let X=[];for(let[K,w]of A.entries()){if(K>0&&k!==void 0)X.push(k);X.push(w)}return new c(X)}T.join=f;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})(R||(R={}));((T)=>{class S{constructor($,M){this.sql=$,this.fieldAlias=M}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:M}){this[xT]={name:T,originalName:T,schema:S,selectedFields:$,query:M,isExisting:!M,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 Gf{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 M=T[v.Symbol.Columns];if(!M)return M;let f={};return Object.keys(M).map((J)=>{f[J]=new Proxy(M[J],new Gf(new Proxy(T,this)))}),f}let $=T[S];if(V($,DT))return new Proxy($,new Gf(new Proxy(T,this)));return $}}function MW(T,S){return new Proxy(T,new xJ(S,!1))}function w$(T,S){return new Proxy(T,new Gf(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 R.join(T.queryChunks.map(($)=>{if(V($,DT))return w$($,S);if(V($,c))return jJ($,S);if(V($,c.Aliased))return U1($,S);return $}))}class fW extends Error{static[y]="DrizzleError";constructor({message:T,cause:S}){super(T);this.name="DrizzleError",this.cause=S}}class V1 extends fW{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function VS(T,S){if(O2(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 R`${T} = ${VS(S,T)}`},_2=(T,S)=>{return R`${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("("),R.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("("),R.join(S,new eT(" or ")),new eT(")")])}function E2(T){return R`not ${T}`}var FW=(T,S)=>{return R`${T} > ${VS(S,T)}`},D2=(T,S)=>{return R`${T} >= ${VS(S,T)}`},Q2=(T,S)=>{return R`${T} < ${VS(S,T)}`},U2=(T,S)=>{return R`${T} <= ${VS(S,T)}`};function V2(T,S){if(Array.isArray(S)){if(S.length===0)return R`false`;return R`${T} in ${S.map(($)=>VS($,T))}`}return R`${T} in ${VS(S,T)}`}function B2(T,S){if(Array.isArray(S)){if(S.length===0)return R`true`;return R`${T} not in ${S.map(($)=>VS($,T))}`}return R`${T} not in ${VS(S,T)}`}function L2(T){return R`${T} is null`}function N2(T){return R`${T} is not null`}function C2(T){return R`exists ${T}`}function x2(T){return R`not exists ${T}`}function j2(T,S,$){return R`${T} between ${VS(S,T)} and ${VS($,T)}`}function I2(T,S,$){return R`${T} not between ${VS(S,T)} and ${VS($,T)}`}function b2(T,S){return R`${T} like ${S}`}function Z2(T,S){return R`${T} not like ${S}`}function q2(T,S){return R`${T} ilike ${S}`}function m2(T,S){return R`${T} not ilike ${S}`}function h2(T){return R`${T} asc`}function v2(T){return R`${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((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),M=$.length?` -- params: [${$.join(", ")}]`:"";this.writer.write(`Query: ${T}${M}`)}}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 M={},f=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[K,w]of F.entries())if(K<F.length-1){if(!(w in X))X[w]={};X=X[w]}else{let z=S[A],O=X[w]=z===null?null:k.mapFromDriverValue(z);if($&&V(W,DT)&&F.length===2){let Q=F[0];if(!(Q in M))M[Q]=O===null?PS(W.table):!1;else if(typeof M[Q]==="string"&&M[Q]!==PS(W.table))M[Q]=!1}}return J},{});if($&&Object.keys(M).length>0){for(let[J,F]of Object.entries(M))if(typeof F==="string"&&!$[F])f[J]=null}return f}function nS(T,S){return Object.entries(T).reduce(($,[M,f])=>{if(typeof M!=="string")return $;let J=S?[...S,M]:[M];if(V(f,DT)||V(f,c)||V(f,c.Aliased))$.push({path:J,field:f});else if(V(f,v))$.push(...nS(f[v.Symbol.Columns],J));else $.push(...nS(f,J));return $},[])}function bJ(T,S){let $=Object.keys(T),M=Object.keys(S);if($.length!==M.length)return!1;for(let[f,J]of $.entries())if(J!==M[f])return!1;return!0}function WW(T,S){let $=Object.entries(S).filter(([,M])=>M!==void 0).map(([M,f])=>{if(V(f,c)||V(f,DT))return[M,f];else return[M,new IS(f,T[v.Symbol.Columns][M])]});if($.length===0)throw new Error("No values to set");return Object.fromEntries($)}function c2(T,S){for(let $ of S)for(let M of Object.getOwnPropertyNames($.prototype)){if(M==="constructor")continue;Object.defineProperty(T.prototype,M,Object.getOwnPropertyDescriptor($.prototype,M)||Object.create(null))}}function o2(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 g2(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 Z{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 Z{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function u2(T,S){let{name:$,config:M}=AT(T,S);if(M.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 Z{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 Z{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function s2(T,S){let{name:$,config:M}=AT(T,S);if(M.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 Z{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 M8(T,this.config)}}class M8 extends Z{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function f8(T,S={}){let{name:$,config:M}=AT(T,S);return new $8($,M)}class J8 extends t{static[y]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new F8(T,this.config)}}class F8 extends Z{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 Z{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:M,config:f}=AT(S,$);return new A8(M,f,T)}}class j$ extends t{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class K8 extends j${static[y]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new AW(T,this.config)}}class AW extends Z{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class w8 extends j${static[y]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new kW(T,this.config)}}class kW extends Z{static[y]="PgDateString";getSQLType(){return"date"}}function Y8(T,S){let{name:$,config:M}=AT(T,S);if(M?.mode==="date")return new K8($);return new w8($)}class y8 extends t{static[y]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new R8(T,this.config)}}class R8 extends Z{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function O8(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 Z{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 Z{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 Z{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:M}=AT(T,S);return new D8($,M)}class V8 extends t{static[y]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new KW(T,this.config)}}class KW extends Z{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 wW(T,this.config)}}class wW extends Z{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 Z{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[S,$,M]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($),Number.parseFloat(M)]}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 Z{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[S,$,M]=T.slice(1,-1).split(",");return{a:Number.parseFloat(S),b:Number.parseFloat($),c:Number.parseFloat(M)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function b8(T,S){let{name:$,config:M}=AT(T,S);if(!M?.mode||M.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 Z{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 Z{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 Z{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:M}=AT(T,S);return new n8($,M?.precision,M?.scale)}class o8 extends t{static[y]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new g8(T,this.config)}}class g8 extends Z{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 Z{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:M}=AT(T,S);if(!M?.mode||M.mode==="tuple")return new o8($);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),M=new DataView($);for(let f=0;f<8;f++)M.setUint8(f,T[S+f]);return M.getFloat64(0,!0)}function N1(T){let S=W7(T),$=0,M=S[$];$+=1;let f=new DataView(S.buffer),J=f.getUint32($,M===1);$+=4;let F;if(J&536870912)F=f.getUint32($,M===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 Z{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 Z{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:M}=AT(T,S);if(!M?.mode||M.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 T4(T,this.config)}}class T4 extends Z{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 S4(T){return new s8(T??"")}class $4 extends t{static[y]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new M4(T,this.config)}}class M4 extends Z{static[y]="PgSerial";getSQLType(){return"serial"}}function f4(T){return new $4(T??"")}class J4 extends l${static[y]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new F4(T,this.config)}}class F4 extends Z{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function W4(T){return new J4(T??"")}class A4 extends t{static[y]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new k4(T,this.config)}}class k4 extends Z{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function X4(T){return new A4(T??"")}class K4 extends t{static[y]="PgTextBuilder";constructor(T,S){super(T,"string","PgText");this.config.enumValues=S.enum}build(T){return new w4(T,this.config)}}class w4 extends Z{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Y4(T,S={}){let{name:$,config:M}=AT(T,S);return new K4($,M)}class y4 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 Z{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 R4(T,S={}){let{name:$,config:M}=AT(T,S);return new y4($,M.withTimezone??!1,M.precision)}class O4 extends j${static[y]="PgTimestampBuilder";constructor(T,S,$){super(T,"date","PgTimestamp");this.config.withTimezone=S,this.config.precision=$}build(T){return new RW(T,this.config)}}class RW extends Z{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 G4 extends j${static[y]="PgTimestampStringBuilder";constructor(T,S,$){super(T,"string","PgTimestampString");this.config.withTimezone=S,this.config.precision=$}build(T){return new OW(T,this.config)}}class OW extends Z{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:M}=AT(T,S);if(M?.mode==="string")return new G4($,M.withTimezone??!1,M.precision);return new O4($,M?.withTimezone??!1,M?.precision)}class z4 extends t{static[y]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(T){return new GW(T,this.config)}}class GW extends Z{static[y]="PgUUID";getSQLType(){return"uuid"}}function bS(T){return new z4(T??"")}class _4 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 H4(T,this.config)}}class H4 extends Z{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:M}=AT(T,S);return new _4($,M)}class E4 extends t{static[y]="PgBinaryVectorBuilder";constructor(T,S){super(T,"string","PgBinaryVector");this.config.dimensions=S.dimensions}build(T){return new D4(T,this.config)}}class D4 extends Z{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function Q4(T,S){let{name:$,config:M}=AT(T,S);return new E4($,M)}class U4 extends t{static[y]="PgHalfVectorBuilder";constructor(T,S){super(T,"array","PgHalfVector");this.config.dimensions=S.dimensions}build(T){return new V4(T,this.config)}}class V4 extends Z{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 B4(T,S){let{name:$,config:M}=AT(T,S);return new U4($,M)}class L4 extends t{static[y]="PgSparseVectorBuilder";constructor(T,S){super(T,"string","PgSparseVector");this.config.dimensions=S.dimensions}build(T){return new N4(T,this.config)}}class N4 extends Z{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function C4(T,S){let{name:$,config:M}=AT(T,S);return new L4($,M)}class x4 extends t{static[y]="PgVectorBuilder";constructor(T,S){super(T,"array","PgVector");this.config.dimensions=S.dimensions}build(T){return new j4(T,this.config)}}class j4 extends Z{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 I4(T,S){let{name:$,config:M}=AT(T,S);return new x4($,M)}function b4(){return{bigint:u2,bigserial:s2,boolean:ZJ,char:f8,cidr:W8,customType:X8,date:Y8,doublePrecision:O8,inet:_8,integer:XW,interval:U8,json:B8,jsonb:N8,line:b8,macaddr:m8,macaddr8:P8,numeric:c8,point:i8,geometry:e8,real:S4,serial:f4,smallint:W4,smallserial:X4,text:Y4,time:R4,timestamp:M$,uuid:bS,varchar:MS,bit:Q4,halfvec:B4,sparsevec:C4,vector:I4}}var C1=Symbol.for("drizzle:PgInlineForeignKeys"),Z4=Symbol.for("drizzle:EnableRLS");class fS extends v{static[y]="PgTable";static Symbol=Object.assign({},v.Symbol,{InlineForeignKeys:C1,EnableRLS:Z4});[C1]=[];[Z4]=!1;[v.Symbol.ExtraConfigBuilder]=void 0}function A7(T,S,$,M,f=T){let J=new fS(T,M,f),F=typeof S==="function"?S(b4()):S,W=Object.fromEntries(Object.entries(F).map(([X,K])=>{let w=K;w.setName(X);let z=w.build(J);return J[C1].push(...w.buildForeignKeys(z,J)),[X,z]})),A=Object.fromEntries(Object.entries(F).map(([X,K])=>{let w=K;w.setName(X);let z=w.buildExtraConfigColumn(J);return[X,z]})),k=Object.assign(J,W);if(k[v.Symbol.Columns]=W,k[v.Symbol.ExtraConfigColumns]=A,$)k[fS.Symbol.ExtraConfigBuilder]=$;return Object.assign(k,{enableRLS:()=>{return k[fS.Symbol.EnableRLS]=!0,k}})}var r$=(T,S,$)=>{return A7(T,S,$,void 0)};function q4(...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 m4(T,this.columns,this.name)}}class m4{constructor(T,S,$){this.table=T,this.columns=S,this.name=$}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[fS.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 h4{constructor(T,S){this.table=T,this.config=S}static[y]="Relations"}class a$ extends x1{constructor(T,S,$,M){super(T,S,$?.relationName);this.config=$,this.isNullable=M}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 v4(){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:R}}function P4(){return{sql:R,asc:h2,desc:v2}}function n4(T,S){if(Object.keys(T).length===1&&"default"in T&&!V(T.default,v))T=T.default;let $={},M={},f={};for(let[J,F]of Object.entries(T))if(V(F,v)){let W=EM(F),A=M[W];$[W]=J,f[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)f[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))f[J].primaryKey.push(...X.columns)}}else if(V(F,h4)){let W=EM(F.table),A=$[W],k=F.config(S(F.table)),X;for(let[K,w]of Object.entries(k))if(A){let z=f[A];if(z.relations[K]=w,X)z.primaryKey.push(...X)}else{if(!(W in M))M[W]={relations:{},primaryKey:X};M[W].relations[K]=w}}return{tables:f,tableNamesMap:$}}function k7(T){return function S($,M){return new a$(T,$,M,M?.fields.reduce((f,J)=>f&&J.notNull,!0)??!1)}}function X7(T){return function S($,M){return new mJ(T,$,M)}}function c4(T,S,$){if(V($,a$)&&$.config)return{fields:$.config.fields,references:$.config.references};let M=S[EM($.referencedTable)];if(!M)throw new Error(`Table "${$.referencedTable[v.Symbol.Name]}" not found in schema`);let f=T[M];if(!f)throw new Error(`Table "${M}" not found in schema`);let J=$.sourceTable,F=S[EM(J)];if(!F)throw new Error(`Table "${J[v.Symbol.Name]}" not found in schema`);let W=[];for(let A of Object.values(f.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 "${M}"`):new Error(`There are multiple relations between "${M}" 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 o4(T){return{one:k7(T),many:X7(T)}}function zW(T,S,$,M,f=(J)=>J){let J={};for(let[F,W]of M.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,f):X.map((K)=>zW(T,T[W.relationTableTsKey],K,W.selection,f))}else{let A=f($[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"),zf={};class cS extends Promise{constructor(T,S,$,M,f={}){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=M,this.options=f,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&&K7(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 M=new Promise((f,J)=>{this.cursorFn=(F)=>{return f({value:F,done:!1}),new Promise((W)=>$=W)},this.resolve=()=>(this.active=!1,f({done:!0})),this.reject=(F)=>(this.active=!1,J(F))});return this.execute(),M},return(){return $&&$(zf),{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 K7(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 _f extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var gT={connection:g4,postgres:t4,generic:p4,notSupported:i4};function g4(T,S,$){let{host:M,port:f}=$||S,J=Object.assign(new Error("write "+T+" "+(S.path||M+":"+f)),{code:T,errno:T,address:S.path||M},S.path?{}:{port:f});return Error.captureStackTrace(J,g4),J}function t4(T){let S=new _f(T);return Error.captureStackTrace(S,t4),S}function p4(T,S){let $=Object.assign(new Error(T+": "+S),{code:T});return Error.captureStackTrace($,p4),$}function i4(T){let S=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(S,i4),S}var w7={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,$,M){let f=Y7.map(([J,F])=>({fn:F,i:T.search(J)})).sort((J,F)=>J.i-F.i).pop();return f.i===-1?v1(this.first,M):f.fn(this.first,this.rest,S,$,M)}}function UW(T,S,$,M){let f=T instanceof Y$?T.value:T;if(f===void 0){if(T instanceof Y$?T.value=M.transform.undefined:f=T=M.transform.undefined,f===void 0)throw gT.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||r4(T.value):T.type):(S.push(T),EW(T)))}var u4=e4(w7);function m1(T,S,$,M,f,J){for(let F=1;F<T.strings.length;F++)S+=h1(S,$,M,f,J)+T.strings[F],$=T.args[F];return S}function h1(T,S,$,M,f){return S instanceof QW?S.build(T,$,M,f):S instanceof cS?q1(S,$,M,f):S instanceof nJ?S.value:S&&S[0]instanceof cS?S.reduce((J,F)=>J+" "+q1(F,$,M,f),""):UW(S,$,M,f)}function q1(T,S,$,M){return T.fragment=!0,m1(T,T.strings[0],T.args[0],S,$,M)}function l4(T,S,$,M,f){return T.map((J)=>"("+M.map((F)=>h1("values",J[F],S,$,f)).join(",")+")").join(",")}function d4(T,S,$,M,f){let J=Array.isArray(T[0]),F=S.length?S.flat():Object.keys(J?T[0]:T);return l4(J?T:[T],$,M,F,f)}function HW(T,S,$,M,f){if(typeof T==="string"&&(T=[T].concat(S)),Array.isArray(T))return v1(T,f);let J;return(S.length?S.flat():Object.keys(T)).map((W)=>{return J=T[W],(J instanceof cS?q1(J,$,M,f):J instanceof nJ?J.value:UW(J,$,M,f))+" as "+VW(f.transform.column.to?f.transform.column.to(W):W)}).join(",")}var Y7=Object.entries({values:d4,in:(...T)=>{let S=d4(...T);return S==="()"?"(null)":S},select:HW,as:HW,returning:HW,"\\(":HW,update(T,S,$,M,f){return(S.length?S.flat():Object.keys(T)).map((J)=>VW(f.transform.column.to?f.transform.column.to(J):J)+"="+h1("values",T[J],$,M,f))},insert(T,S,$,M,f){let J=S.length?S.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+v1(J,f)+")values"+l4(Array.isArray(T)?T:[T],$,M,J,f)}}).map(([T,S])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),S]);function b1(){throw gT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:y7,parsers:R7}=u4;function r4(T){if(Array.isArray(T))return r4(T[0]);return typeof T==="string"?1009:0}var a4=function(T){let S=e4(T||{});return{serializers:Object.assign({},y7,S.serializers),parsers:Object.assign({},R7,S.parsers)}};function e4(T){return Object.keys(T).reduce((S,$)=>{if(T[$].from&&[].concat(T[$].from).forEach((M)=>S.parsers[M]=T[$].parse),T[$].serialize)S.serializers[T[$].to]=T[$].serialize,T[$].from&&[].concat(T[$].from).forEach((M)=>S.serializers[M]=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},O7=/\\/g,G7=/"/g;function z7(T){return T.replace(O7,"\\\\").replace(G7,"\\\"")}var s4=function T(S,$,M,f){if(Array.isArray(S)===!1)return S;if(!S.length)return"{}";let J=S[0],F=f===1020?";":",";if(Array.isArray(J)&&!J.type)return"{"+S.map((W)=>T(W,$,M,f)).join(F)+"}";return"{"+S.map((W)=>{if(W===void 0){if(W=M.transform.undefined,W===void 0)throw gT.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,$,M){return Z1.i=Z1.last=0,SK(Z1,S,$,M)};function SK(T,S,$,M){let f=[],J=M===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==='"')f.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,f.push(SK(T,S,$,M));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&f.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!=='"')f.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&&f.push($?$(S.slice(T.last,T.i+1)):S.slice(T.last,T.i+1)),f}var DM=(T)=>{let S=T[0];for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},QM=(T)=>{let S=T[0].toUpperCase();for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},UM=(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($,M){return typeof $==="object"&&$!==null&&(M.type===114||M.type===3802)?Array.isArray($)?$.map((f)=>S(f,M)):Object.entries($).reduce((f,[J,F])=>Object.assign(f,{[T(J)]:S(F,M)}),{}):$}}DM.column={from:DM};DM.value={from:P1(DM)};hJ.column={to:hJ};var n1={...DM};n1.column.to=hJ;QM.column={from:QM};QM.value={from:P1(QM)};vJ.column={to:vJ};var c1={...QM};c1.column.to=vJ;UM.column={from:UM};UM.value={from:P1(UM)};PJ.column={to:PJ};var o1={...UM};o1.column.to=PJ;import $K from"net";import D7 from"tls";import cJ from"crypto";import g1 from"stream";import{performance as MK}from"perf_hooks";class VM 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:(M)=>{let f=S.indexOf(M);return f===-1?null:(S.splice(f,1),M)},push:(M)=>(S.push(M),M),shift:()=>{let M=S[$++];if($===S.length)$=0,S=[];else S[$-1]=void 0;return M}}}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(),fK=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(),Hf=()=>{},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:$=Hf,onend:M=Hf,onclose:f=Hf}={}){let{ssl:J,max:F,user:W,host:A,port:k,database:X,parsers:K,transform:w,onnotice:z,onnotify:O,onparameter:Q,max_pipeline:D,keep_alive:B,backoff:L,target_session_attrs:b}=T,C=ZS(),E=Q7++,_={pid:null,secret:null},U=p1(nW,T.idle_timeout),q=p1(nW,T.max_lifetime),h=p1(jK,T.connect_timeout),G=null,o,n=new VM,p=Buffer.alloc(0),RT=T.fetch_types,_T={},HS={},y$=Math.random().toString(36).slice(2),N=1,l=0,OT=0,jT=0,tT=0,FT=0,UT=0,cT=0,bT=null,LT=null,FS=!1,VT=null,oS=null,WS=null,Z$=null,pT=null,NT=null,gS=null,f$=null,m=null,Uf=null,AS={queue:S.closed,idleTimer:U,connect(Y){WS=Y||!0,OA()},terminate:Bf,execute:Vf,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){CM(H);return}return Y.on("error",CM),Y.on("close",GA),Y.on("drain",yA),Y}async function LK({pid:Y,secret:H},a,GT){try{o=r().i32(16).i32(80877102).i32(Y).i32(H).end(16),await RA(),G.once("error",GT),G.once("close",a)}catch(hT){GT(hT)}}function Vf(Y){if(FS)return uJ(Y,gT.connection("CONNECTION_DESTROYED",T));if(Y.cancelled)return;try{return Y.state=_,m?C.push(Y):(m=Y,m.active=!0),xK(Y),TS(NK(Y))&&!Y.describeFirst&&!Y.cursorFn&&C.length<D&&(!Y.options.onexecute||Y.options.onexecute(AS))}catch(H){return C.length===0&&TS(e$),J$(H),!0}}function NK(Y){if(Y.parameters.length>=65534)throw gT.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([KA(Y),fK]):Y.prepare?Y.prepared?dJ(Y):Buffer.concat([KA(Y),dJ(Y)]):CK(Y)}function KA(Y){return Buffer.concat([_A(Y.statement.string,Y.parameters,Y.statement.types,Y.statement.name),Rw("S",Y.statement.name)])}function dJ(Y){return Buffer.concat([yw(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 wA(H);return LT===null&&(LT=setImmediate(wA)),!0}function wA(Y){let H=G.write(NT,Y);return LT!==null&&clearImmediate(LT),NT=LT=null,H}function jK(){J$(gT.connection("CONNECT_TIMEOUT",T,G)),G.destroy()}async function YA(){if(TS(U7),!await new Promise((H)=>G.once("data",(a)=>H(a[0]===83)))&&J==="prefer")return NM();G.removeAllListeners(),G=D7.connect({socket:G,servername:$K.isIP(G.host)?void 0:G.host,...J==="require"||J==="allow"||J==="prefer"?{rejectUnauthorized:!1}:J==="verify-full"?{}:typeof J==="object"?J:{}}),G.on("secureConnect",NM),G.on("error",CM),G.on("close",GA),G.on("drain",yA)}function yA(){!m&&$(AS)}function PW(Y){if(VT){if(VT.push(Y),OT-=Y.length,OT>=0)return}p=VT?Buffer.concat(VT,FT-OT):p.length===0?Y:Buffer.concat([p,Y],p.length+Y.length);while(p.length>4){if(FT=p.readUInt32BE(1),FT>=p.length){OT=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),OT=0,VT=null}}async function RA(){if(FS=!1,_T={},G||(G=await BK()),!G)return;if(h.start(),T.socket)return J?YA():NM();if(G.on("connect",J?YA:NM),T.path)return G.connect(T.path);G.ssl=J,G.connect(k[jT],A[jT]),G.host=A[jT],G.port=k[jT],jT=(jT+1)%k.length}function OA(){setTimeout(RA,l?l+UT-MK.now():0)}function NM(){try{HS={},RT=T.fetch_types,y$=Math.random().toString(36).slice(2),N=1,q.start(),G.on("data",PW),B&&G.setKeepAlive&&G.setKeepAlive(!0,1000*B);let Y=Gw();TS(Y)}catch(Y){CM(Y)}}function CM(Y){if(AS.queue===S.connecting&&T.host[tT+1])return;J$(Y);while(C.length)uJ(C.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&&M(AS),!AS.reserved&&!WS&&!m&&C.length===0?(Bf(),new Promise((Y)=>G&&G.readyState!=="closed"?G.once("close",Y):Y())):Z$=new Promise((Y)=>gS=Y))}function Bf(){if(FS=!0,pT||m||WS||C.length)CM(gT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(LT),G)G.removeListener("data",PW),G.removeListener("connect",NM),G.readyState==="open"&&G.end(r().X().end());gS&&(gS(),Z$=gS=null)}async function GA(Y){if(p=Buffer.alloc(0),OT=0,VT=null,clearImmediate(LT),G.removeListener("data",PW),G.removeListener("connect",NM),U.cancel(),q.cancel(),h.cancel(),G.removeAllListeners(),G=null,WS)return OA();!Y&&(m||C.length)&&CM(gT.connection("CONNECTION_CLOSED",T,G)),l=MK.now(),Y&&T.shared.retries++,UT=(typeof L==="function"?L(T.shared.retries):L)*1000,f(AS,gT.connection("CONNECTION_CLOSED",T,G))}function IK(Y,H=Y[0]){(H===68?bK:H===100?Fw:H===65?Tw: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?Sw:H===51?$w:H===71?Mw:H===78?Aw:H===72?fw:H===99?Ww:H===73?kw:H===86?Xw:H===118?Kw:H===87?Jw:ww)(Y)}function bK(Y){let H=7,a,GT,hT,kS=m.isRaw?new Array(m.statement.columns.length):{};for(let RS=0;RS<m.statement.columns.length;RS++)GT=m.statement.columns[RS],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[RS]=m.isRaw===!0?hT:w.value.from?w.value.from(hT,GT):hT:kS[GT.name]=w.value.from?w.value.from(hT,GT):hT;m.forEachFn?m.forEachFn(w.row.from?w.row.from(kS):kS,n):n[cT++]=w.row.from?w.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,Q&&Q(H,a)}function qK(Y){if(m&&m.options.simple&&m.resolve(oS||n),m=oS=null,n=new VM,h.cancel(),WS){if(b){if(!_T.in_hot_standby||!_T.default_transaction_read_only)return aK();else if(rK(b,_T))return Bf()}if(RT)return WS===!0&&(WS=null),uK();WS!==!0&&Vf(WS),T.shared.retries=tT=0,WS=null;return}while(C.length&&(m=C.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$?Bf():(AS.reserved=null,$(AS)):AS.reserved():Z$?Bf():$(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(Uf&&(Uf(),Uf=null),n.command==="BEGIN"&&F!==1&&!AS.reserved)return J$(gT.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)oS=oS||[n],oS.push(n=new VM),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),RS=Y.readUInt16BE(a+4),q$=Y.readUInt32BE(a+6);m.statement.columns[hT]={name:w.column.from?w.column.from(Y.toString("utf8",GT,a-1)):Y.toString("utf8",GT,a-1),parser:K[q$],table:kS,number:RS,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?oK:H===10?gK:H===11?tK:H===12?pK:H!==0?Yw:Hf)(Y,H)}async function cK(){let Y=await cW();TS(r().p().str(Y).z(1).end())}async function oK(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 gK(){f$=(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="+f$).i32(r.i-Y-4,Y).end())}async function tK(Y){let H=Y.toString("utf8",9).split(",").reduce((RS,q$)=>(RS[q$[0]]=q$.slice(2),RS),{}),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="+f$+",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$(gT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),G.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(){RT=!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
+ `],[],Vf)).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)=>s4(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
+ `],[],Vf,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=gT.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,Vf(Y)}function Tw(Y){if(!O)return;let H=9;while(Y[H++]!==0);O(Y.toString("utf8",9,H-1),Y.toString("utf8",H,Y.length-1))}async function Sw(){try{let Y=await Promise.resolve(m.cursorFn(n));cT=0,Y===zf?TS(Ow(m.portal)):(n=new VM,TS(HA("",m.cursorRows)))}catch(Y){TS(e$),m.reject(Y)}}function $w(){n.count&&m.cursorFn(n),m.resolve(n)}function Mw(){pT=new g1.Writable({autoDestroy:!0,write(Y,H,a){G.write(r().d().raw(Y).end(),a)},destroy(Y,H){H(Y),G.write(r().f().str(Y+r.N).end()),pT=null},final(Y){G.write(r().c().end()),Uf=Y}}),m.resolve(pT)}function fw(){pT=new g1.Readable({read(){G.resume()}}),m.resolve(pT)}function Jw(){pT=new g1.Duplex({autoDestroy:!0,read(){G.resume()},write(Y,H,a){G.write(r().d().raw(Y).end(),a)},destroy(Y,H){H(Y),G.write(r().f().str(Y+r.N).end()),pT=null},final(Y){G.write(r().c().end()),Uf=Y}}),m.resolve(pT)}function Fw(Y){pT&&(pT.push(Y.subarray(5))||G.pause())}function Ww(){pT&&pT.push(null),pT=null}function Aw(Y){z?z(t1(Y)):console.log(t1(Y))}function kw(){}function Xw(){J$(gT.notSupported("FunctionCallResponse"))}function Kw(){J$(gT.notSupported("NegotiateProtocolVersion"))}function ww(Y){console.error("Postgres.js : Unknown Message:",Y[0])}function Yw(Y,H){console.error("Postgres.js : Unknown Auth:",H)}function yw(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((RS,q$)=>{if(RS===null)return r.i32(4294967295);kS=H[q$],Y[q$]=RS=kS in T.serializers?T.serializers[kS](RS):""+RS,hT=r.i,r.inc(4).str(RS).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 Rw(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(),fK])}function Ow(Y=""){return Buffer.concat([r().C().str("P").str(Y+r.N).end(),r().S().end()])}function Gw(){return o||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 M=5;M<T.length-1;M++)if(T[M]===0)S[N7[T[$]]]=T.toString("utf8",$+1,M),$=M+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),M=Buffer.allocUnsafe($);for(let f=0;f<$;f++)M[f]=T[f]^S[f];return M}function p1(T,S){if(S=typeof S==="function"?S():S,!S)return{cancel:Hf,start:Hf};let $;return{cancel(){$&&(clearTimeout($),$=null)},start(){$&&clearTimeout($),$=setTimeout(M,S*1000,arguments)}};function M(f){T.apply(null,f),$=null}}var WK=()=>{};function d1(T,S){let $=new Map,M="postgresjs_"+Math.random().toString(36).slice(2),f={},J,F,W=!1,A=K.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,f.pid=f.secret=void 0,w(await z(A,M,S.publications)),$.forEach((Q)=>Q.forEach(({onsubscribe:D})=>D()))},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()},K;async function K(Q,D,B=WK,L=WK){if(Q=b7(Q),!J)J=z(A,M,S.publications);let b={fn:D,onsubscribe:B},C=$.has(Q)?$.get(Q).add(b):$.set(Q,new Set([b])).get(Q),E=()=>{C.delete(b),C.size===0&&$.delete(Q)};return J.then((_)=>{return w(_),B(),F&&F.on("error",L),{unsubscribe:E,state:f,sql:A}})}function w(Q){F=Q.stream,f.pid=Q.state.pid,f.secret=Q.state.secret}async function z(Q,D,B){if(!B)throw new Error("Missing publication names");let L=await Q.unsafe(`CREATE_REPLICATION_SLOT ${D} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[b]=L,C=await Q.unsafe(`START_REPLICATION SLOT ${D} LOGICAL ${b.consistent_point} (proto_version '1', publication_names '${B}')`).writable(),E={lsn:Buffer.concat(b.consistent_point.split("/").map((G)=>Buffer.from(("00000000"+G).slice(-8),"hex")))};return C.on("data",U),C.on("error",_),C.on("close",Q.close),{stream:C,state:L.state};function _(G){console.error("Unexpected error during logical streaming - reconnecting",G)}function U(G){if(G[0]===119)I7(G.subarray(25),E,Q.options.parsers,q,S.transform);else if(G[0]===107&&G[17])E.lsn=G.subarray(1,9),h()}function q(G,o){let n=o.relation.schema+"."+o.relation.table;O("*",G,o),O("*:"+n,G,o),o.relation.keys.length&&O("*:"+n+"="+o.relation.keys.map((p)=>G[p.name]),G,o),O(o.command,G,o),O(o.command+":"+n,G,o),o.relation.keys.length&&O(o.command+":"+n+"="+o.relation.keys.map((p)=>G[p.name]),G,o)}function h(){let G=Buffer.alloc(34);G[0]=114,G.fill(E.lsn,1),G.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),C.write(G)}}function O(Q,D,B){$.has(Q)&&$.get(Q).forEach(({fn:L})=>L(D,B,Q))}}function j7(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function I7(T,S,$,M,f){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:f.column.from?f.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,f);M(k,{command:"insert",relation:A})},D:(F)=>{let W=1,A=S[F.readUInt32BE(W)];W+=4;let k=F[W]===75;M(k||F[W]===79?NW(F,A.columns,W+=3,f).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,f):null;X&&(W=X.i);let{row:K}=NW(F,A.columns,W+3,f);M(K,{command:"update",relation:A,key:k,old:X&&X.row})},T:()=>{},C:()=>{}}).reduce(J,{})[T[0]](T)}function NW(T,S,$,M){let f,J,F,W=M.raw?new Array(S.length):{};for(let A=0;A<S.length;A++)f=T[$++],J=S[A],F=f===110?null:f===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($))),M.raw?W[A]=M.raw===!0?F:M.value.from?M.value.from(F,J):F:W[J.name]=M.value.from?M.value.from(F,J):F;return{i:$,row:M.row.from?M.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[,$,M,f]=S;return($||"*")+(M?":"+(M.indexOf(".")===-1?"public."+M:M):"")+(f?"="+f:"")}import AK from"stream";function u1(T,S,$=393216){return new Promise(async(M,f)=>{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:(K)=>J`select loread(${W}, ${K}) as data`,write:(K)=>J`select lowrite(${W}, ${K})`,truncate:(K)=>J`select lo_truncate64(${W}, ${K})`,seek:(K,w=0)=>J`select lo_lseek64(${W}, ${K}, ${w})`,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 M(A),new Promise(async(K)=>F=K);async function k({highWaterMark:K=16384,start:w=0,end:z=1/0}={}){let O=z-w;return w&&await A.seek(w),new AK.Readable({highWaterMark:K,async read(Q){let D=Q>O?Q-O:Q;O-=Q;let[{data:B}]=await A.read(D);if(this.push(B),B.length<Q)this.push(null)}})}async function X({highWaterMark:K=16384,start:w=0}={}){return w&&await A.seek(w),new AK.Writable({highWaterMark:K,write(z,O,Q){A.write(z).then(()=>Q(),Q)}})}}).catch(f)})}Object.assign(CW,{PostgresError:_f,toPascal:QM,pascal:c1,toCamel:DM,camel:n1,toKebab:UM,kebab:o1,fromPascal:vJ,fromCamel:hJ,fromKebab:PJ,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var Ef=CW;function CW(T,S){let $=m7(T,S),M=$.no_subscribe||d1(CW,{...$}),f=!1,J=ZS(),F=ZS(),W=ZS(),A=ZS(),k=ZS(),X=ZS(),K=ZS(),w=ZS(),z={connecting:F,reserved:W,closed:A,ended:k,open:X,busy:K,full:w},O=[...Array($.max)].map(()=>i1($,z,{onopen:HS,onend:_T,onclose:y$})),Q=D(q);return Object.assign(Q,{get parameters(){return $.parameters},largeObject:u1.bind(null,Q),subscribe:M,CLOSE:zf,END:zf,PostgresError:_f,options:$,reserve:b,listen:B,begin:C,close:n,end:o}),Q;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(OT,{types:l,typed:l,unsafe:jT,notify:L,array:U,json:_,file:tT}),OT;function l(FT,UT){return new Y$(FT,UT)}function OT(FT,...UT){return FT&&Array.isArray(FT.raw)?new cS(FT,UT,N,G):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,G,{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)})},G,{...cT,simple:"simple"in cT?cT.simple:UT.length===0})}}async function B(N,l,OT){let jT={fn:l,onlisten:OT},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 Q`select pg_notify(${N}, ${""+l})`}async function b(){let N=ZS(),l=X.length?X.shift():await new Promise((tT)=>{J.push({reserve:tT}),A.length&&RT(A.shift())});E(l,W),l.reserved=()=>N.length?l.execute(N.shift()):E(l,W),l.reserved.release=!0;let OT=D(jT);return OT.release=()=>{l.reserved=null,HS(l)},OT;function jT(tT){l.queue===w?N.push(tT):l.execute(tT)||E(l,w)}}async function C(N,l){!l&&(l=N,N="");let OT=ZS(),jT=0,tT,FT=null;try{return await Q.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 oS,WS;FS&&await VT`savepoint ${VT(FS)}`;try{if(WS=await new Promise((NT,gS)=>{let f$=LT(VT);Promise.resolve(Array.isArray(f$)?Promise.all(f$):f$).then(NT,gS)}),oS)throw oS}catch(NT){throw await(FS?VT`rollback to ${VT(FS)}`:VT`rollback`),NT instanceof _f&&NT.code==="25P02"&&oS||NT}if(!FS)FT?await VT`prepare transaction '${VT.unsafe(FT)}'`:await VT`commit`;return WS;function Z$(NT,gS){if(NT&&Array.isArray(NT.raw))return Z$((f$)=>f$.apply(f$,arguments));return arguments.length===1&&(gS=NT,NT=null),UT(bT,gS,"s"+jT+++(NT?"_"+NT:""))}function pT(NT){NT.catch((gS)=>oS||(oS=gS)),bT.queue===w?OT.push(NT):bT.execute(NT)||E(bT,w)}}function cT(bT){tT=bT,E(bT,W),bT.reserved=()=>OT.length?bT.execute(OT.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 U(N,l){if(!Array.isArray(N))return U(Array.from(arguments));return new Y$(N,l||(N.length?EW(N)||25:0),$.shared.typeArrayMap)}function q(N){if(f)return N.reject(gT.connection("CONNECTION_ENDED",$,$));if(X.length)return h(X.shift(),N);if(A.length)return RT(A.shift(),N);K.length?h(K.shift(),N):J.push(N)}function h(N,l){return N.execute(l)?E(N,K):E(N,w)}function G(N){return new Promise((l,OT)=>{N.state?N.active?i1($).cancel(N.state,l,OT):N.cancelled={resolve:l,reject:OT}:(J.remove(N),N.cancelled=!0,N.reject(gT.generic("57014","canceling statement due to user request")),l())})}async function o({timeout:N=null}={}){if(f)return f;await 1;let l;return f=Promise.race([new Promise((OT)=>N!==null&&(l=setTimeout(p,N*1000,OT))),Promise.all(O.map((OT)=>OT.end()).concat(B.sql?B.sql.end({timeout:0}):[],M.sql?M.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(l))}async function n(){await Promise.all(O.map((N)=>N.end()))}async function p(N){await Promise.all(O.map((l)=>l.terminate()));while(J.length)J.shift().reject(gT.connection("CONNECTION_DESTROYED",$));N()}function RT(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)),OT=!0;while(OT&&J.length&&l-- >0){let jT=J.shift();if(jT.reserve)return jT.reserve(N);OT=N.execute(jT)}OT?E(N,K):E(N,w)}function y$(N,l){E(N,A),N.reserved=null,N.onclose&&(N.onclose(l),N.onclose=null),$.onclose&&$.onclose(N.id),J.length&&RT(N,J.shift())}}function m7(T,S){if(T&&T.shared)return T;let $=process.env,M=(!T||typeof T==="string"?S:T)||{},{url:f,multihost:J}=c7(T),F=[...f.searchParams].reduce((w,[z,O])=>(w[z]=O,w),{}),W=M.hostname||M.host||J||f.hostname||$.PGHOST||"localhost",A=M.port||f.port||$.PGPORT||5432,k=M.user||M.username||f.username||$.PGUSERNAME||$.PGUSER||o7();M.no_prepare&&(M.prepare=!1),F.sslmode&&(F.ssl=F.sslmode,delete F.sslmode),"timeout"in M&&(console.log("The timeout option is deprecated, use idle_timeout instead"),M.idle_timeout=M.timeout),F.sslrootcert==="system"&&(F.ssl="verify-full");let X=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],K={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((w)=>w.split(":")[0]),port:Array.isArray(A)?A:W.split(",").map((w)=>parseInt(w.split(":")[1]||A)),path:M.path||W.indexOf("/")>-1&&W+"/.s.PGSQL."+A,database:M.database||M.db||(f.pathname||"").slice(1)||$.PGDATABASE||k,user:k,pass:M.pass||M.password||f.password||$.PGPASSWORD||"",...Object.entries(K).reduce((w,[z,O])=>{let Q=z in M?M[z]:(z in F)?F[z]==="disable"||F[z]==="false"?!1:F[z]:$["PG"+z.toUpperCase()]||O;return w[z]=typeof Q==="string"&&X.includes(z)?+Q:Q,w},{}),connection:{application_name:"postgres.js",...M.connection,...Object.entries(F).reduce((w,[z,O])=>((z in K)||(w[z]=O),w),{})},types:M.types||{},target_session_attrs:h7(M,f,$),onnotice:M.onnotice,onnotify:M.onnotify,onclose:M.onclose,onparameter:M.onparameter,socket:M.socket,transform:n7(M.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...a4(M.types)}}function h7(T,S,$){let M=T.target_session_attrs||S.searchParams.get("target_session_attrs")||$.PGTARGETSESSIONATTRS;if(!M||["read-write","read-only","primary","standby","prefer-standby"].includes(M))return M;throw new Error("target_session_attrs "+M+" 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 o7(){try{return Z7.userInfo().username}catch(T){return process.env.USERNAME||"runner"}}class xW extends zS{constructor(T,S,$,M){super();this.session=S,this.dialect=$,this.config={table:T,withList:M}}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)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})};$dynamic(){return this}}function g7(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(($,M,f)=>{let J=f===0?M.toLowerCase():`${M[0].toUpperCase()}${M.slice(1)}`;return $+J},"")}function p7(T){return T}class l1{static[y]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?g7: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],M=`${S}.${$}.${T.name}`;if(!this.cache[M])this.cacheTable(T.table);return this.cache[M]}cacheTable(T){let S=T[v.Symbol.Schema]??"public",$=T[v.Symbol.OriginalName],M=`${S}.${$}`;if(!this.cachedTables[M]){for(let f of Object.values(T[v.Symbol.Columns])){let J=`${M}.${f.name}`;this.cache[J]=this.convert(f.name)}this.cachedTables[M]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class oJ extends US{static[y]="PgViewBase"}class BM{static[y]="PgDialect";casing;constructor(T){this.casing=new l1(T?.casing)}async migrate(T,S,$){let M=typeof $==="string"?"__drizzle_migrations":$.migrationsTable??"__drizzle_migrations",f=typeof $==="string"?"drizzle":$.migrationsSchema??"drizzle",J=R`
64
+ CREATE TABLE IF NOT EXISTS ${R.identifier(f)}.${R.identifier(M)} (
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(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(f)}`),await S.execute(J);let W=(await S.all(R`select id, hash, created_at from ${R.identifier(f)}.${R.identifier(M)} 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(f)}.${R.identifier(M)} ("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[$,M]of T.entries())if(S.push(R`${R.identifier(M._.alias)} as (${M._.sql})`),$<T.length-1)S.push(R`, `);return S.push(R` `),R.join(S)}buildDeleteQuery({table:T,where:S,returning:$,withList:M}){let f=this.buildWithCTE(M),J=$?R` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,F=S?R` where ${S}`:void 0;return R`${f}delete from ${T}${F}${J}`}buildUpdateSet(T,S){let $=T[v.Symbol.Columns],M=Object.keys($).filter((J)=>S[J]!==void 0||$[J]?.onUpdateFn!==void 0),f=M.length;return R.join(M.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<f-1)return[k,R.raw(", ")];return[k]}))}buildUpdateQuery({table:T,set:S,where:$,returning:M,withList:f,from:J,joins:F}){let W=this.buildWithCTE(f),A=T[fS.Symbol.Name],k=T[fS.Symbol.Schema],X=T[fS.Symbol.OriginalName],K=A===X?void 0:A,w=R`${k?R`${R.identifier(k)}.`:void 0}${R.identifier(X)}${K&&R` ${R.identifier(K)}`}`,z=this.buildUpdateSet(T,S),O=J&&R.join([R.raw(" from "),this.buildFromTable(J)]),Q=this.buildJoins(F),D=M?R` returning ${this.buildSelection(M,{isSingleTable:!J})}`:void 0,B=$?R` where ${$}`:void 0;return R`${W}update ${w} set ${z}${O}${Q}${B}${D}`}buildSelection(T,{isSingleTable:S=!1}={}){let $=T.length,M=T.flatMap(({field:f},J)=>{let F=[];if(V(f,c.Aliased)&&f.isSelectionField)F.push(R.identifier(f.fieldAlias));else if(V(f,c.Aliased)||V(f,c)){let W=V(f,c.Aliased)?f.sql:f;if(S)F.push(new c(W.queryChunks.map((A)=>{if(V(A,Z))return R.identifier(this.casing.getColumnCasing(A));return A})));else F.push(W);if(V(f,c.Aliased))F.push(R` as ${R.identifier(f.fieldAlias)}`)}else if(V(f,DT))if(S)F.push(R.identifier(this.casing.getColumnCasing(f)));else F.push(f);if(J<$-1)F.push(R`, `);return F});return R.join(M)}buildJoins(T){if(!T||T.length===0)return;let S=[];for(let[$,M]of T.entries()){if($===0)S.push(R` `);let f=M.table,J=M.lateral?R` lateral`:void 0;if(V(f,fS)){let F=f[fS.Symbol.Name],W=f[fS.Symbol.Schema],A=f[fS.Symbol.OriginalName],k=F===A?void 0:M.alias;S.push(R`${R.raw(M.joinType)} join${J} ${W?R`${R.identifier(W)}.`:void 0}${R.identifier(A)}${k&&R` ${R.identifier(k)}`} on ${M.on}`)}else if(V(f,US)){let F=f[xT].name,W=f[xT].schema,A=f[xT].originalName,k=F===A?void 0:M.alias;S.push(R`${R.raw(M.joinType)} join${J} ${W?R`${R.identifier(W)}.`:void 0}${R.identifier(A)}${k&&R` ${R.identifier(k)}`} on ${M.on}`)}else S.push(R`${R.raw(M.joinType)} join${J} ${f} on ${M.on}`);if($<T.length-1)S.push(R` `)}return R.join(S)}buildFromTable(T){if(V(T,v)&&T[v.Symbol.OriginalName]!==T[v.Symbol.Name]){let S=R`${R.identifier(T[v.Symbol.OriginalName])}`;if(T[v.Symbol.Schema])S=R`${R.identifier(T[v.Symbol.Schema])}.${S}`;return R`${S} ${R.identifier(T[v.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:S,fieldsFlat:$,where:M,having:f,table:J,joins:F,orderBy:W,groupBy:A,limit:k,offset:X,lockingClause:K,distinct:w,setOperators:z}){let O=$??nS(S);for(let p of O)if(V(p.field,DT)&&PS(p.field.table)!==(V(J,aT)?J._.alias:V(J,oJ)?J[xT].name:V(J,c)?void 0:PS(J))&&!((RT)=>F?.some(({alias:_T})=>_T===(RT[v.Symbol.IsAlias]?PS(RT):RT[v.Symbol.BaseName])))(p.field.table)){let RT=PS(p.field.table);throw new Error(`Your "${p.path.join("->")}" field references a column "${RT}"."${p.field.name}", but the table "${RT}" is not part of the query! Did you forget to join it?`)}let Q=!F||F.length===0,D=this.buildWithCTE(T),B;if(w)B=w===!0?R` distinct`:R` distinct on (${R.join(w.on,R`, `)})`;let L=this.buildSelection(O,{isSingleTable:Q}),b=this.buildFromTable(J),C=this.buildJoins(F),E=M?R` where ${M}`:void 0,_=f?R` having ${f}`:void 0,U;if(W&&W.length>0)U=R` order by ${R.join(W,R`, `)}`;let q;if(A&&A.length>0)q=R` group by ${R.join(A,R`, `)}`;let h=typeof k==="object"||typeof k==="number"&&k>=0?R` limit ${k}`:void 0,G=X?R` offset ${X}`:void 0,o=R.empty();if(K){let p=R` for ${R.raw(K.strength)}`;if(K.config.of)p.append(R` of ${R.join(Array.isArray(K.config.of)?K.config.of:[K.config.of],R`, `)}`);if(K.config.noWait)p.append(R` no wait`);else if(K.config.skipLocked)p.append(R` skip locked`);o.append(p)}let n=R`${D}select${B} ${L} from ${b}${C}${E}${q}${_}${U}${h}${G}${o}`;if(z.length>0)return this.buildSetOperations(n,z);return n}buildSetOperations(T,S){let[$,...M]=S;if(!$)throw new Error("Cannot pass undefined values to any set operator");if(M.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:$}),M)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:$,rightSelect:M,limit:f,orderBy:J,offset:F}}){let W=R`(${T.getSQL()}) `,A=R`(${M.getSQL()})`,k;if(J&&J.length>0){let z=[];for(let O of J)if(V(O,Z))z.push(R.identifier(O.name));else if(V(O,c)){for(let Q=0;Q<O.queryChunks.length;Q++){let D=O.queryChunks[Q];if(V(D,Z))O.queryChunks[Q]=R.identifier(D.name)}z.push(R`${O}`)}else z.push(R`${O}`);k=R` order by ${R.join(z,R`, `)} `}let X=typeof f==="object"||typeof f==="number"&&f>=0?R` limit ${f}`:void 0,K=R.raw(`${S} ${$?"all ":""}`),w=F?R` offset ${F}`:void 0;return R`${W}${K}${A}${k}${X}${w}`}buildInsertQuery({table:T,values:S,onConflict:$,returning:M,withList:f,select:J}){let F=[],W=T[v.Symbol.Columns],A=Object.entries(W).filter(([O,Q])=>!Q.shouldDisableInsert()),k=A.map(([,O])=>R.identifier(this.casing.getColumnCasing(O)));if(J){let O=S;if(V(O,c))F.push(O);else F.push(O.getSQL())}else{let O=S;F.push(R.raw("values "));for(let[Q,D]of O.entries()){let B=[];for(let[L,b]of A){let C=D[L];if(C===void 0||V(C,IS)&&C.value===void 0)if(b.defaultFn!==void 0){let E=b.defaultFn(),_=V(E,c)?E:R.param(E,b);B.push(_)}else if(!b.default&&b.onUpdateFn!==void 0){let E=b.onUpdateFn(),_=V(E,c)?E:R.param(E,b);B.push(_)}else B.push(R`default`);else B.push(C)}if(F.push(B),Q<O.length-1)F.push(R`, `)}}let X=this.buildWithCTE(f),K=R.join(F),w=M?R` returning ${this.buildSelection(M,{isSingleTable:!0})}`:void 0,z=$?R` on conflict ${$}`:void 0;return R`${X}insert into ${T} ${k} ${K}${z}${w}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:$}){let M=S?R` concurrently`:void 0,f=$?R` with no data`:void 0;return R`refresh materialized view${M} ${T}${f}`}prepareTyping(T){if(V(T,wW)||V(T,KW))return"json";else if(V(T,YW))return"decimal";else if(V(T,yW))return"time";else if(V(T,RW)||V(T,OW))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:M,tableConfig:f,queryConfig:J,tableAlias:F,nestedQueryRelation:W,joinOn:A}){let k=[],X,K,w=[],z,O=[];if(J===!0)k=Object.entries(f.columns).map(([B,L])=>({dbKey:L.name,tsKey:B,field:w$(L,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let D=Object.fromEntries(Object.entries(f.columns).map(([_,U])=>[_,w$(U,F)]));if(J.where){let _=typeof J.where==="function"?J.where(D,v4()):J.where;z=_&&jJ(_,F)}let B=[],L=[];if(J.columns){let _=!1;for(let[U,q]of Object.entries(J.columns)){if(q===void 0)continue;if(U in f.columns){if(!_&&q===!0)_=!0;L.push(U)}}if(L.length>0)L=_?L.filter((U)=>J.columns?.[U]===!0):Object.keys(f.columns).filter((U)=>!L.includes(U))}else L=Object.keys(f.columns);for(let _ of L){let U=f.columns[_];B.push({tsKey:_,value:U})}let b=[];if(J.with)b=Object.entries(J.with).filter((_)=>!!_[1]).map(([_,U])=>({tsKey:_,queryConfig:U,relation:f.relations[_]}));let C;if(J.extras){C=typeof J.extras==="function"?J.extras(D,{sql:R}):J.extras;for(let[_,U]of Object.entries(C))B.push({tsKey:_,value:U1(U,F)})}for(let{tsKey:_,value:U}of B)k.push({dbKey:V(U,c.Aliased)?U.fieldAlias:f.columns[_].name,tsKey:_,field:V(U,DT)?w$(U,F):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof J.orderBy==="function"?J.orderBy(D,P4()):J.orderBy??[];if(!Array.isArray(E))E=[E];w=E.map((_)=>{if(V(_,DT))return w$(_,F);return jJ(_,F)}),X=J.limit,K=J.offset;for(let{tsKey:_,queryConfig:U,relation:q}of b){let h=c4(S,$,q),G=EM(q.referencedTable),o=$[G],n=`${F}_${_}`,p=IJ(...h.fields.map((HS,y$)=>JW(w$(h.references[y$],n),w$(HS,F)))),RT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[o],tableConfig:S[o],queryConfig:V(q,a$)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:n,joinOn:p,nestedQueryRelation:q}),_T=R`${R.identifier(n)}.${R.identifier("data")}`.as(_);O.push({on:R`true`,table:new aT(RT.sql,{},n),alias:n,joinType:"left",lateral:!0}),k.push({dbKey:_,tsKey:_,field:_T,relationTableTsKey:o,isJson:!0,selection:RT.selection})}}if(k.length===0)throw new fW({message:`No fields selected for table "${f.tsName}" ("${F}")`});let Q;if(z=IJ(A,z),W){let D=R`json_build_array(${R.join(k.map(({field:b,tsKey:C,isJson:E})=>E?R`${R.identifier(`${F}_${C}`)}.${R.identifier("data")}`:V(b,c.Aliased)?b.sql:b),R`, `)})`;if(V(W,mJ))D=R`coalesce(json_agg(${D}${w.length>0?R` order by ${R.join(w,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:D.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:k}];if(X!==void 0||K!==void 0||w.length>0)Q=this.buildSelectQuery({table:MW(M,F),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:z,limit:X,offset:K,orderBy:w,setOperators:[]}),z=void 0,X=void 0,K=void 0,w=[];else Q=MW(M,F);Q=this.buildSelectQuery({table:V(Q,fS)?Q:new aT(Q,{},F),fields:{},fieldsFlat:B.map(({field:b})=>({path:[],field:V(b,DT)?w$(b,F):b})),joins:O,where:z,limit:X,offset:K,orderBy:w,setOperators:[]})}else Q=this.buildSelectQuery({table:MW(M,F),fields:{},fieldsFlat:k.map(({field:D})=>({path:[],field:V(D,DT)?w$(D,F):D})),joins:O,where:z,limit:X,offset:K,orderBy:w,setOperators:[]});return{tableTsKey:f.tsName,sql:Q,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 M=(V(T,aT)?T._.selectedFields:V(T,US)?T[xT].selectedFields:T)[S];if(V(M,c.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!M.isSelectionField)return M.sql;let f=M.clone();return f.isSelectionField=!0,f}if(V(M,c)){if(this.config.sqlBehavior==="sql")return M;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(M,DT)){if(this.config.alias)return new Proxy(M,new Gf(new Proxy(M.table,new xJ(this.config.alias,this.config.replaceOriginalName??!1))));return M}if(typeof M!=="object"||M===null)return M;return new Proxy(M,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}from(T){let S=!!this.fields,$;if(this.fields)$=this.fields;else if(V(T,aT))$=Object.fromEntries(Object.keys(T._.selectedFields).map((M)=>[M,T[M]]));else if(V(T,oJ))$=T[xT].selectedFields;else if(V(T,c))$={};else $=o2(T);return new a1({table:T,fields:$,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class kK extends r1{static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:$,session:M,dialect:f,withList:J,distinct:F}){super();this.config={withList:J,table:T,fields:{...S},distinct:F,setOperators:[]},this.isPartialSelect=$,this.session=M,this.dialect=f,this._={selectedFields:S},this.tableName=x$(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,$)=>{let M=this.tableName,f=x$(S);if(typeof f==="string"&&this.config.joins?.some((J)=>J.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof M==="string")this.config.fields={[M]:this.config.fields};if(typeof f==="string"&&!V(S,c)){let J=V(S,aT)?S._.selectedFields:V(S,US)?S[xT].selectedFields:S[v.Symbol.Columns];this.config.fields[f]=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:f}),typeof f==="string")switch(T){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[f]=!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 M=typeof $==="function"?$(i7()):$;if(!bJ(this.getSelectedFields(),M.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:M}),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:M,joinsNotNullableMap:f}=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(M.sqlToQuery(this.getSQL()),J,T,!0);return F.joinsNotNullableMap=f,F})}prepare(T){return this._prepare(T)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}c2(a1,[zS]);function Df(T,S){return($,M,...f)=>{let J=[M,...f].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=Df("union",!1),u7=Df("union",!0),l7=Df("intersect",!1),r7=Df("intersect",!0),a7=Df("except",!1),e7=Df("except",!0);class gJ{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=V(T,BM)?T:void 0,this.dialectConfig=V(T,BM)?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 M(J){return new _S({fields:J??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function f(J,F){return new _S({fields:F??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:J}})}return{select:$,selectDistinct:M,selectDistinctOn:f}}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 BM(this.dialectConfig);return this.dialect}}class jW{constructor(T,S,$,M){this.table=T,this.session=S,this.dialect=$,this.withList=M}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 M={},f=this.table[v.Symbol.Columns];for(let J of Object.keys($)){let F=$[J];M[J]=V(F,c)?F:new IS(F,f[J])}return M});return new e1(this.table,S,this.session,this.dialect,this.withList)}select(T){let S=typeof T==="function"?T(new gJ):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,$,M,f,J){super();this.session=$,this.dialect=M,this.config={table:T,values:S,withList:f,select:J}}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=R`do nothing`;else{let S="";S=Array.isArray(T.target)?T.target.map((M)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(M))).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,M=T.setWhere?R` where ${T.setWhere}`:void 0,f=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=R`(${R.raw(J)})${$} do update set ${f}${S}${M}`,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}}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)}execute=(T)=>{return QT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}class IW{constructor(T,S,$,M){this.table=T,this.session=S,this.dialect=$,this.withList=M}static[y]="PgUpdateBuilder";set(T){return new XK(this.table,WW(this.table,T),this.session,this.dialect,this.withList)}}class XK extends zS{constructor(T,S,$,M,f){super();this.session=$,this.dialect=M,this.config={set:S,table:T,withList:f,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,fS))return T[v.Symbol.Columns];else if(V(T,aT))return T._.selectedFields;return T[xT].selectedFields}createJoin(T){return(S,$)=>{let M=x$(S);if(typeof M==="string"&&this.config.joins.some((f)=>f.alias===M))throw new Error(`Alias "${M}" is already used in this query`);if(typeof $==="function"){let f=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"})),f&&new Proxy(f,new JS({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}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(([f])=>[f,!1])),this.joinsNotNullableMap[M]=!0;break}case"inner":{this.joinsNotNullableMap[M]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[M]=!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 M=x$($.table);if(typeof M==="string"&&!V($.table,c)){let f=this.getTableLikeFields($.table);T[M]=f}}}}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)}execute=(T)=>{return this._prepare().execute(T)};$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;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 SA{constructor(T,S,$,M,f,J,F){this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=M,this.tableConfig=f,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,$,M,f,J,F,W,A){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=M,this.tableConfig=f,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,(M,f)=>{let J=M.map((F)=>zW(this.schema,this.tableConfig,F,S.selection,f));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 $A extends zS{constructor(T,S,$,M){super();this.execute=T,this.sql=S,this.query=$,this.mapBatchResult=M}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[M,f]of Object.entries(this._.schema))this.query[M]=new SA($.fullSchema,this._.schema,this._.tableNamesMap,$.fullSchema[M],f,T,S)}static[y]="PgDatabase";query;$with(T){let S=this;return{as($){if(typeof $==="function")$=$(new gJ(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 M(A){return new _S({fields:A??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function f(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:M,selectDistinctOn:f,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)}execute(T){let S=typeof T==="string"?R.raw(T):T.getSQL(),$=this.dialect.sqlToQuery(S),M=this.session.prepareQuery($,void 0,void 0,!1);return new $A(()=>M.execute(),S,$,(f)=>M.mapResult(f,!0))}transaction(T,S){return this.session.transaction(T,S)}}class KK{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 M=new NJ($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),M}),this.unique,!0,this.name,T)}}class bW{static[y]="PgIndexBuilder";config;constructor(T,S,$,M,f="btree"){this.config={name:M,columns:T,unique:S,only:$,method:f}}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 wK(this.config,T)}}class wK{static[y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function MA(T){return new KK(!0,T)}class fA{constructor(T){this.query=T}getQuery(){return this.query}mapResult(T,S){return T}static[y]="PgPreparedQuery";joinsNotNullableMap}class JA{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 pJ{constructor(T,S,$,M=0){super(T,S,$);this.schema=$,this.nestedIndex=M}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 R.raw(S.join(" "))}setTransaction(T){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(T)}`)}}class YK extends fA{constructor(T,S,$,M,f,J,F){super({sql:S,params:$});this.client=T,this.queryString=S,this.params=$,this.logger=M,this.fields=f,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:M,queryString:f,client:J,joinsNotNullableMap:F,customResultMapper:W}=this;if(!M&&!W)return QT.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(f,$)});let A=await QT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":f,"drizzle.query.params":JSON.stringify($)}),J.unsafe(f,$).values()});return QT.startActiveSpan("drizzle.mapResponse",()=>{return W?W(A):A.map((k)=>n2(M,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,$,M={}){super(S);this.client=T,this.schema=$,this.options=M,this.logger=M.logger??new L1}static[y]="PostgresJsSession";logger;prepareQuery(T,S,$,M,f){return new YK(this.client,T.sql,T.params,this.logger,S,M,f)}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 M=new iJ($,this.dialect,this.schema,this.options),f=new WA(this.dialect,M,this.schema);if(S)await f.setTransaction(S);return T(f)})}}class WA extends FA{constructor(T,S,$,M=0){super(T,S,$,M);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),M=new WA(this.dialect,$,this.schema);return T(M)})}}class yK extends pJ{static[y]="PostgresJsDatabase"}function Qf(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 M=new BM({casing:S.casing}),f;if(S.logger===!0)f=new B1;else if(S.logger!==!1)f=S.logger;let J;if(S.schema){let A=n4(S.schema,o4);J={fullSchema:S.schema,schema:A.tables,tableNamesMap:A.tableNamesMap}}let F=new iJ(T,M,J,{logger:f}),W=new yK(M,F,J);return W.$client=T,W}function ZW(...T){if(typeof T[0]==="string"){let S=Ef(T[0]);return Qf(S,T[1])}if(g2(T[0])){let{connection:S,client:$,...M}=T[0];if($)return Qf($,M);if(typeof S==="object"&&S.url!==void 0){let{url:J,...F}=S,W=Ef(J,F);return Qf(W,M)}let f=Ef(S);return Qf(f,M)}return Qf(T[0],T[1])}((T)=>{function S($){return Qf({},$)}T.mock=S})(ZW||(ZW={}));function RK(T){let S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[_,U]of Object.entries(S))if(U==="")delete S[_]}if(!!T.skipValidation)return S;let f=typeof T.client==="object"?T.client:{},J=typeof T.server==="object"?T.server:{},F=typeof T.shared==="object"?T.shared:{},W=rf(f),A=rf(J),k=rf(F),X=T.isServer??(typeof window==="undefined"||("Deno"in window)),K=W.merge(k),w=A.merge(k).merge(W),z=X?w.safeParse(S):K.safeParse(S),O=T.onValidationError??((_)=>{throw console.error("\u274C Invalid environment variables:",_.flatten().fieldErrors),new Error("Invalid environment variables")}),Q=T.onInvalidAccess??((_)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(z.success===!1)return O(z.error);let D=(_)=>{if(!T.clientPrefix)return!0;return!_.startsWith(T.clientPrefix)&&!(_ in k.shape)},B=(_)=>{return X||!D(_)},L=(_)=>{return _==="__esModule"||_==="$$typeof"},b=(T.extends??[]).reduce((_,U)=>{return Object.assign(_,U)},{}),C=Object.assign(z.data,b);return new Proxy(C,{get(_,U){if(typeof U!=="string")return;if(L(U))return;if(!B(U))return Q(U);return Reflect.get(_,U)}})}var s7="__vite_start_time"in globalThis,Ty=typeof window!=="undefined",Om="vitest"in globalThis,I$=RK({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={};Dw(kA,{users:()=>LM,userChanges:()=>$y,untrackedUserColumnNames:()=>Sy,twoFactorMethod:()=>HK,trackedUserColumnName:()=>_K,trackableUserColumnNames:()=>zK,role:()=>GK,players:()=>AA,passwordResetAttempts:()=>fy,loginHistory:()=>My,games:()=>qW,banishedIps:()=>mW});function OK(T){return R`lower(${T})`}var GK=eF("role",["admin","user"]),LM=r$("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:ZJ().notNull().default(!1),verifiedAt:M$({withTimezone:!0}),userRole:GK().default("user")},(T)=>[MA("usernameUniqueIndex").on(OK(T.username)),MA("emailUniqueIndex").on(OK(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(()=>LM.id),changedAt:M$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:_K().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),qW=r$("games",{id:bS().primaryKey().defaultRandom()}),AA=r$("players",{userId:bS().notNull().references(()=>LM.id),gameId:bS().notNull().references(()=>qW.id),score:XW().notNull()},(T)=>[q4({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),My=r$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>LM.id),loginTime:M$({withTimezone:!0}).notNull().defaultNow(),ipAddress:MS({length:45}).notNull(),userAgent:MS({length:1024}),successful:ZJ().notNull().default(!1)}),HK=eF("twoFactorMethod",["email","phone"]),fy=r$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>LM.id),requestedIp:MS({length:45}).notNull(),requestedAt:M$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:M$({withTimezone:!0}),verificationMethod:HK().notNull()}),mW=r$("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 XA{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Jy.resolve(__dirname,"notify_update.sql"));let T=[PS(LM),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(","),M=$[0],f=$[1],J=`${M}("${f}")`;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=Ef(S),this.drizzle=ZW(this.sql,{schema:kA,logger:T})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new MT);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(.+)/,(M,f,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}-${f}T${W}`});return new Date($)}async function DK(T,S="/var/log/nginx/access.log",$=new Date){let M=new Map;if(!hW.existsSync(S))return T.error(`Log file not found: ${S}`),M;let f=hW.createReadStream(S),J=EK.createInterface({input:f,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,K=k.groups.dateTime,w=Fy(K);if(!Number.isNaN(w.getTime())){if(w>=F&&w<=$){let z=M.get(X);if(!z)z=[],M.set(X,z);z.push(W)}}else T.error(`Failed to parse date: ${K}`)}}),new Promise((W,A)=>{J.on("error",(k)=>{A(k)}),J.on("close",()=>{W(M)})})}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:M}){let f=T.usdBudget,J=new XA({logQuery(C,E){$.info("\uD83D\uDCDD query",C,E)}}),F=await DK($,S,M),W=[],A=T.from(UK),k=0,X=0;for(let[C,E]of F){$.info(`\uD83D\uDD0D ruling on ${C}. logs:`),$.info(E.map((U)=>`\t${U}`).join(`
73
+ `));let _=!1;for(let U of Yy)if(E.some((q)=>q.includes(U))){W.push({ip:C,reason:`Always ban ${U}`}),$.info(`\t\uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--always ban ${U}
74
+ `),_=!0;break}if(_)continue;if(T.usdBudget>T.usdFloor){let U=QK(E),q=await A(U);if(q.shouldBanIp)W.push({ip:C,reason:q.veryConciseReason}),$.info(`\t\uD83E\uDDD1\u200D\u2696\uFE0F banning ${C}--${q.veryConciseReason}
75
+ `);else X++,$.info(`\t\uD83D\uDD4A\uFE0F not banning ${C}
76
+ `);k++}else{$.warn("\uD83D\uDCB0 insufficient funds to process all logs"),$.warn(`\uD83D\uDCB0 got through ${k}/${F.size} ips
77
+ `);break}}let K=W.length;if(W.length>0)await J.drizzle.insert(mW).values(W).onConflictDoNothing();let w=[],z=zT.object({lastDay:zT.string()}),O=wy(import.meta.dirname,"tribunal.cache.json");if(ky(O)){let C=await Xy(O,"utf-8");try{let E=JSON.parse(C),{lastDay:_}=z.parse(E);if(_){let U=new Date(_);w.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:FW(mW.banishedAt,U)}))}}catch(E){$.error(E)}}try{await Promise.all(w.map((C)=>new Promise((E,_)=>Ay(`iptables -D INPUT -s ${C.ip} -j DROP`).on("exit",(U)=>{if(U===0)$.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${C.ip}`),E();else _(new Error(`iptables exited with code ${U}`))}))))}catch(C){if(C instanceof Error)$.error(C.message);else{let E=Of(C);$.error("iptables exited with error",E)}}await Ky(O,JSON.stringify({lastDay:M}),"utf-8"),$.info(`\u2728 banned ${K} ips, didn't ban ${X} ips`);let D=f-T.usdBudget,B=D.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),L=f.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),b=Math.round(D/f*100);$.info(`\uD83D\uDCB8 spent ${B}, ${b}% of ${L} budget`)}var b$=new K0;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)}