tempest.games 0.1.13 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/app/assets/{index-Cj0zGHKx.js → index-BAiC1k6g.js} +1 -1
- package/app/assets/index-k4NBGR4H.css +1 -0
- package/app/index.html +2 -2
- package/bin/backend.bun.js +13 -13
- package/bin/backend.worker.tribunal.bun.js +8 -8
- package/bin/frontend.bun.js +5 -5
- package/drizzle/0008_talented_blur.sql +4 -0
- package/drizzle/meta/0008_snapshot.json +489 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +4 -4
- package/app/assets/index-BFPcq13d.css +0 -1
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var GK=Object.create;var{getPrototypeOf:zK,defineProperty:hW,getOwnPropertyNames:_K}=Object;var HK=Object.prototype.hasOwnProperty;var Y7=(T,S,$)=>{$=T!=null?GK(zK(T)):{};let f=S||!T||!T.__esModule?hW($,"default",{value:T,enumerable:!0}):$;for(let M of _K(T))if(!HK.call(f,M))hW(f,M,{get:()=>T[M],enumerable:!0});return f};var R7=(T,S)=>()=>(S||T((S={exports:{}}).exports,S),S.exports);var DK=(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 _7(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})`,w=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(w,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})`,w=I(T),G=CM(w,{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)=>wT(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 EK={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=EK[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 u7=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(QK)){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 w=e(y),G=T.molecules.get(w);if(!G)throw new Error(`Molecule ${w} not found in store "${T.config.name}"`);M.push(G)}}else{J="any";let y=e(S),w=T.molecules.get(y);if(!w)throw new Error(`Molecule ${y} not found in store "${T.config.name}"`);M.push(w)}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(KT(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(KT(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 QK="T$";function If(T){return DA(XT.STORE,T)}function a$(T){return HA(XT.STORE,T)}function nW(...T){if(T.length===2)return wT(XT.STORE,...T);return wT(XT.STORE,...T)}var cW=(T)=>(S,$,f,M,...J)=>{console[T](`${S} ${$} "${f}" ${M}`,...J)},UK={error:cW("error"),info:cW("info"),warn:cW("warn")};class oW{T;S;$;constructor(T,S,$=UK){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 KT(T){return"phase"in T.transactionMeta}var QA=(T)=>{let S=I(T);if(!KT(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 VK=(T)=>T[0].toUpperCase()+T.slice(1);function iS(T){return T.type.split("_").map(VK).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 q$(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 Z$=(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}"${!KT(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 BK(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(!KT(M)||M.transactionMeta.phase!=="building"){$.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!BK(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=Z$(T,$),M=f;if(T.type==="mutable_atom"&&KT($)){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"&&KT($)){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=KT($)&&$.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 wT(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 Z$(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)=>wT(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())=>q$(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=w.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)},w=TT($,T),G=w.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))w.subject.next(Q);else if(KT(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||!KT($)||$.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(KT(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)=>wT(A,...k),set:(...k)=>{qT(A,...k)},run:(k,X=Cf())=>q$(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,...w)=>G$(A,k,X,y,...w),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(),KT(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(KT(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),LK=(T,S)=>I(S).selectors.has(T),NK=(T,S)=>I(S).readonlySelectors.has(T),lA=(T,S)=>SF(T,S)||LK(T,S)||NK(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 wT($,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 wT($,J);let F=TT(J,$),W=Z$(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 w=X();T.logger.info("\u2728",y.type,y.key,"=",w);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},w=(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:w,set:(B)=>{let L=I(T),b=w(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=w();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"),KT($)&&$.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})`,w=I(T),G=mM(w,{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)=>wT(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 w=lS(X,T,$);return S.toJson(W(w))}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 w=lS(y,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)jT($,f,lT(J.token.family.subKey))}),f}var lT=(T)=>JSON.parse(T),e=(T)=>JSON.stringify(T),lG=[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=Z$(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 w=f.on.operationClose.subscribe(`state subscription ${$}`,()=>{w(),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 m${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}:${KT($)?$.transactionMeta.update.key:"main"}:${T.key}`,M=wT($,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}:${KT($)?$.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=wT($,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 w=y({setSelf:(G)=>{qT(T,A,G)},onSet:(G)=>XS(A,G,`effect[${k}]`,T)});if(w)X.push(w);++k}F.cleanup=()=>{for(let y of X)y()}}if(new m$(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 m$(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 m$(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})`,w=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(w,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 m$(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"&&KT(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 w=y({setSelf:(G)=>{qT(T,A,G)},onSet:(G)=>XS(A,G,`effect[${k}]`,T)});if(w)X.push(w);++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"),KT($)&&$.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)=>wT($,...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},w={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(w,{getContent:(h)=>{return D(this.toolkit,h)},setContent:(h,O)=>{H(this.toolkit,h,O)},deleteContent:(h)=>{U(this.toolkit,h)}})}else G=w;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(KT(M)){let{toolkit:J}=M.transactionMeta;f.transact(J,({relations:F})=>{S(F)})}else S(f.relations)}function CK(T,S){return ZM(T,S).core.findRelatedKeysState}function eA(T){return CK(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 t_(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 d_=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)}),xK={enteredAtEpoch:0},vM=JF({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},xK),r_=iJ({key:"usersInMyRoomView",get:(T)=>({find:S})=>{let $=eA(vM);return[S($,T)]}});import{spawn as jK}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=a$({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=jK(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 UH=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)}}),VH=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}}),BH=bM({key:"leaveRoom",do:(T,S,$)=>{WF(vM,(f)=>{f.delete({room:S,user:$})},T.env().store)}}),LH=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 xH=a$({key:"redactor",default:{occlude:(T)=>T}}),Zf=a$({key:"unacknowledgedUpdates",default:()=>[]});var $k=a$({key:"sockets",default:null}),ZH=If({key:"socketsIndex",mutable:!0,default:()=>new uT,toJson:(T)=>T.toJSON(),fromJson:(T)=>uT.fromJSON(T)}),mH=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=wT(T,k);F.push(k,X)}for(let A of S.perspectives){let{viewAtoms:k,resourceAtoms:X}=A,y=OT(T,k,$),w=wT(T,y);T.logger.info("\uD83D\uDC41","atom",X.key,`${$} can see`,{viewAtoms:k,resourceAtoms:X,userView:w});for(let G of w){let z=G.type==="mutable_atom"?nT(T,G):G,Q=wT(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{q$({type:"transaction",key:F},W,T)(...J.params)}catch(w){if(w instanceof Error)T.logger.error("\u274C","continuity",f,`failed to run transaction ${F} from ${$} with update ${W}`,w.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((w)=>{if(w.type==="atom")return w.key;return z$(w).key}).concat(S.perspectives.flatMap((w)=>{let{viewAtoms:G}=w,z=OT(T,G,$);return wT(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,$,(w)=>{if(y)w.push(y),w.sort((G,z)=>G.epoch-z.epoch),T.logger.info("\uD83D\uDC4D","continuity",M,`${$} unacknowledged update queue now has`,w.length,"items");return w}),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 w=X.map((E)=>E.key),G=y.map((E)=>E.key),z=X.filter((E)=>!G.includes(E.key)),Q=y.filter((E)=>!w.includes(E.key)).flatMap((E)=>{let B=E.type==="mutable_atom"?nT(T,E):E,L=wT(T,B);return[B,L]});if(T.logger.info("\uD83D\uDC41","atom",F.resourceAtoms.key,`${$} has a new perspective`,{oldKeys:w,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=wT(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=wT(S,L);for(let C of X)M?.emit(`tx-new:${J}`,C)},`sync-continuity:${J}:${W}`,S),X=wT(S,Zf,W),y=[],w=Wk(S,f,W,M),G=Fk(S,f,W,M);y.push(...w,...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 w0;(function(T){T.mergeShapes=(S,$)=>{return{...S,...$}}})(w0||(w0={}));var n=GT.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),h$=(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"]),IK=(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 bK(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}},qK=[];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}),K0=(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 wk=(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 h$(T.data)}_getOrReturnCtx(T,S){return S||{common:T.parent.common,data:T.data,parsedType:h$(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:h$(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:h$(T)},M=this._parseSync({data:T,path:f.path,parent:f});return wk(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:h$(T)},f=this._parse({data:T,path:$.path,parent:$}),M=await(oM(f)?f:Promise.resolve(f));return wk($,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 Sf.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 KF({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 ZK=/^c[^\s-]{8,}$/i,mK=/^[0-9a-z]+$/,hK=/^[0-9A-HJKMNP-TV-Z]{26}$/,vK=/^[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,PK=/^[a-z0-9_-]{21}$/i,nK=/^[-+]?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)?)??$/,cK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y0,gK=/^(?:(?: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])$/,tK=/^(([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})))$/,pK=/^([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])))",iK=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 lK(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 uK(T,S){if((S==="v4"||!S)&&gK.test(T))return!0;if((S==="v6"||!S)&&tK.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(!cK.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(oK,"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(!vK.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(!PK.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(!ZK.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(!mK.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(!hK.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(!iK.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(!lK(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(!nK.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(!uK(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(!pK.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 dK(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 P$ 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(dK(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 P$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:l.toString(f)}]})}_addCheck(T){return new P$({...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"&>.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)}}P$.create=(T)=>{return new P$({checks:[],typeName:x.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...FT(T)})};class n$ 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 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]})}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}}n$.create=(T)=>{var S;return new n$({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 e$ 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 e$({...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}}e$.create=(T)=>{return new e$({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 s$ extends WT{constructor(){super(...arguments);this._any=!0}_parse(T){return OS(T.data)}}s$.create=(T)=>{return new s$({typeName:x.ZodAny,...FT(T)})};class v$ extends WT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return OS(T.data)}}v$.create=(T)=>{return new v$({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 c$)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 KF)return _$(T.unwrap());else if(T instanceof af)return _$(T.unwrap());else if(T instanceof rf)return _$(T._def.innerType);else return[]};class wF 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 wF({typeName:x.ZodDiscriminatedUnion,discriminator:T,options:S,optionsMap:f,...FT($)})}}function R0(T,S){let $=h$(T),f=h$(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(K0(M)||K0(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 Tf 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 Tf({...this._def,minSize:{value:T,message:l.toString(S)}})}max(T,S){return new Tf({...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)}}Tf.create=(T,S)=>{return new Tf({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 Sf){let F=this;return OS(async function(...W){let A=new LS([]),k=await F._def.args.parseAsync(W,M).catch((w)=>{throw A.addIssue($(W,w)),A}),X=await Reflect.apply(J,this,k);return await F._def.returns._def.type.parseAsync(X,M).catch((w)=>{throw A.addIssue(f(X,w)),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(v$.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(v$.create()),returns:S||v$.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 c$({values:T,typeName:x.ZodEnum,...FT(S)})}class c$ 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 c$.create(T,{...this._def,...S})}exclude(T,S=this._def){return c$.create(this.options.filter(($)=>!T.includes($)),{...this._def,...S})}}PM=new WeakMap;c$.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 Sf 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})}))}}Sf.create=(T,S)=>{return new Sf({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 rK=Symbol("zod_brand");class KF 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 s$.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 s$.create()}var aK={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 eK=(T,S={message:`Input not instance of ${T.name}`})=>Hk(($)=>$ instanceof T,S),Dk=uS.create,Ek=P$.create,sK=lM.create,T4=n$.create,Qk=nf.create,S4=e$.create,$4=gM.create,f4=cf.create,M4=of.create,J4=s$.create,F4=v$.create,W4=A$.create,A4=tM.create,k4=dS.create,dM=ZT.create,X4=ZT.strictCreate,y4=gf.create,w4=wF.create,K4=tf.create,Y4=k$.create,R4=pM.create,O4=iM.create,G4=Tf.create,z4=vf.create,_4=pf.create,H4=lf.create,D4=c$.create,E4=uf.create,Q4=Sf.create,Kk=hS.create,U4=rS.create,V4=H$.create,B4=hS.createWithPreprocess,L4=uM.create,N4=()=>Dk().optional(),C4=()=>Ek().optional(),x4=()=>Qk().optional(),j4={string:(T)=>uS.create({...T,coerce:!0}),number:(T)=>P$.create({...T,coerce:!0}),boolean:(T)=>nf.create({...T,coerce:!0}),bigint:(T)=>n$.create({...T,coerce:!0}),date:(T)=>e$.create({...T,coerce:!0})},I4=ST,HT=Object.freeze({__proto__:null,defaultErrorMap:Pf,setErrorMap:bK,getErrorMap:kF,makeIssue:XF,EMPTY_PATH:qK,addIssueToContext:v,ParseStatus:yS,INVALID:ST,DIRTY:hf,OK:OS,isAborted:K0,isDirty:Y0,isValid:cM,isAsync:oM,get util(){return GT},get objectUtil(){return w0},ZodParsedType:n,getParsedType:h$,ZodType:WT,datetimeRegex:zk,ZodString:uS,ZodNumber:P$,ZodBigInt:n$,ZodBoolean:nf,ZodDate:e$,ZodSymbol:gM,ZodUndefined:cf,ZodNull:of,ZodAny:s$,ZodUnknown:v$,ZodNever:A$,ZodVoid:tM,ZodArray:dS,ZodObject:ZT,ZodUnion:gf,ZodDiscriminatedUnion:wF,ZodIntersection:tf,ZodTuple:k$,ZodRecord:pM,ZodMap:iM,ZodSet:Tf,ZodFunction:vf,ZodLazy:pf,ZodLiteral:lf,ZodEnum:c$,ZodNativeEnum:uf,ZodPromise:Sf,ZodEffects:hS,ZodTransformer:hS,ZodOptional:rS,ZodNullable:H$,ZodDefault:df,ZodCatch:rf,ZodNaN:lM,BRAND:rK,ZodBranded:KF,ZodPipeline:uM,ZodReadonly:af,custom:Hk,Schema:WT,ZodSchema:WT,late:aK,get ZodFirstPartyTypeKind(){return x},coerce:j4,any:J4,array:k4,bigint:T4,boolean:Qk,date:S4,discriminatedUnion:w4,effect:Kk,enum:D4,function:z4,instanceof:eK,intersection:K4,lazy:_4,literal:H4,map:O4,nan:sK,nativeEnum:E4,never:W4,null:M4,nullable:V4,number:Ek,object:dM,oboolean:x4,onumber:C4,optional:U4,ostring:N4,pipeline:L4,preprocess:B4,promise:Q4,record:R4,set:G4,strictObject:X4,string:Dk,symbol:$4,transformer:Kk,tuple:Y4,undefined:f4,union:y4,unknown:F4,void:A4,NEVER:I4,ZodIssueCode:j,quotelessJson:IK,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 b4(T,S)}}var b4=(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 q4=(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(q4(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,$f={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"?Z4(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($,$f.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($,$f.cuid,M.message,S);break;case"cuid2":sS($,$f.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($,$f.emoji,M.message,S);break;case"ulid":{sS($,$f.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($,$f.base64,M.message,S);break}}break}case"nanoid":sS($,$f.nanoid,M.message,S);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(M)}return $}var Z4=(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 m4(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:m4(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=h4(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=P4(T,T.typeName,S);if(J)n4(T,S,J);return M.jsonSchema=J,J}var h4=(T,S)=>{switch(S.$refStrategy){case"root":return{$ref:T.path.join("/")};case"relative":return{$ref:v4(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}}},v4=(T,S)=>{let $=0;for(;$<T.length&&$<S.length;$++)if(T[$]!==S[$])break;return[(T.length-$).toString(),...S.slice($)].join("/")},P4=(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)}},n4=(T,S,$)=>{if(T.description){if($.description=T.description,S.markdownDescription)$.markdownDescription=T.description}return $};var ek=(T,S)=>{let $=yk(S),f=typeof S==="object"&&S.definitions?Object.entries(S.definitions).reduce((A,[k,X])=>({...A,[k]:s(X._def,{...$,currentPath:[...$.basePath,$.definitionPath,k]},!0)??{}}),{}):void 0,M=typeof S==="string"?S:S?.nameStrategy==="title"?void 0:S?.name,J=s(T._def,M===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,M]},!1)??{},F=typeof S==="object"&&S.name!==void 0&&S.nameStrategy==="title"?S.name:void 0;if(F!==void 0)J.title=F;let W=M===void 0?f?{...J,[$.definitionPath]:f}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,M].join("/"),[$.definitionPath]:{...f,[M]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09")W.$schema="https://json-schema.org/draft/2019-09/schema#";return W};var sk=ek;function TX(T,S){return function $({schema:f,fallback:M}){let J=sk(f);return async function F(W,A=3){let k,X=[];while(X.length<A){k=await T(W,J,M,X);let y=f.safeParse(k);if(y.success)return y.data;S?.warn(`safegen failed to generate well-formed data.
|
|
3
|
+
var z4=Object.create;var{getPrototypeOf:_4,defineProperty: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 a$(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 q$(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 Z$=(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=Z$(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 Z$(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())=>q$(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())=>q$(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=Z$(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=Z$(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 m${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 m$(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 m$(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 m$(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 m$(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=a$({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=a$({key:"redactor",default:{occlude:(T)=>T}}),Zf=a$({key:"unacknowledgedUpdates",default:()=>[]});var $k=a$({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{q$({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"]),h$=(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 h$(T.data)}_getOrReturnCtx(T,S){return S||{common:T.parent.common,data:T.data,parsedType:h$(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:h$(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:h$(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:h$(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 Sf.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 P$ 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 P$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:l.toString(f)}]})}_addCheck(T){return new P$({...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"&>.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)}}P$.create=(T)=>{return new P$({checks:[],typeName:x.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...FT(T)})};class n$ 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 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]})}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}}n$.create=(T)=>{var S;return new n$({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 e$ 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 e$({...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}}e$.create=(T)=>{return new e$({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 s$ extends WT{constructor(){super(...arguments);this._any=!0}_parse(T){return OS(T.data)}}s$.create=(T)=>{return new s$({typeName:x.ZodAny,...FT(T)})};class v$ extends WT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return OS(T.data)}}v$.create=(T)=>{return new v$({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 c$)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 $=h$(T),f=h$(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 Tf 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 Tf({...this._def,minSize:{value:T,message:l.toString(S)}})}max(T,S){return new Tf({...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)}}Tf.create=(T,S)=>{return new Tf({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 Sf){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(v$.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(v$.create()),returns:S||v$.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 c$({values:T,typeName:x.ZodEnum,...FT(S)})}class c$ 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 c$.create(T,{...this._def,...S})}exclude(T,S=this._def){return c$.create(this.options.filter(($)=>!T.includes($)),{...this._def,...S})}}PM=new WeakMap;c$.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 Sf 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})}))}}Sf.create=(T,S)=>{return new Sf({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 s$.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 s$.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=P$.create,Tw=lM.create,Sw=n$.create,Qk=nf.create,$w=e$.create,fw=gM.create,Mw=cf.create,Jw=of.create,Fw=s$.create,Ww=v$.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=Tf.create,_w=vf.create,Hw=pf.create,Dw=lf.create,Ew=c$.create,Qw=uf.create,Uw=Sf.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)=>P$.create({...T,coerce:!0}),boolean:(T)=>nf.create({...T,coerce:!0}),bigint:(T)=>n$.create({...T,coerce:!0}),date:(T)=>e$.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:h$,ZodType:WT,datetimeRegex:zk,ZodString:uS,ZodNumber:P$,ZodBigInt:n$,ZodBoolean:nf,ZodDate:e$,ZodSymbol:gM,ZodUndefined:cf,ZodNull:of,ZodAny:s$,ZodUnknown:v$,ZodNever:A$,ZodVoid:tM,ZodArray:dS,ZodObject:ZT,ZodUnion:gf,ZodDiscriminatedUnion:KF,ZodIntersection:tf,ZodTuple:k$,ZodRecord:pM,ZodMap:iM,ZodSet:Tf,ZodFunction:vf,ZodLazy:pf,ZodLiteral:lf,ZodEnum:c$,ZodNativeEnum:uf,ZodPromise:Sf,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,$f={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($,$f.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($,$f.cuid,M.message,S);break;case"cuid2":sS($,$f.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($,$f.emoji,M.message,S);break;case"ulid":{sS($,$f.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($,$f.base64,M.message,S);break}}break}case"nanoid":sS($,$f.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.
|
|
4
4
|
`,`Here's what was returned last time:
|
|
5
5
|
`,JSON.stringify(k,null," "),`
|
|
6
6
|
`,`Here's the error message from zod:
|
|
7
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
|
|
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 ff="4.71.1";var AX=!1,Mf=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(Mf)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${Mf}'\``);AX=S.auto,Mf=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
9
|
- \`import 'openai/shims/node'\` (if you're running on Node)
|
|
10
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 s4}from"fs";function yX(){let T=XX();function S($){return $ instanceof s4}return{...T,isFsReadStream:S}}if(!Mf)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 Jf({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 Jf 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 Ff extends Jf{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 o${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 $=o$.NEWLINE_CHARS.has(S[S.length-1]||""),f=S.split(o$.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}}o$.NEWLINE_CHARS=new Set(["\n","\r"]);o$.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 S6(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 o$,F=KX(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*S6(T,S){if(!T.body)throw S.abort(),new $T("Attempted to iterate over a response with no body");let $=new wX,f=new o$,M=KX(T.body);for await(let J of $6(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*$6(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=f6(S))!==-1)yield S.slice(0,J),S=S.slice(J)}if(S.length>0)yield S}function f6(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 wX{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]=M6(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 M6(T,S){let $=T.indexOf(S);if($!==-1)return[T.substring(0,$),S,T.substring($+S.length)];return[T,"",""]}function KX(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",J6=(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 F6(T);if(S||(S=A6(T)??"unknown_file"),!$?.type){let M=f[0]?.type;if(typeof M==="string")$={...$,type:M}}return new _F(f,S,$)}async function F6(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(k6(T))for await(let $ of T)S.push($);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${W6(T)}`);return S}function W6(T){return`[${Object.getOwnPropertyNames(T).map(($)=>`"${$}"`).join(", ")}]`}function A6(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},k6=(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(J6($)){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 y6=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(),...G6(),...this.authHeaders(T)}}validateHeaders(T,S){}defaultIdempotencyKey(){return`stainless-node-retry-${D6()}`}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 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:f}){let M={};if($)M["content-length"]=$;let J=this.defaultHeaders(T);if(HX(M,J),HX(M,S),I0(T.body)&&Mf!=="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 Ff;throw new Jf({cause:A})}let k=K6(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=z6(X),w=y?void 0:X;throw ef(`response (error; ${S?"(error; no more retries left)":"(error; not retryable)"})`,A.status,J,k,w),this.makeStatusError(A.status,y,w,k)}return{response:A,options:$,controller:W}}requestAPIList(T,S){let $=this.makeRequest(S,null);return new UX(this,$,T)}buildURL(T,S){let $=H6(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 ${ff}`}}class IF{constructor(T,S,$,f){xF.set(this,void 0),y6(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 K6=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get(S,$){let f=$.toString();return S[f.toLowerCase()]||S[f]}})},Y6={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(Y6,S))},R6=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"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":ff,"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":ff,"X-Stainless-OS":zX(process.platform),"X-Stainless-Arch":GX(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let T=O6();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"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":ff,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function O6(){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,G6=()=>{return _X??(_X=R6())},z6=(T)=>{try{return JSON.parse(T)}catch(S){return}},_6=new RegExp("^(?:[a-z]+:)?//","i"),H6=(T)=>{return _6.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 D6=()=>{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"},E6=(T)=>{return typeof T?.get==="function"};var DX=(T,S)=>{let $=S.toLowerCase();if(E6(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 Af extends i{constructor(){super(...arguments);this.completions=new $J(this._client)}}Af.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 kf 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{}kf.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 g$=(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 Xf(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 wJ(T,S)}function wJ(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)=>C6(S,M))??[],parsed:f.message.content&&!f.message.refusal?N6(S,f.message.content):null}}});return{...T,choices:$}}function N6(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 C6(T,S){let $=T.tools?.find((f)=>f.function?.name===S.function.name);return{...S,function:{...S.function,parsed_arguments:Xf($)?$.$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 Xf($)||$?.function.strict||!1}function c0(T){if(n0(T.response_format))return!0;return T.tools?.some((S)=>Xf(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)},wS,o0,vF,g0,t0,p0,bX,i0,IX=10;class KJ extends yJ{constructor(){super(...arguments);wS.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(g$(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(g$(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,wS,"m",o0).call(this)}async finalMessage(){return await this.done(),DS(this,wS,"m",vF).call(this)}async finalFunctionCall(){return await this.done(),DS(this,wS,"m",g0).call(this)}async finalFunctionCallResult(){return await this.done(),DS(this,wS,"m",t0).call(this)}async totalUsage(){return await this.done(),DS(this,wS,"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,wS,"m",vF).call(this);if(S)this._emit("finalMessage",S);let $=DS(this,wS,"m",o0).call(this);if($)this._emit("finalContent",$);let f=DS(this,wS,"m",g0).call(this);if(f)this._emit("finalFunctionCall",f);let M=DS(this,wS,"m",t0).call(this);if(M!=null)this._emit("finalFunctionCallResult",M);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",DS(this,wS,"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,wS,"m",bX).call(this,S);let M=await T.chat.completions.create({...S,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(wJ(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,wS,"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((w)=>{if(Xf(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 y="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 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,wS,"m",i0).call(this,D);if(this._addMessage({role:"tool",tool_call_id:E,content:H}),W)return}}return}}wS=new WeakSet,o0=function T(){return DS(this,wS,"m",vF).call(this).content??null},vF=function T(){let S=this.messages.length;while(S-- >0){let $=this.messages[S];if(g$($)){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(g$($)&&$?.function_call)return $.function_call;if(g$($)&&$?.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 KJ{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),g$(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 x6(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 j6(T.trim(),S)}var j6=(T,S)=>{let $=T.length,f=0,M=(w)=>{throw new qX(`${w} at position ${f}`)},J=(w)=>{throw new ZX(`${w} 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 w=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(w,++f-Number(G)))}catch(z){J(String(z))}else if(sT.STR&S)try{return JSON.parse(T.substring(w,f-Number(G))+'"')}catch(z){return JSON.parse(T.substring(w,T.lastIndexOf("\\"))+'"')}M("Unterminated string literal")},A=()=>{f++,y();let w={};try{while(T[f]!=="}"){if(y(),f>=$&&sT.OBJ&S)return w;let G=W();y(),f++;try{let z=F();Object.defineProperty(w,G,{value:z,writable:!0,enumerable:!0,configurable:!0})}catch(z){if(sT.OBJ&S)return w;else throw z}if(y(),T[f]===",")f++}}catch(G){if(sT.OBJ&S)return w;else M("Expected '}' at end of object")}return f++,w},k=()=>{f++;let w=[];try{while(T[f]!=="]")if(w.push(F()),y(),T[f]===",")f++}catch(G){if(sT.ARR&S)return w;M("Expected ']' at end of array")}return f++,w},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 w=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(w,f))}catch(G){if(T.substring(w,f)==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T.substring(w,T.lastIndexOf("e")))}catch(z){J(String(z))}}},y=()=>{while(f<$&&" \n\r\t".includes(T[f]))f++};return F()},l0=(T)=>x6(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,t$,u0,PF,d0,r0,a0,nF,e0,mX;class yf extends KJ{constructor(T){super();rT.add(this),U$.set(this,void 0),MM.set(this,void 0),t$.set(this,void 0),fM(this,U$,T,"f"),fM(this,MM,[],"f")}get currentChatCompletionSnapshot(){return DT(this,t$,"f")}static fromReadableStream(T){let S=new yf(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){let f=new yf(S);return f._run(()=>f._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}async _createChatCompletion(T,S,$){super._createChatCompletion;let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}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,t$=new WeakMap,rT=new WeakSet,u0=function T(){if(this.ended)return;fM(this,t$,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:Xf(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,t$,"f");if(!S)throw new $T("request ended without sending any chunks");return fM(this,t$,void 0,"f"),fM(this,MM,[],"f"),I6(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,t$,"f"),{choices:W,...A}=S;if(!F)F=fM(this,t$,{...A,choices:[]},"f");else Object.assign(F,A);for(let{delta:k,finish_reason:X,index:y,logprobs:w=null,...G}of S.choices){let z=F.choices[y];if(!z)z=F.choices[y]={finish_reason:X,index:y,message:{},logprobs:w,...G};if(w)if(!z.logprobs)z.logprobs=Object.assign({},w);else{let{content:D,refusal:H,...U}=w;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 I6(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:w,...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:w}}if(E)return{...G,index:y,finish_reason:X,logprobs:w,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:w}}),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 yf{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(($)=>wJ($,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 yf.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,w$,gF,S$,Yf,JM,Kf,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,[]),w$.set(this,{}),gF.set(this,{}),S$.set(this,void 0),Yf.set(this,void 0),JM.set(this,void 0),Kf.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,w$=new WeakMap,gF=new WeakMap,S$=new WeakMap,Yf=new WeakMap,JM=new WeakMap,Kf=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,w$,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,gF,"f"))}async finalRun(){if(await this.done(),!u(this,Yf,"f"))throw Error("Final run was not received.");return u(this,Yf,"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,Yf,"f"))throw Error("Final run has not been received");return u(this,Yf,"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,Kf,"f"))switch(u(this,Kf,"f").type){case"text":this._emit("textDone",u(this,Kf,"f").text,u(this,S$,"f"));break;case"image_file":this._emit("imageFileDone",u(this,Kf,"f").image_file,u(this,S$,"f"));break}CS(this,JM,M.index,"f")}CS(this,Kf,$.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,w$,"f")[S.data.id]=S.data,S.data;case"thread.run.step.delta":let $=u(this,w$,"f")[S.data.id];if(!$)throw Error("Received a RunStepDelta before creation of a snapshot");let f=S.data;if(f.delta){let M=jS.accumulateDelta($,f.delta);u(this,w$,"f")[S.data.id]=M}return u(this,w$,"f")[S.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,w$,"f")[S.data.id]=S.data;break}if(u(this,w$,"f")[S.data.id])return u(this,w$,"f")[S.data.id];throw new Error("No snapshot available")},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,Yf,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 p$ 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{}p$.RunsPage=HJ;p$.Steps=WM;p$.RunStepsPage=_J;class V$ extends i{constructor(){super(...arguments);this.runs=new p$(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=p$;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`,Rf,{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 Rf extends PT{}AM.VectorStoreFilesPage=Rf;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`,Rf,{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 w of y){let G=await F.files.create({file:w,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=Rf;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 Of 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 Ff({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class yM extends PT{}Of.FileObjectsPage=yM;class wM 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{}wM.FineTuningJobCheckpointsPage=QJ;class L$ extends i{constructor(){super(...arguments);this.checkpoints=new wM(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=wM;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 KM 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 Gf 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{}Gf.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 zf 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,...$})}}zf.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 Af(this),this.embeddings=new XM(this),this.files=new Of(this),this.images=new KM(this),this.audio=new E$(this),this.moderations=new RM(this),this.models=new Gf(this),this.fineTuning=new N$(this),this.beta=new $$(this),this.batches=new kf(this),this.uploads=new zf(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=Jf;RT.APIConnectionTimeoutError=Ff;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=Af;RT.Embeddings=XM;RT.Files=Of;RT.FileObjectsPage=yM;RT.Images=KM;RT.Audio=E$;RT.Moderations=RM;RT.Models=Gf;RT.ModelsPage=YM;RT.FineTuning=N$;RT.Beta=$$;RT.Batches=kf;RT.BatchesPage=sf;RT.Uploads=zf;var uX=RT;import{createHash as i6}from"crypto";import*as aT from"fs";import*as C$ from"path";function l6(T){let S=T.replace(u6,"-");if(S.length<=64)return S;let $=i6("sha256").update(T).digest("hex");return S.slice(-64)+"+"+$}var u6=/[^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=l6($),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 r6(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 a6(T="NO_API_KEY_PROVIDED"){let S=d6("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,w=A.completion_tokens,G=k*S1[f.model].promptPricePerToken+y*S1[f.model].promptPricePerTokenCached+w*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=a6(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=r6(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 W7}from"child_process";import{existsSync as A7}from"fs";import{readFile as k7,writeFile as X7}from"fs/promises";import{resolve as y7}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)}),e6=new lF({...M1.supported,...F1.supported}),OM=(T)=>{if(T===void 0)return"undefined";let S=e6.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,w=J-y;F.push([k,w])}}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,w=J-y;F.push([k,w])}}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 s6(T,S){return{summary:`${T<S?"+":"-"}${Math.abs(T-S)} (${T} \u2192 ${S})`}}function TY(T,S){return{summary:`${T.length<S.length?"+":"-"}${Math.abs(T.length-S.length)} ("${T}" \u2192 "${S}")`}}function SY(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 $Y(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 CN=new sX(M1,F1,{number:s6,string:TY,boolean:SY,null:()=>({summary:"No Change"}),object:eX,array:$Y});var Y=Symbol.for("drizzle:entityKind"),hN=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 w1=Symbol.for("drizzle:isPgEnum");function W2(T){return!!T&&typeof T==="function"&&w1 in T&&T[w1]===!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 fY(T,S,void 0)}function fY(T,S,$){let f=Object.assign((M)=>new A2(M??"",f),{enumName:T,enumValues:S,schema:$,[w1]:!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 K1,Y1,QT={startActiveSpan(T,S){if(!K1)return S();if(!Y1)Y1=K1.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()}}),K1,Y1)}};var hT=Symbol.for("drizzle:ViewBaseConfig");var rF=Symbol.for("drizzle:Schema"),y2=Symbol.for("drizzle:Columns"),w2=Symbol.for("drizzle:ExtraConfigColumns"),R1=Symbol.for("drizzle:OriginalName"),O1=Symbol.for("drizzle:BaseName"),K2=Symbol.for("drizzle:IsAlias"),Y2=Symbol.for("drizzle:ExtraConfigBuilder"),MY=Symbol.for("drizzle:IsDrizzleTable");class c{static[Y]="Table";static Symbol={Name:f$,Schema:rF,OriginalName:R1,Columns:y2,ExtraConfigColumns:w2,BaseName:O1,IsAlias:K2,ExtraConfigBuilder:Y2};[f$];[R1];[rF];[y2];[w2];[O1];[K2]=!1;[MY]=!0;[Y2]=void 0;constructor(T,S,$){this[f$]=this[R1]=T,this[rF]=S,this[O1]=$}}function PS(T){return T[f$]}function _f(T){return`${T[rF]??"public"}.${T[f$]}`}function G1(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function JY(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 JY(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,w]of k.entries())if(X.push(w),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,i$))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,i$))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},VC={...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,w]of A.entries()){if(y>0&&k!==void 0)X.push(k);X.push(w)}return new t(X)}T.join=M;function J(A){return new aF(A)}T.identifier=J;function F(A){return new i$(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 i${constructor(T){this.name=T}static[Y]="Placeholder";getSQL(){return new t([this])}}function z1(T,S){return T.map(($)=>{if(V($,i$)){if(!($.name in S))throw new Error(`No value for placeholder "${$.name}" was provided`);return S[$.name]}if(V($,IS)&&V($.value,i$)){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 K$(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 K$($,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,i$)&&!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,w]of F.entries())if(y<F.length-1){if(!(w in X))X[w]={};X=X[w]}else{let G=S[A],z=X[w]=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 l$ 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 l${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 l${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 wy(T,S){let{name:$,config:f}=yT(T,S);if(f?.mode==="date")return new Xy($);return new yy($)}class Ky 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 Ky(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 l${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 FY(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=FY(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 l${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 w8(T,S={}){let{name:$,config:f}=yT(T,S);return new X8($,f)}class K8 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 K8($,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 wW(T,this.config)}}class wW 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:wy,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:w8,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 WY(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 w=y;w.setName(X);let G=w.build(J);return J[B1].push(...w.buildForeignKeys(G,J)),[X,G]})),A=Object.fromEntries(Object.entries(F).map(([X,y])=>{let w=y;w.setName(X);let G=w.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 u$=(T,S,$)=>{return WY(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 d$ extends L1{constructor(T,S,$,f){super(T,S,$?.relationName);this.config=$,this.isNullable=f}static[Y]="One";withFieldName(T){let S=new d$(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=_f(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=_f(F.table),A=$[W],k=F.config(S(F.table)),X;for(let[y,w]of Object.entries(k))if(A){let G=M[A];if(G.relations[y]=w,X)G.primaryKey.push(...X)}else{if(!(W in f))f[W]={relations:{},primaryKey:X};f[W].relations[y]=w}}return{tables:M,tableNamesMap:$}}function AY(T){return function S($,f){return new d$(T,$,f,f?.fields.reduce((M,J)=>M&&J.notNull,!0)??!1)}}function kY(T){return function S($,f){return new qJ(T,$,f)}}function n8(T,S,$){if(V($,d$)&&$.config)return{fields:$.config.fields,references:$.config.references};let f=S[_f($.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[_f(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],d$)&&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:AY(T),many:kY(T)}}function KW(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,d$)?X&&KW(T,T[W.relationTableTsKey],X,W.selection,M):X.map((y)=>KW(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 M7 from"path";import bY from"os";import qY 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&&XY(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 XY(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 yY={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(yY);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:KY,parsers:YY}=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({},KY,S.serializers),parsers:Object.assign({},YY,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},RY=/\\/g,OY=/"/g;function GY(T){return T.replace(RY,"\\\\").replace(OY,'\\"')}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":'"'+GY($?$(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,Tw(j1,S,$,f)};function Tw(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(Tw(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 Hf=(T)=>{let S=T[0];for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Df=(T)=>{let S=T[0].toUpperCase();for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Ef=(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)}),{}):$}}Hf.column={from:Hf};Hf.value={from:m1(Hf)};ZJ.column={to:ZJ};var h1={...Hf};h1.column.to=ZJ;Df.column={from:Df};Df.value={from:m1(Df)};mJ.column={to:mJ};var v1={...Df};v1.column.to=mJ;Ef.column={from:Ef};Ef.value={from:m1(Ef)};hJ.column={to:hJ};var P1={...Ef};P1.column.to=hJ;import Sw from"net";import DY from"tls";import PJ from"crypto";import n1 from"stream";import{performance as $w}from"perf_hooks";class Qf 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=zY;function zY(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 KS=Buffer.allocUnsafe(256),_Y="BCcDdEFfHPpQSX".split("").reduce((T,S)=>{let $=S.charCodeAt(0);return T[S]=()=>{return KS[0]=$,ET.i=5,ET},T},{}),ET=Object.assign(HY,_Y,{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+=KS.write(T,ET.i,S,"utf8"),ET},i16(T){return DW(2),KS.writeUInt16BE(T,ET.i),ET.i+=2,ET},i32(T,S){if(S||S===0)return KS.writeUInt32BE(T,S),ET;return DW(4),KS.writeUInt32BE(T,ET.i),ET.i+=4,ET},z(T){return DW(T),KS.fill(0,ET.i,ET.i+T),ET.i+=T,ET},raw(T){return KS=Buffer.concat([KS.subarray(0,ET.i),T]),ET.i=KS.length,ET},end(T=1){KS.writeUInt32BE(ET.i-T,T);let S=KS.subarray(0,ET.i);return ET.i=0,KS=Buffer.allocUnsafe(256),S}}),d=ET;function DW(T){if(KS.length-ET.i<T){let S=KS,$=S.length;KS=Buffer.allocUnsafe($+($>>1)+T),S.copy(KS)}}function HY(){return ET.i=0,ET}var g1=Jw,EY=1,r$=d().S().end(),fw=d().H().end(),QY=d().i32(8).i32(80877103).end(8),UY=Buffer.concat([d().E().str(d.N).i32(0).end(),r$]),VY=d().D().str("S").str(d.N).end(),HM=()=>{},BY=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),LY={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 Jw(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:w,onnotice:G,onnotify:z,onparameter:Q,max_pipeline:E,keep_alive:B,backoff:L,target_session_attrs:b}=T,C=qS(),D=EY++,H={pid:null,secret:null},U=o1(ZW,T.idle_timeout),Z=o1(ZW,T.max_lifetime),h=o1(xw,T.connect_timeout),O=null,o,P=new Qf,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,I$=null,iT=null,xT=null,tS=null,J$=null,m=null,UM=null,WS={queue:S.closed,idleTimer:U,connect(K){FS=K||!0,KA()},terminate:BM,execute:VM,cancel:Bw,end:ZW,count:0,id:D};return S.closed&&S.closed.push(WS),WS;async function Vw(){let K;try{K=T.socket?await Promise.resolve(T.socket(T)):new Sw.Socket}catch(_){Nf(_);return}return K.on("error",Nf),K.on("close",YA),K.on("drain",yA),K}async function Bw({pid:K,secret:_},r,zT){try{o=d().i32(16).i32(80877102).i32(K).i32(_).end(16),await wA(),O.once("error",zT),O.once("close",r)}catch(vT){zT(vT)}}function VM(K){if(JS)return pJ(K,tT.connection("CONNECTION_DESTROYED",T));if(K.cancelled)return;try{return K.state=H,m?C.push(K):(m=K,m.active=!0),Cw(K),TS(Lw(K))&&!K.describeFirst&&!K.cursorFn&&C.length<E&&(!K.options.onexecute||K.options.onexecute(WS))}catch(_){return C.length===0&&TS(r$),F$(_),!0}}function Lw(K){if(K.parameters.length>=65534)throw tT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return K.options.simple?d().Q().str(K.statement.string+d.N).end():K.describeFirst?Buffer.concat([AA(K),fw]):K.prepare?K.prepared?tJ(K):Buffer.concat([AA(K),tJ(K)]):Nw(K)}function AA(K){return Buffer.concat([OA(K.statement.string,K.parameters,K.statement.types,K.statement.name),YK("S",K.statement.name)])}function tJ(K){return Buffer.concat([KK(K.parameters,K.statement.types,K.statement.name,K.cursorName),K.cursorFn?GA("",K.cursorRows):UY])}function Nw(K){return Buffer.concat([OA(K.statement.string,K.parameters,K.statement.types),VY,tJ(K)])}function Cw(K){let _=[],r=[],zT=b1(K,K.strings[0],K.args[0],_,r,T);!K.tagged&&K.args.forEach((vT)=>_W(vT,_,r,T)),K.prepare=T.prepare&&("prepare"in K.options?K.options.prepare:!0),K.string=zT,K.signature=K.prepare&&r+zT,K.onlyDescribe&&delete UT[K.signature],K.parameters=K.parameters||_,K.prepared=K.prepare&&K.signature in UT,K.describeFirst=K.onlyDescribe||_.length&&!K.prepared,K.statement=K.prepared?UT[K.signature]:{string:zT,types:r,name:K.prepare?VS+N++:""},typeof T.debug==="function"&&T.debug(D,zT,_,r)}function TS(K,_){if(xT=xT?Buffer.concat([xT,K]):Buffer.from(K),_||xT.length>=1024)return kA(_);return CT===null&&(CT=setImmediate(kA)),!0}function kA(K){let _=O.write(xT,K);return CT!==null&&clearImmediate(CT),xT=CT=null,_}function xw(){F$(tT.connection("CONNECT_TIMEOUT",T,O)),O.destroy()}async function XA(){if(TS(QY),!await new Promise((_)=>O.once("data",(r)=>_(r[0]===83)))&&J==="prefer")return Lf();O.removeAllListeners(),O=DY.connect({socket:O,servername:Sw.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(K){if(BT){if(BT.push(K),kT-=K.length,kT>=0)return}a=BT?Buffer.concat(BT,AT-kT):a.length===0?K:Buffer.concat([a,K],a.length+K.length);while(a.length>4){if(AT=a.readUInt32BE(1),AT>=a.length){kT=AT-a.length,BT=[a];break}try{jw(a.subarray(0,AT+1))}catch(_){m&&(m.cursorFn||m.describeFirst)&&TS(r$),F$(_)}a=a.subarray(AT+1),kT=0,BT=null}}async function wA(){if(JS=!1,fT={},O||(O=await Vw()),!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 KA(){setTimeout(wA,p?p+VT-$w.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 K=OK();TS(K)}catch(K){Nf(K)}}function Nf(K){if(WS.queue===S.connecting&&T.host[pT+1])return;F$(K);while(C.length)pJ(C.shift(),K)}function F$(K){iT&&(iT.destroy(K),iT=null),m&&pJ(m,K),FS&&(pJ(FS,K),FS=null)}function pJ(K,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+K.origin.replace(/.*\n/,"\n"),enumerable:T.debug},query:{value:K.string,enumerable:T.debug},parameters:{value:K.parameters,enumerable:T.debug},args:{value:K.args,enumerable:T.debug},types:{value:K.statement&&K.statement.types,enumerable:T.debug}}),K.reject(_)}function ZW(){return I$||(!WS.reserved&&f(WS),!WS.reserved&&!FS&&!m&&C.length===0?(BM(),new Promise((K)=>O&&O.readyState!=="closed"?O.once("close",K):K())):I$=new Promise((K)=>tS=K))}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(),I$=tS=null)}async function YA(K){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 KA();!K&&(m||C.length)&&Nf(tT.connection("CONNECTION_CLOSED",T,O)),p=$w.now(),K&&T.shared.retries++,VT=(typeof L==="function"?L(T.shared.retries):L)*1000,M(WS,tT.connection("CONNECTION_CLOSED",T,O))}function jw(K,_=K[0]){(_===68?Iw:_===100?JK:_===65?sw:_===83?bw:_===90?qw:_===67?Zw:_===50?RA:_===49?mw:_===116?hw:_===84?vw:_===82?Pw:_===110?pw:_===75?iw:_===69?aw:_===115?TK:_===51?SK:_===71?$K:_===78?WK:_===72?fK:_===99?FK:_===73?AK:_===86?kK:_===118?XK:_===87?MK:yK)(K)}function Iw(K){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=K.readInt32BE(_),_+=4,vT=r===-1?null:m.isRaw===!0?K.subarray(_,_+=r):zT.parser===void 0?K.toString("utf8",_,_+=r):zT.parser.array===!0?zT.parser(K.toString("utf8",_+1,_+=r)):zT.parser(K.toString("utf8",_,_+=r)),m.isRaw?AS[YS]=m.isRaw===!0?vT:w.value.from?w.value.from(vT,zT):vT:AS[zT.name]=w.value.from?w.value.from(vT,zT):vT;m.forEachFn?m.forEachFn(w.row.from?w.row.from(AS):AS,P):P[oT++]=w.row.from?w.row.from(AS):AS}function bw(K){let[_,r]=K.toString("utf8",5,K.length-1).split(d.N);if(fT[_]=r,T.parameters[_]!==r)T.parameters[_]=r,Q&&Q(_,r)}function qw(K){if(m&&m.options.simple&&m.resolve(gS||P),m=gS=null,P=new Qf,h.cancel(),FS){if(b){if(!fT.in_hot_standby||!fT.default_transaction_read_only)return rw();else if(dw(b,fT))return BM()}if(MT)return FS===!0&&(FS=null),lw();FS!==!0&&VM(FS),T.shared.retries=pT=0,FS=null;return}while(C.length&&(m=C.shift())&&(m.active=!0,m.cancelled))Jw(T).cancel(m.state,m.cancelled.resolve,m.cancelled.reject);if(m)return;WS.reserved?!WS.reserved.release&&K[5]===73?I$?BM():(WS.reserved=null,$(WS)):WS.reserved():I$?BM():$(WS)}function Zw(K){oT=0;for(let _=K.length-1;_>0;_--){if(K[_]===32&&K[_+1]<58&&P.count===null)P.count=+K.toString("utf8",_+1,K.length-1);if(K[_-1]>=65){P.command=K.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(r$);m.resolve(P)}function mw(){m.parsing=!1}function RA(){!P.statement&&(P.statement=m.statement),P.columns=m.statement.columns}function hw(K){let _=K.readUInt16BE(5);for(let r=0;r<_;++r)!m.statement.types[r]&&(m.statement.types[r]=K.readUInt32BE(7+r*4));m.prepare&&(UT[m.signature]=m.statement),m.describeFirst&&!m.onlyDescribe&&(TS(tJ(m)),m.describeFirst=!1)}function vw(K){if(P.command)gS=gS||[P],gS.push(P=new Qf),P.count=null,m.statement.columns=null;let _=K.readUInt16BE(5),r=7,zT;m.statement.columns=Array(_);for(let vT=0;vT<_;++vT){zT=r;while(K[r++]!==0);let AS=K.readUInt32BE(r),YS=K.readUInt16BE(r+4),b$=K.readUInt32BE(r+6);m.statement.columns[vT]={name:w.column.from?w.column.from(K.toString("utf8",zT,r-1)):K.toString("utf8",zT,r-1),parser:y[b$],table:AS,number:YS,type:b$},r+=18}if(P.statement=m.statement,m.onlyDescribe)return m.resolve(m.statement),TS(r$)}async function Pw(K,_=K.readUInt32BE(5)){(_===3?nw:_===5?cw:_===10?ow:_===11?gw:_===12?tw:_!==0?wK:HM)(K,_)}async function nw(){let K=await mW();TS(d().p().str(K).z(1).end())}async function cw(K){let _="md5"+await Mw(Buffer.concat([Buffer.from(await Mw(await mW()+W)),K.subarray(9)]));TS(d().p().str(_).z(1).end())}async function ow(){J$=(await PJ.randomBytes(18)).toString("base64"),d().p().str("SCRAM-SHA-256"+d.N);let K=d.i;TS(d.inc(4).str("n,,n=*,r="+J$).i32(d.i-K-4,K).end())}async function gw(K){let _=K.toString("utf8",9).split(",").reduce((YS,b$)=>(YS[b$[0]]=b$.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="+CY(zT,Buffer.from(await EW(await NY(zT),vT))).toString("base64");TS(d().p().str(AS).end())}function tw(K){if(K.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 pw(){if(P.statement=m.statement,P.statement.columns=[],m.onlyDescribe)return m.resolve(m.statement),TS(r$)}function iw(K){H.pid=K.readUInt32BE(5),H.secret=K.readUInt32BE(9)}async function lw(){MT=!1,(await new oS([`
|
|
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(!Mf)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 Jf({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 Jf 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 Ff extends Jf{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 o${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 $=o$.NEWLINE_CHARS.has(S[S.length-1]||""),f=S.split(o$.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}}o$.NEWLINE_CHARS=new Set(["\n","\r"]);o$.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 o$,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 o$,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)&&Mf!=="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 Ff;throw new Jf({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 ${ff}`}}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":ff,"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":ff,"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":ff,"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":ff,"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":ff,"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 Af extends i{constructor(){super(...arguments);this.completions=new $J(this._client)}}Af.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 kf 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{}kf.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 g$=(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 Xf(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:Xf($)?$.$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 Xf($)||$?.function.strict||!1}function c0(T){if(n0(T.response_format))return!0;return T.tools?.some((S)=>Xf(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(g$(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(g$(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(Xf(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(g$($)){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(g$($)&&$?.function_call)return $.function_call;if(g$($)&&$?.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),g$(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,t$,u0,PF,d0,r0,a0,nF,e0,mX;class yf extends wJ{constructor(T){super();rT.add(this),U$.set(this,void 0),MM.set(this,void 0),t$.set(this,void 0),fM(this,U$,T,"f"),fM(this,MM,[],"f")}get currentChatCompletionSnapshot(){return DT(this,t$,"f")}static fromReadableStream(T){let S=new yf(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){let f=new yf(S);return f._run(()=>f._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}async _createChatCompletion(T,S,$){super._createChatCompletion;let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}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,t$=new WeakMap,rT=new WeakSet,u0=function T(){if(this.ended)return;fM(this,t$,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:Xf(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,t$,"f");if(!S)throw new $T("request ended without sending any chunks");return fM(this,t$,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,t$,"f"),{choices:W,...A}=S;if(!F)F=fM(this,t$,{...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 Kf extends yf{static fromReadableStream(T){let S=new Kf(null);return S._run(()=>S._fromReadableStream(T)),S}static runFunctions(T,S,$){let f=new Kf(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 Kf(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 Kf.runFunctions(this._client,T,S);return $M.runFunctions(this._client,T,S)}runTools(T,S){if(T.stream)return Kf.runTools(this._client,T,S);return $M.runTools(this._client,T,S)}stream(T,S){return yf.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$,Yf,JM,wf,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),Yf.set(this,void 0),JM.set(this,void 0),wf.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,Yf=new WeakMap,JM=new WeakMap,wf=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,Yf,"f"))throw Error("Final run was not received.");return u(this,Yf,"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,Yf,"f"))throw Error("Final run has not been received");return u(this,Yf,"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,wf,"f"))switch(u(this,wf,"f").type){case"text":this._emit("textDone",u(this,wf,"f").text,u(this,S$,"f"));break;case"image_file":this._emit("imageFileDone",u(this,wf,"f").image_file,u(this,S$,"f"));break}CS(this,JM,M.index,"f")}CS(this,wf,$.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,Yf,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 p$ 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{}p$.RunsPage=HJ;p$.Steps=WM;p$.RunStepsPage=_J;class V$ extends i{constructor(){super(...arguments);this.runs=new p$(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=p$;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`,Rf,{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 Rf extends PT{}AM.VectorStoreFilesPage=Rf;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`,Rf,{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=Rf;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 Of 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 Ff({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class yM extends PT{}Of.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 Gf 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{}Gf.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 zf 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,...$})}}zf.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 Af(this),this.embeddings=new XM(this),this.files=new Of(this),this.images=new wM(this),this.audio=new E$(this),this.moderations=new RM(this),this.models=new Gf(this),this.fineTuning=new N$(this),this.beta=new $$(this),this.batches=new kf(this),this.uploads=new zf(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=Jf;RT.APIConnectionTimeoutError=Ff;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=Af;RT.Embeddings=XM;RT.Files=Of;RT.FileObjectsPage=yM;RT.Images=wM;RT.Audio=E$;RT.Moderations=RM;RT.Models=Gf;RT.ModelsPage=YM;RT.FineTuning=N$;RT.Beta=$$;RT.Batches=kf;RT.BatchesPage=sf;RT.Uploads=zf;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 _f(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,i$))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,i$))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 i$(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 i${constructor(T){this.name=T}static[Y]="Placeholder";getSQL(){return new t([this])}}function z1(T,S){return T.map(($)=>{if(V($,i$)){if(!($.name in S))throw new Error(`No value for placeholder "${$.name}" was provided`);return S[$.name]}if(V($,IS)&&V($.value,i$)){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,i$)&&!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 l$ 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 l${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 l${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 l${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 l${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 u$=(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 d$ extends L1{constructor(T,S,$,f){super(T,S,$?.relationName);this.config=$,this.isNullable=f}static[Y]="One";withFieldName(T){let S=new d$(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=_f(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=_f(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 d$(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($,d$)&&$.config)return{fields:$.config.fields,references:$.config.references};let f=S[_f($.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[_f(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],d$)&&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,d$)?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 Hf=(T)=>{let S=T[0];for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Df=(T)=>{let S=T[0].toUpperCase();for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Ef=(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)}),{}):$}}Hf.column={from:Hf};Hf.value={from:m1(Hf)};ZJ.column={to:ZJ};var h1={...Hf};h1.column.to=ZJ;Df.column={from:Df};Df.value={from:m1(Df)};mJ.column={to:mJ};var v1={...Df};v1.column.to=mJ;Ef.column={from:Ef};Ef.value={from:m1(Ef)};hJ.column={to:hJ};var P1={...Ef};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 Qf 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,r$=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(),r$]),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 Qf,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,I$=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(r$),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(r$),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 I$||(!WS.reserved&&f(WS),!WS.reserved&&!FS&&!m&&C.length===0?(BM(),new Promise((w)=>O&&O.readyState!=="closed"?O.once("close",w):w())):I$=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(),I$=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 Qf,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?I$?BM():(WS.reserved=null,$(WS)):WS.reserved():I$?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(r$);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 Qf),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),b$=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[b$],table:AS,number:YS,type:b$},r+=18}if(P.statement=m.statement,m.onlyDescribe)return m.resolve(m.statement),TS(r$)}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,b$)=>(YS[b$[0]]=b$.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(r$)}function lK(w){H.pid=w.readUInt32BE(5),H.secret=w.readUInt32BE(9)}async function uK(){MT=!1,(await new oS([`
|
|
13
13
|
select b.oid, b.typarray
|
|
14
14
|
from pg_catalog.pg_type a
|
|
15
15
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
16
16
|
where a.typcategory = 'A'
|
|
17
17
|
group by b.oid, b.typarray
|
|
18
18
|
order by b.oid
|
|
19
|
-
`],[],VM)).forEach(({oid:_,typarray:r})=>
|
|
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([`
|
|
20
20
|
show transaction_read_only;
|
|
21
21
|
select pg_catalog.pg_is_in_recovery()
|
|
22
|
-
`],[],VM,null,{simple:!0});
|
|
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(r$);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 Qf,TS(GA("",m.cursorRows)))}catch(w){TS(r$),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,b$)=>{if(YS===null)return d.i32(4294967295);AS=_[b$],w[b$]=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`
|
|
23
23
|
select
|
|
24
24
|
lo_lseek64(${W}, location, 0) as position,
|
|
25
25
|
seek.size
|
|
@@ -29,10 +29,10 @@ var GK=Object.create;var{getPrototypeOf:zK,defineProperty:hW,getOwnPropertyNames
|
|
|
29
29
|
tell.location
|
|
30
30
|
from (select lo_tell64($1) as location) tell
|
|
31
31
|
) seek
|
|
32
|
-
`};return f(A),new Promise(async(y)=>F=y);async function k({highWaterMark:y=16384,start:w=0,end:G=1/0}={}){let z=G-w;return w&&await A.seek(w),new Ww.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:w=0}={}){return w&&await A.seek(w),new Ww.Writable({highWaterMark:y,write(G,z,Q){A.write(G).then(()=>Q(),Q)}})}}).catch(M)})}Object.assign(UW,{PostgresError:_M,toPascal:Df,pascal:v1,toCamel:Hf,camel:h1,toKebab:Ef,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 $=ZY(T,S),f=$.no_subscribe||t1(UW,{...$}),M=!1,J=qS(),F=qS(),W=qS(),A=qS(),k=qS(),X=qS(),y=qS(),w=qS(),G={connecting:F,reserved:W,closed:A,ended:k,open:X,busy:y,full:w},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)=>{qY.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===w?N.push(pT):p.execute(pT)||D(p,w)}}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=I$,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 I$(xT,tS){if(xT&&Array.isArray(xT.raw))return I$((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===w?kT.push(xT):bT.execute(xT)||D(bT,w)}}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,w)}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,w)}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 ZY(T,S){if(T&&T.shared)return T;let $=process.env,f=(!T||typeof T==="string"?S:T)||{},{url:M,multihost:J}=nY(T),F=[...M.searchParams].reduce((w,[G,z])=>(w[G]=z,w),{}),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||cY();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:vY,max_pipeline:100,backoff:hY,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: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((w,[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 w[G]=typeof Q==="string"&&X.includes(G)?+Q:Q,w},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries(F).reduce((w,[G,z])=>((G in y)||(w[G]=z),w),{})},types:f.types||{},target_session_attrs:mY(f,M,$),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:PY(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...r8(f.types)}}function mY(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 hY(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function vY(){return 60*(30+Math.random()*30)}function PY(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 nY(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 cY(){try{return bY.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 Aw(this.table,S,this.session,this.dialect,this.withList)}}class Aw 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 oY(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(($)=>$.toLowerCase()).join("_")}function gY(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 tY(T){return T}class i1{static[Y]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?oY:T==="camelCase"?gY:tY}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 Uf{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`
|
|
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:Df,pascal:v1,toCamel:Hf,camel:h1,toKebab:Ef,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=I$,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 I$(xT,tS){if(xT&&Array.isArray(xT.raw))return I$((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 Uf{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
33
|
CREATE TABLE IF NOT EXISTS ${R.identifier(M)}.${R.identifier(f)} (
|
|
34
34
|
id SERIAL PRIMARY KEY,
|
|
35
35
|
hash text NOT NULL,
|
|
36
36
|
created_at bigint
|
|
37
37
|
)
|
|
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:w,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(w)B=w===!0?R` distinct`:R` distinct on (${R.join(w.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 ":""}`),w=F?R` offset ${F}`:void 0;return R`${W}${y}${A}${k}${X}${w}`}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,w=$?R` on conflict ${$}`:void 0;return R`${k}insert into ${T} ${A} values ${X}${w}${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,wW))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,w=[],G,z=[];if(J===!0)k=Object.entries(M.columns).map(([B,L])=>({dbKey:L.name,tsKey:B,field:K$(L,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let E=Object.fromEntries(Object.entries(M.columns).map(([H,U])=>[H,K$(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)?K$(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];w=D.map((H)=>{if(V(H,NT))return K$(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=_f(Z.referencedTable),o=$[O],P=`${F}_${H}`,a=jJ(...h.fields.map((UT,VS)=>TW(K$(h.references[VS],P),K$(UT,F)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[o],tableConfig:S[o],queryConfig:V(Z,d$)?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}${w.length>0?R` order by ${R.join(w,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||w.length>0)Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:X,offset:y,orderBy:w,setOperators:[]}),G=void 0,X=void 0,y=void 0,w=[];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)?K$(b,F):b})),joins:z,where:G,limit:X,offset:y,orderBy:w,setOperators:[]})}else Q=this.buildSelectQuery({table:eF(f,F),fields:{},fieldsFlat:k.map(({field:E})=>({path:[],field:V(E,NT)?K$(E,F):E})),joins:z,where:G,limit:X,offset:y,orderBy:w,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 kw 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"?$(pY()):$;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 kw{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 pY=()=>({union:iY,unionAll:lY,intersect:uY,intersectAll:dY,except:rY,exceptAll:aY}),iY=EM("union",!1),lY=EM("union",!0),uY=EM("intersect",!1),dY=EM("intersect",!0),rY=EM("except",!1),aY=EM("except",!0);class d1{static[Y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=V(T,Uf)?T:void 0,this.dialectConfig=V(T,Uf)?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 Uf(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 Xw(this.table,$W(this.table,T),this.session,this.dialect,this.withList)}}class Xw 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)=>KW(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 yw{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 ww(this.config,T)}}class ww{static[Y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function TA(T){return new yw(!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 Kw 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 Kw(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 Yw 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 Uf({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 Yw(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 Rw(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),w=A.merge(k).merge(W),G=X?w.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 eY="__vite_start_time"in globalThis,sY=typeof window!=="undefined",km="vitest"in globalThis,j$=Rw({isServer:!eY&&!sY,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={};DK(FA,{users:()=>Vf,userChanges:()=>S7,untrackedUserColumnNames:()=>T7,twoFactorMethod:()=>_w,trackedUserColumnName:()=>zw,trackableUserColumnNames:()=>Gw,role:()=>Ow,players:()=>JA,passwordResetAttempts:()=>f7,loginHistory:()=>$7,games:()=>xW,banishedIps:()=>jW});var Ow=dF("role",["admin","user"]),Vf=u$("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:Ow().default("user")},(T)=>({usersUsernameUnique:TA().on(T.username),usersEmailUnique:TA().on(T.email)})),T7=["id","createdAt","createdIp","isActive","salt","verifiedAt"],Gw=["username","email","hash","userRole"],zw=dF("trackedUserColumnName",Gw),S7=u$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Vf.id),changedAt:M$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:zw().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),xW=u$("games",{id:bS("id").primaryKey().defaultRandom()}),JA=u$("players",{userId:bS().notNull().references(()=>Vf.id),gameId:bS().notNull().references(()=>xW.id),score:JW().notNull()},(T)=>({pk:q8({columns:[T.userId,T.gameId]})})),$7=u$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Vf.id),loginTime:M$({withTimezone:!0}).notNull().defaultNow(),ipAddress:MS({length:45}).notNull(),userAgent:MS({length:1024}),successful:IJ().notNull().default(!1)}),_w=dF("twoFactorMethod",["email","phone"]),f7=u$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Vf.id),requestedIp:MS({length:45}).notNull(),requestedAt:M$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:M$({withTimezone:!0}),verificationMethod:_w().notNull()}),jW=u$("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(M7.resolve(__dirname,"notify_update.sql"));let T=[PS(Vf),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 Hw from"readline";function J7(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 Dw(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=Hw.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,w=J7(y);if(!Number.isNaN(w.getTime())){if(w>=F&&w<=$){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 F7=["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 Ew(T){return F7+T.join("\n\n")}var Qw={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 Uw({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 Dw($,S,f),W=[],A=T.from(Qw),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=Ew(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);let w=[],G=HT.object({lastDay:HT.string()}),z=y7(import.meta.dirname,"tribunal.cache.json");if(A7(z)){let C=await k7(z,"utf-8");try{let D=JSON.parse(C),{lastDay:H}=G.parse(D);if(H){let U=new Date(H);w.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:SW(jW.banishedAt,U)}))}}catch(D){$.error(D)}}try{await Promise.all(w.map((C)=>new Promise((D,H)=>W7(`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 X7(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 Bf=new F0;process.on("SIGINT",()=>{Bf.logger.info("\u2757 received SIGINT; exiting gracefully"),bW()});process.on("SIGTERM",()=>{Bf.logger.info("\u2757 received SIGTERM; exiting gracefully"),bW()});process.on("exit",()=>{Bf.logger.info("\u2757 received exit; exiting gracefully"),bW()});Bf.logger.info("\uD83D\uDEEB tribunal worker ready");var K7=new rX({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:j$.OPENAI_API_KEY,cachingMode:"off",logger:Bf.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 Uw({generator:K7,logFilePath:"/var/log/nginx/access.log",logger:Bf.logger});bW();function bW(){Bf.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
|
|
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=_f(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,d$)?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,Uf)?T:void 0,this.dialectConfig=V(T,Uf)?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 Uf(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 Uf({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:()=>Vf,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"]),Vf=u$("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=u$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Vf.id),changedAt:M$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:_K().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),xW=u$("games",{id:bS().primaryKey().defaultRandom()}),JA=u$("players",{userId:bS().notNull().references(()=>Vf.id),gameId:bS().notNull().references(()=>xW.id),score:JW().notNull()},(T)=>[q8({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),f7=u$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Vf.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=u$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Vf.id),requestedIp:MS({length:45}).notNull(),requestedAt:M$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:M$({withTimezone:!0}),verificationMethod:HK().notNull()}),jW=u$("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(Vf),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);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 Bf=new F0;process.on("SIGINT",()=>{Bf.logger.info("\u2757 received SIGINT; exiting gracefully"),bW()});process.on("SIGTERM",()=>{Bf.logger.info("\u2757 received SIGTERM; exiting gracefully"),bW()});process.on("exit",()=>{Bf.logger.info("\u2757 received exit; exiting gracefully"),bW()});Bf.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:Bf.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:Bf.logger});bW();function bW(){Bf.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
|