tempest.games 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var CD=Object.create;var{getPrototypeOf:kD,defineProperty:N9,getOwnPropertyNames:jD}=Object;var ID=Object.prototype.hasOwnProperty;var fD=(W,$,X)=>{X=W!=null?CD(kD(W)):{};let Y=$||!W||!W.__esModule?N9(X,"default",{value:W,enumerable:!0}):X;for(let J of jD(W))if(!ID.call(Y,J))N9(Y,J,{get:()=>W[J],enumerable:!0});return Y};var PD=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var xD=(W,$)=>{for(var X in $)N9(W,X,{get:$[X],enumerable:!0,configurable:!0,set:(Y)=>$[X]=()=>Y})};var FB=(W,$)=>()=>(W&&($=W(W=0)),$);var TG=import.meta.require;var I3=PD((dC,j3)=>{var D4=TG("os"),M4=TG("path");function k3(W){let $=process.env.XDG_CACHE_HOME||M4.join(D4.homedir(),".cache");return M4.join($,W)}function OM(W){return M4.join(D4.homedir(),"Library","Caches",W)}function KM(W){let $=process.env.LOCALAPPDATA||M4.join(D4.homedir(),"AppData","Local");return M4.join($,W,"Cache")}var AM=function(){switch(D4.platform()){case"darwin":return OM;case"win32":return KM;case"aix":case"android":case"freebsd":case"linux":case"netbsd":case"openbsd":case"sunos":return k3;default:return console.error(`(node:${process.pid}) [cachedir] Warning: the platform "${D4.platform()}" is not currently supported by node-cachedir, falling back to "posix". Please file an issue with your platform here: https://github.com/LinusU/node-cachedir/issues/new`),k3}}();j3.exports=function W($){if(typeof $!=="string")throw new TypeError("id is not a string");if($.length===0)throw new Error("id cannot be empty");if(/[^0-9a-zA-Z-]/.test($))throw new Error("id cannot contain special characters");return AM($)}});class c$ extends Promise{fate;resolve;reject;done=!1;constructor(W){let $,X;super((Y,J)=>{$=Y,X=J});this.resolve=$,this.reject=X,this.use(W instanceof Promise?W:new Promise(W))}pass(W,$){if(W===this.fate)this.resolve($),this.done=!0}fail(W,$){if(W===this.fate)this.reject($),this.done=!0}use(W){if(W instanceof Promise){let $=W;this.fate=$,$.then((X)=>{this.pass($,X)},(X)=>{this.fail($,X)})}else this.resolve(W),this.fate=void 0}}var _B=(W,$,X=wG.STORE)=>{return UG(X,{key:`${W.key}:JSON`,get:({get:Y})=>$.toJson(Y(W)),set:({set:Y},J)=>{Y(W,$.fromJson(J))}})};function VB(W,$,X){return Z9(W,{key:`${$.key}:JSON`,get:(J)=>({get:G})=>{let H=G($,J);return X.toJson(H)},set:(J)=>({set:G},H)=>{G($,J,X.fromJson(H))}},["mutable","json"])}var d$=(W)=>JSON.parse(W),S1=(W)=>JSON.stringify(W),KB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function G0(W){while(W.child!==null)W=W.child;return W}class XX{_buffer;_index=0;constructor(W){let $;if(typeof W==="number")$=W;else $=W.length;this._buffer=Array.from({length:$})}get buffer(){return this._buffer}get index(){return this._index}add(W){this._buffer[this._index]=W,this._index=(this._index+1)%this._buffer.length}copy(){let W=new XX([...this._buffer]);return W._index=this._index,W}}var vD={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function _G(W,$){let X=S1($),Y=`${W.key}(${X})`,J=vD[W.type],G={key:Y,type:J};return Object.assign(G,{family:{key:W.key,subKey:X}}),Object.assign(G,{counterfeit:!0}),G}function l$(W){let $={key:W.key,type:W.type};if("family"in W)$.family=W.family;return $}var S9=(W)=>($,X,Y,J,...G)=>{console[W](`${$} ${X} "${Y}" ${J}`,...G)},bD={error:S9("error"),info:S9("info"),warn:S9("warn")};class q9{logLevel;filter;logger;constructor(W,$,X=bD){this.logLevel=W,this.filter=$,this.logger=X}error=(...W)=>{if((this.filter?.(...W)??!0)&&this.logLevel!==null)this.logger.error(...W)};info=(...W)=>{if((this.filter?.(...W)??!0)&&this.logLevel==="info")this.logger.info(...W)};warn=(...W)=>{if((this.filter?.(...W)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...W)}}class fW{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(W,$)=>`${W}:${$}`;warn;getRelatedKeys(W){return this.relations.get(W)}addRelation(W,$){let X=this.relations.get(W),Y=this.relations.get($);if(X)X.add($);else X=new Set([$]),this.relations.set(W,X);if(Y)Y.add(W);else Y=new Set([W]),this.relations.set($,Y)}deleteRelation(W,$){let X=this.relations.get(W);if(X){if(X.delete($),X.size===0)this.relations.delete(W);let Y=this.relations.get($);if(Y){if(Y.delete(W),Y.size===0)this.relations.delete($)}}}replaceRelationsUnsafely(W,$){this.relations.set(W,new Set($));for(let X of $){let Y=new Set().add(W);this.relations.set(X,Y)}}replaceRelationsSafely(W,$){let X=this.relations.get(W),Y=this.isAType?.(W)?W:void 0,J=Y===void 0?W:void 0;if(X)for(let G of X){Y??=G,J??=G;let H=this.relations.get(G);if(H){if(H.size===1)this.relations.delete(G);else H.delete(W);this.contents.delete(this.makeContentKey(Y,J))}}this.relations.set(W,new Set($));for(let G of $){let H=this.relations.get(G);if(H)H.add(W);else H=new Set().add(W),this.relations.set(G,H)}}getContentInternal(W){return this.contents.get(W)}setContent(W,$){this.contents.set(W,$)}deleteContent(W){this.contents.delete(W)}constructor(W,$){if(this.a=W.between[0],this.b=W.between[1],this.cardinality=W.cardinality,!$?.externalStore)this.relations=new Map(W.relations?.map(([X,Y])=>[X,new Set(Y)])),this.contents=new Map(W.contents);if(this.isAType=$?.isAType??null,this.isBType=$?.isBType??null,this.isContent=$?.isContent??null,$?.makeContentKey)this.makeContentKey=$.makeContentKey;if($?.externalStore){let X=$.externalStore;if(this.has=(Y,J)=>X.has(Y,J),this.addRelation=(Y,J)=>{X.addRelation(Y,J)},this.deleteRelation=(Y,J)=>{X.deleteRelation(Y,J)},this.replaceRelationsSafely=(Y,J)=>{X.replaceRelationsSafely(Y,J)},this.replaceRelationsUnsafely=(Y,J)=>{X.replaceRelationsUnsafely(Y,J)},this.getRelatedKeys=(Y)=>X.getRelatedKeys(Y),X.getContent)this.getContentInternal=(Y)=>{return X.getContent(Y)},this.setContent=(Y,J)=>{X.setContent(Y,J)},this.deleteContent=(Y)=>{X.deleteContent(Y)};for(let[Y,J]of W.relations??[]){let G=this.isAType?.(Y)?Y:void 0,H=G===void 0?Y:void 0;for(let Q of J)G??=Q,H??=Q,this.addRelation(G,H)}for(let[Y,J]of W.contents??[])this.setContent(Y,J)}if($?.warn)this.warn=$.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([W,$])=>[W,[...$]]),contents:[...this.contents.entries()]}}set(...W){let $,X,Y;switch(W.length){case 1:{let J=W[0];$=J[this.a],X=J[this.b],Y=void 0;break}case 2:{let J=W[0];if(typeof J==="string")[$,X]=W;else $=J[this.a],X=J[this.b],Y=W[1];break}default:{$=W[0],X=W[1],Y=W[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey($);if(J&&J!==X)this.delete($,J)}case"1:n":{let J=this.getRelatedKey(X);if(J&&J!==$)this.delete(J,X)}break;case"n:n":}if(Y){let J=this.makeContentKey($,X);this.setContent(J,Y)}return this.addRelation($,X),this}delete(W,$){$=typeof $==="string"?$:W[this.b];let X=typeof W==="string"?W:W[this.a];if(X===void 0&&typeof $==="string"){let Y=this.getRelatedKeys($);if(Y)for(let J of Y)this.delete(J,$)}if(typeof X==="string"&&$===void 0){let Y=this.getRelatedKeys(X);if(Y)for(let J of Y)this.delete(X,J)}if(typeof X==="string"&&typeof $==="string"){this.deleteRelation(X,$);let Y=this.makeContentKey(X,$);this.deleteContent(Y)}return this}getRelatedKey(W){let $=this.getRelatedKeys(W);if($){if($.size>1)this.warn?.(`${$.size} related keys were found for key "${W}": (${[...$].map((Y)=>`"${Y}"`).join(", ")}). Only one related key was expected.`);let X;for(let Y of $){X=Y;break}return X}}replaceRelations(W,$,X){let Y=!Array.isArray($),J=Y?Object.keys($):$;if(X?.reckless)this.replaceRelationsUnsafely(W,J);else this.replaceRelationsSafely(W,J);if(Y)for(let G of J){let H=this.makeContentKey(W,G),Q=$[G];this.setContent(H,Q)}return this}getContent(W,$){let X=this.makeContentKey(W,$);return this.getContentInternal(X)}getRelationEntries(W){let $=W[this.a],X=W[this.b];if($!==void 0&&X===void 0){let Y=this.getRelatedKeys($);if(Y)return[...Y].map((J)=>{return[J,this.getContent($,J)]})}if($===void 0&&X!==void 0){let Y=this.getRelatedKeys(X);if(Y)return[...Y].map((J)=>{return[J,this.getContent(J,X)]})}return[]}has(W,$){if($)return this.getRelatedKeys(W)?.has($)??!1;return this.relations.has(W)}}class S0{Subscriber;subscribers=new Map;subscribe(W,$){return this.subscribers.set(W,$),()=>{this.unsubscribe(W)}}unsubscribe(W){this.subscribers.delete(W)}next(W){let $=this.subscribers.values();for(let X of $)X(W)}}class C9 extends S0{state;constructor(W){super();this.state=W}next(W){this.state=W,super.next(W)}}function f8(W){return"epoch"in W.transactionMeta}function l1(W){return"phase"in W.transactionMeta}function DG(W){return W[0].toUpperCase()+W.slice(1)}function YX(W){return W.type.split("_").map(DG).join(" ")}class o$ extends Error{constructor(W,$){super(`${YX(W)} ${S1(W.key)} not found in store "${$.config.name}".`)}}var JX=(W)=>($)=>W instanceof Function?W($):W;var A2=(W,$)=>{if(W.valueMap.has($.key))return W.logger.info("\uD83D\uDCD6",$.type,$.key,"reading cached value"),MG($,W);switch($.type){case"selector":case"readonly_selector":return W.logger.info("\uD83E\uDDEE",$.type,$.key,"computing value"),$.get();case"atom":case"mutable_atom":{let X=$.default,Y;if(X instanceof Function)Y=X();else Y=X;return W.logger.info("\uD83D\uDC81","atom",$.key,"could not find cached value; using default",Y),Y}}};var VG=(W,$)=>{if(W.operation.open){let X=performance.now();return W.logger.info("\u2757",$.type,$.key,`deferring setState at T-${X} until setState for "${W.operation.token.key}" is done`),X}W.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:$},W.logger.info("\u2B55",$.type,$.key,`operation start in store "${W.config.name}"${!l1(W)?"":` ${W.transactionMeta.phase} "${W.transactionMeta.update.key}"`}`)},OG=(W)=>{if(W.operation.open)W.logger.info("\uD83D\uDD34",W.operation.token.type,W.operation.token.key,`operation done in store "${W.config.name}"`);W.operation={open:!1},W.on.operationClose.next(W.operation)},KG=(W,$)=>{if(!W.operation.open)return W.logger.error("\uD83D\uDC1E","unknown",$,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return W.operation.done.has($)},P8=(W,$)=>{if(!W.operation.open){W.logger.error("\uD83D\uDC1E","unknown",$,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}W.operation.done.add($)};var AG=(W,$,X)=>{switch($.type){case"mutable_atom":W.logger.info("\uD83D\uDCE2",$.type,$.key,"is now (",X.newValue,") subscribers:",$.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":W.logger.info("\uD83D\uDCE2",$.type,$.key,"went (",X.oldValue,"->",X.newValue,") subscribers:",$.subject.subscribers)}$.subject.next(X)};var k9=(W,$)=>{let X=G0(W),Y=X.selectorAtoms.getRelatedKeys($.key);if(X.logger.info("\uD83E\uDDF9",$.type,$.key,Y?`evicting ${Y.size} states downstream:`:"no downstream states",Y??"to evict"),Y){if(X.operation.open)X.logger.info("\uD83E\uDDF9",$.type,$.key,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let J of Y){if(KG(X,J))continue;EG(J,X),P8(X,J)}}};var LG=(W,$,X)=>{let Y=A2(W,$),J=Y;if($.type==="mutable_atom"&&l1(W)){let{parent:H}=W;J=i$(W,$,H)}if(J=JX(X)(J),W.logger.info("\uD83D\uDCDD","atom",$.key,"set to",J),J=PW(W,$.key,J,$.subject),RG(W,$.key))NG(W,$.key);P8(W,$.key),k9(W,$);let G={oldValue:Y,newValue:J};if(!l1(W)){AG(W,$,G);return}if(W.on.transactionApplying.state===null){let{key:H}=$;if(BG(G.newValue))return;let Q={type:"atom_update",key:H,...G};if($.family)Q.family=$.family;W.transactionMeta.update.updates.push(Q),W.logger.info("\uD83D\uDCC1","atom",H,"stowed (",G.oldValue,"->",G.newValue,")")}else if($.key.startsWith("*")){let H=$.key.slice(1),Q=W.atoms.get(H),z=W.valueMap.get(H);if(Q.type==="mutable_atom"&&l1(W)){let{parent:T}=W;z=i$(W,Q,T)}if(z.do(G.newValue)===null)k9(W,Q)}};var GX=(W,$,X)=>{switch($.type){case"atom":case"mutable_atom":LG(W,$,X);break;case"selector":$.set(X);break}};var HX=(W,$)=>G0(W).atoms.has($),yD=(W,$)=>G0(W).selectors.has($),hD=(W,$)=>G0(W).readonlySelectors.has($),ZG=(W,$)=>HX(W,$)||yD(W,$)||hD(W,$);var QX=(W,$)=>{return G0($).selectorGraph.getRelationEntries({downstreamSelectorKey:W}).filter(([Y,{source:J}])=>J!==W).map(([Y,{source:J}])=>J).filter((Y)=>ZG($,Y))};var j9=(W,$,X)=>{let Y=[],J=QX(W,X);while(J.length>0){let G=J.shift();if($.has(G))continue;if($.add(G),!HX(X,G))J.push(...QX(G,X));else if(!Y.includes(G))Y.push(G)}return Y},SG=(W,$)=>{let X=W.key,Y=QX(X,$),J=new Set;return Y.flatMap((G)=>HX($,G)?G:j9(G,J,$))};var qG=(W,$,X,Y)=>{let J=G0(Y);if($.type==="atom"||$.type==="mutable_atom")J.selectorAtoms.set({selectorKey:W,atomKey:$.key}),Y.logger.info("\uD83D\uDD0D","selector",W,`discovers root atom "${$.key}"`);else{let G=j9($.key,X,Y);Y.logger.info("\uD83D\uDD0D","selector",W,`discovers root atoms: [ ${G.map((H)=>`"${H}"`).join(", ")} ]`);for(let H of G)J.selectorAtoms=J.selectorAtoms.set({selectorKey:W,atomKey:H})}X.add($.key)};var zX=(W,$,X)=>({get:(...Y)=>{let J=G0(X),G;if(Y.length===2){let[z,F]=Y;G=o1(X,z,F)}else[G]=Y;let H=x1(X,G),Q=A2(X,H);return X.logger.info("\uD83D\uDD0C","selector",W,`registers dependency ( "${G.key}" =`,Q,")"),J.selectorGraph.set({upstreamSelectorKey:G.key,downstreamSelectorKey:W},{source:G.key}),qG(W,G,$,X),Q},set:(...Y)=>{let J,G;if(Y.length===2)J=Y[0],G=Y[1];else{let z=Y[0],F=Y[1];G=Y[2],J=o1(X,z,F)}let H=G0(X),Q=x1(H,J);GX(H,Q,G)},find:(...Y)=>o1(X,...Y),json:(Y)=>x8(X,Y)});var I9=(W,$,X)=>{let Y=G0(W),J=new S0,G=new Set,{get:H,find:Q,json:z}=zX($.key,G,Y),F=()=>{let V=$.get({get:H,find:Q,json:z});return PW(G0(W),$.key,V,J),G.clear(),V},T={...$,subject:J,install:(V)=>I9(V,$,X),get:F,type:"readonly_selector",...X&&{family:X}};Y.readonlySelectors.set($.key,T);let U=F();W.logger.info("\u2728",T.type,T.key,"=",U);let _={key:$.key,type:"readonly_selector"};if(X)_.family=X;return _};var n$=(W,$,X)=>{let Y=G0(W),J=new S0,G=new Set,H=zX($.key,G,Y),{find:Q,get:z,json:F}=H,T={find:Q,get:z,json:F},U=(I=$.get,C=G0(W))=>{let R=I(T);return PW(C,$.key,R,J),G.clear(),R},V={...$,subject:J,install:(I)=>n$(I,$,X),get:U,set:(I)=>{let C=G0(W),R=U($.get,C),q=JX(I)(R);if(W.logger.info("\uD83D\uDCDD","selector",$.key,"set (",R,"->",q,")"),PW(C,$.key,q,J),P8(C,$.key),f8(C))J.next({newValue:q,oldValue:R});$.set(H,q)},type:"selector",...X&&{family:X}};Y.selectors.set($.key,V);let K=U();W.logger.info("\u2728",V.type,V.key,"=",K);let B={key:$.key,type:"selector"};if(X)B.family=X;return B};function UG(W,$){if("set"in $){let J=n$(W,$,void 0);return W.on.selectorCreation.next(J),J}let Y=I9(W,$,void 0);return W.on.selectorCreation.next(Y),Y}function Z9(W,$,X){let Y={key:$.key,type:"selector_family"},J=W.families.get($.key);if(J)W.logger.error("\u2757","selector_family",$.key,`Overwriting an existing ${YX(J)} "${J.key}" in store "${W.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let G=new S0,Q=Object.assign((z)=>{let F=S1(z),T={key:$.key,subKey:F},U=`${$.key}(${F})`,_=G0(W),V=n$(_,{key:U,get:$.get(z),set:$.set(z)},T);return G.next({type:"state_creation",token:V}),V},Y,{internalRoles:X,subject:G,install:(z)=>Z9(z,$),default:(z)=>{return $.get(z)({get:(...T)=>r$(W,...T),find:(...T)=>o1(W,...T),json:(T)=>x8(W,T)})}});return W.families.set($.key,Q),Y}function CG(W,$,X){let Y=W.families.get($.key);if(Y===void 0)throw new o$($,W);let J=Y(X),G=G0(W);if(J.family){if(f8(G))switch(J.type){case"atom":case"mutable_atom":W.on.atomCreation.next(J);break;case"selector":case"readonly_selector":W.on.selectorCreation.next(J);break}else if(l1(G)&&G.on.transactionApplying.state===null)G.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function kG(W,$,X){let Y=S1(X),J=`${$.key}(${Y})`,G=G0(W),H;switch($.type){case"atom_family":case"mutable_atom_family":H=G.atoms.get(J);break;case"selector_family":H=G.selectors.get(J);break;case"readonly_selector_family":H=G.readonlySelectors.get(J);break}if(H)return l$(H);return H}function o1(W,$,X){let Y=kG(W,$,X);if(Y)return Y;let J=S1(X),G=W.molecules.get(J);if(!G&&W.config.lifespan==="immortal"){let H=_G($,X);return W.logger.error("\u274C",H.type,H.key,`was not found in store "${W.config.name}"; returned a counterfeit token.`),H}if(Y=CG(W,$,X),G)G0(W).moleculeData.set(J,$.key);return Y}function jG(W,$){if($.family){let X=W.families.get($.family.key);if(X)return X}}function E2(W,...$){let X,Y,J,G;if($.length===2){if(X=$[0],G=$[1],Y=jG(W,X)??null,Y)J=X.family?d$(X.family.subKey):null,X=o1(W,Y,J)}else Y=$[0],J=$[1],G=$[2],X=o1(W,Y,J);if("counterfeit"in X&&"family"in X){let z=X.family.subKey,F=W.disposalTraces.buffer.find((T)=>T?.key===z);W.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${W.config.name}".`,F?`This state was previously disposed:
4
- ${F.trace}`:"No previous disposal trace was found.");return}let H=VG(W,X);if(H){let z=W.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${H}`,()=>{z(),W.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${H}`),E2(W,X,G)});return}let Q=x1(W,X);GX(W,Q,G),OG(W)}function r$(W,...$){let X,Y,J;if($.length===1)X=$[0];else Y=$[0],J=$[1],X=o1(W,Y,J);if("counterfeit"in X&&"family"in X){Y=W.families.get(X.family.key);let G=X.family.subKey,H=W.disposalTraces.buffer.find((Q)=>Q?.key===G);switch(W.logger.error("\u274C",X.type,X.key,`could not be retrieved because it was not found in the store "${W.config.name}".`,H?`This state was previously disposed:
5
- ${H.trace}`:"No previous disposal trace was found."),Y.type){case"atom_family":case"mutable_atom_family":return W.defaults.get(Y.key);case"selector_family":case"readonly_selector_family":{if(W.defaults.has(Y.key))return W.defaults.get(X.family.key);let Q=x1(W,Y).default(G);return W.defaults.set(Y.key,Q),Q}}}return A2(W,x1(W,X))}class IG{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new fW({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new fW({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new fW({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new fW({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new XX(100);molecules=new Map;moleculeJoins=new fW({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});moleculeGraph=new fW({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});moleculeData=new fW({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});miscResources=new Map;on={atomCreation:new S0,atomDisposal:new S0,selectorCreation:new S0,selectorDisposal:new S0,timelineCreation:new S0,transactionCreation:new S0,transactionApplying:new C9(null),operationClose:new S0,moleculeCreation:new S0,moleculeDisposal:new S0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new q9("warn",(W,$,X)=>!PG(X))];logger={error:(...W)=>{for(let $ of this.loggers)$.error(...W)},info:(...W)=>{for(let $ of this.loggers)$.info(...W)},warn:(...W)=>{for(let $ of this.loggers)$.warn(...W)}};constructor(W,$=null){if(this.config={...$?.config,...W},$!==null){if(this.valueMap=new Map($?.valueMap),this.operation={...$?.operation},f8($))this.transactionMeta={epoch:new Map($?.transactionMeta.epoch),actionContinuities:new fW($?.transactionMeta.actionContinuities.toJSON())};for(let[,Y]of $.families){if(Y.internalRoles?.includes("mutable")||Y.internalRoles?.includes("join"))continue;Y.install(this)}let X=new Set;for(let[,Y]of $.atoms){if(X.has(Y.key))continue;if(Y.install(this),Y.type==="mutable_atom"){let J=x8($,Y),G=fG(Y);X.add(J.key),X.add(G.key)}}for(let[,Y]of $.readonlySelectors)Y.install(this);for(let[,Y]of $.selectors){if(X.has(Y.key))continue;Y.install(this)}for(let[,Y]of $.transactions)Y.install(this);for(let[,Y]of $.timelines)Y.install(this)}}}var wG={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new IG({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function x1(W,$){let X,Y=W;while(Y!==null){switch($.type){case"atom":case"mutable_atom":X=Y.atoms.get($.key);break;case"selector":X=Y.selectors.get($.key);break;case"readonly_selector":X=Y.readonlySelectors.get($.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":X=Y.families.get($.key);break;case"timeline":X=Y.timelines.get($.key);break;case"transaction":X=Y.transactions.get($.key);break}if(X)return X;Y=Y.child}throw new o$($,W)}var xG=(W,$)=>{let X=G0(W);if(X.operation.open)return X.operation.prev.get($.key);return X.valueMap.get($.key)};var f9=(W,$)=>{let X=G0(W);return SG($,W).map((J)=>{let G=X.atoms.get(J);if(G===void 0)throw new Error(`Atom "${J}", a dependency of selector "${$.key}", not found in store "${W.config.name}".`);return G.subject.subscribe(`${$.type}:${$.key}`,(H)=>{W.logger.info("\uD83D\uDCE2",$.type,$.key,"root",J,"went",H.oldValue,"->",H.newValue);let Q=xG(X,$),z=A2(X,$);W.logger.info("\u2728",$.type,$.key,"went",Q,"->",z),$.subject.next({newValue:z,oldValue:Q})})})};function t$(W,$,X,Y){function J(U){if(W.operation.open){let _=W.on.operationClose.subscribe(`state subscription ${X}`,()=>{_(),Y(U)})}else Y(U)}let G=x1(W,$);W.logger.info("\uD83D\uDC40",G.type,G.key,`Adding subscription "${X}"`);let H=G.type==="selector"||G.type==="readonly_selector",Q=null,z=J;if(H)Q=f9(W,G),z=(U)=>{if(Q)Q.length=0,Q.push(...f9(W,G));J(U)};let F=G.subject.subscribe(X,z);return()=>{if(W.logger.info("\uD83D\uDE48",G.type,G.key,`Removing subscription "${X}"`),F(),Q)for(let U of Q)U()}}var vG=(W,$,X,Y)=>{let J=x1(W,$);W.logger.info("\uD83D\uDC40","timeline",$.key,`Adding subscription "${X}"`);let G=J.subject.subscribe(X,Y);return()=>{W.logger.info("\uD83D\uDE48","timeline",$.key,`Removing subscription "${X}" from timeline`),G()}};class P9{initializeState(W,$){let X=`*${W.key}`;$.atoms.delete(X),$.valueMap.delete(X);let Y=W.family?{key:`*${W.family.key}`,subKey:W.family.subKey}:void 0,J=x9($,{key:X,default:null},Y);if($.parent?.valueMap.has(X)){let G=$.parent.valueMap.get(X);$.valueMap.set(X,G)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(W,$,X){let Y=`tracker:${X.config.name}:${l1(X)?X.transactionMeta.update.key:"main"}:${W.key}`,J=r$(X,W);this.unsubscribeFromInnerValue=J.subscribe(Y,(G)=>{E2(X,$,G)}),this.unsubscribeFromState=t$(X,W,Y,(G)=>{if(G.newValue!==G.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=G.newValue.subscribe(Y,(H)=>{E2(X,$,H)})})}updateCore(W,$,X){let Y=`tracker:${X.config.name}:${l1(X)?X.transactionMeta.update.key:"main"}:${W.key}`;t$(X,$,Y,({newValue:J,oldValue:G})=>{let H=X.timelineTopics.getRelatedKey($.key);if(H){if(X.timelines.get(H)?.timeTraveling){let F=vG(X,{key:H,type:"timeline"},Y,(T)=>{F(),E2(X,W,(U)=>{if(T==="redo"&&J)U.do(J);else if(T==="undo"&&G)U.undo(G);return U})});return}}let Q=X.on.operationClose.subscribe(Y,()=>{Q();let z=r$(X,W),F=J===null?-1:z.getUpdateNumber(J),T=F-z.cacheUpdateNumber;if(J&&T===1)E2(X,W,(U)=>(U.do(J),U));else X.logger.info("\u274C","mutable_atom",W.key,`could not be updated. Expected update number ${z.cacheUpdateNumber+1}, but got ${F}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(W,$){this.mutableState=W;let X=G0($);this.latestUpdateState=this.initializeState(W,X),this.observeCore(W,this.latestUpdateState,X),this.updateCore(W,this.latestUpdateState,X),X.trackers.set(W.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(W.key)}}}var x8=(W,$)=>{if($.family){let Y=G0(W),G={key:`${$.family.key}:JSON`,type:"selector_family"},H=x1(Y,G),Q=JSON.parse($.family.subKey);return o1(W,H,Q)}return{type:"selector",key:`${$.key}:JSON`}};var fG=(W)=>{let X={type:"atom",key:`*${W.key}`};if(W.family)X.family={key:`*${W.family.key}`,subKey:W.family.subKey};return X};function BG(W){return typeof W==="object"&&W!==null&&"do"in W&&"undo"in W&&"subscribe"in W}function i$(W,$,X){let Y=X.valueMap.get($.key),J=W.valueMap.get($.key);if(Y!==J)return J;if(Y===void 0)return $.default();X.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let G=$.toJson(Y),H=$.fromJson(G);return W.valueMap.set($.key,H),new P9($,X),H}function PW(W,$,X,Y){let J=W.valueMap.get($);if(J instanceof c$)J.use(X);if(X instanceof Promise){let G=new c$(X);return W.valueMap.set($,G),G.then((H)=>{PW(W,$,H,Y),Y.next({newValue:H,oldValue:G})}).catch((H)=>{W.logger.error("\uD83D\uDCA5","state",$,"rejected:",H)}),G}return W.valueMap.set($,X),X}var MG=(W,$)=>{let X=$.valueMap.get(W.key);if(W.type==="mutable_atom"&&l1($)){let{parent:Y}=$;X=i$($,W,Y)}return X},EG=(W,$)=>{let X=$.valueMap.get(W);if(X instanceof c$){let Y=X,J=$.selectors.get(W)??$.readonlySelectors.get(W);if(J)Y.use(J.get());return}if($.operation.open)$.operation.prev.set(W,X);$.valueMap.delete(W),$.logger.info("\uD83D\uDDD1","state",W,"evicted")};var RG=(W,$)=>{return G0(W).atomsThatAreDefault.has($)},bG=(W,$)=>{let X=G0(W);X.atomsThatAreDefault=new Set(X.atomsThatAreDefault).add($)},NG=(W,$)=>{let X=G0(W);X.atomsThatAreDefault=new Set(G0(W).atomsThatAreDefault),X.atomsThatAreDefault.delete($)};function x9(W,$,X){W.logger.info("\uD83D\uDD28","atom",$.key,`creating in store "${W.config.name}"`);let Y=G0(W),J=Y.atoms.get($.key);if(J&&J.type==="atom")return W.logger.error("\u274C","atom",$.key,"Tried to create atom, but it already exists in the store."),l$(J);let G=new S0,H={...$,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",$.key,`installing in store "${F.config.name}"`),x9(F,$,X)},subject:G};if(X)H.family=X;let Q=$.default;if($.default instanceof Function)Q=$.default();Y.atoms.set(H.key,H),bG(W,$.key),PW(Y,$.key,Q,G);let z=l$(H);if($.effects){let F=0,T=[];for(let U of $.effects){let _=U({setSelf:(V)=>{E2(W,z,V)},onSet:(V)=>t$(W,z,`effect[${F}]`,V)});if(_)T.push(_);++F}H.cleanup=()=>{for(let U of T)U()}}return z}class v8 extends Set{mode="record";subject=new S0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(W,$=0){super(W);if(W instanceof v8)this.parent=W,this.cacheUpdateNumber=W.cacheUpdateNumber;if($)this.cacheLimit=$,this.cache=new Array($),this.subscribe("auto cache",(X)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=X})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(W){let $=new v8(W.members,W.cacheLimit);return $.cache=W.cache,$.cacheIdx=W.cacheIdx,$.cacheUpdateNumber=W.cacheUpdateNumber,$}add(W){let $=super.add(W);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S1(W)}`);return $}clear(){let W=this.mode==="record"?[...this]:null;if(super.clear(),W)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(W)}`)}delete(W){let $=super.delete(W);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S1(W)}`);return $}parent=null;child=null;transactionUpdates=null;transaction(W){this.mode="transaction",this.transactionUpdates=[],this.child=new v8(this);let $=this.child._subscribe("transaction",(X)=>{this.transactionUpdates?.push(X)});try{if(W(this.child)){for(let Y of this.transactionUpdates)this.doStep(Y);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(X){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",X),X}finally{$(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(W,$){return this.subject.subscribe(W,$)}subscribe(W,$){return this.subject.subscribe(W,(X)=>{$(`${this.cacheUpdateNumber}=${X}`)})}emit(W){this.subject.next(W)}doStep(W){let $=W.indexOf(":"),X=W.substring(0,$),Y=W.substring($+1);switch(X){case"add":this.add(JSON.parse(Y));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(Y));break;case"tx":for(let J of Y.split(";"))this.doStep(J)}}getUpdateNumber(W){let $=W.indexOf("=");return Number(W.substring(0,$))}do(W){let $=W.indexOf("="),X=Number(W.substring(0,$)),Y=X-this.cacheUpdateNumber;if(Y>0){if(Y===1){this.mode="playback";let G=W.substring($+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=X,null}return this.cacheUpdateNumber+1}if(Math.abs(Y)<this.cacheLimit){let G=this.cacheIdx+Y;if(this.cache[G]===W)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),Q=this.cacheIdx===G-1}let z=W.substring($+1);return this.doStep(z),this.mode="record",this.cacheUpdateNumber=X,null}return"OUT_OF_RANGE"}undoStep(W){let $=W.indexOf(":"),X=W.substring(0,$),Y=W.substring($+1);switch(X){case"add":this.delete(JSON.parse(Y));break;case"del":this.add(JSON.parse(Y));break;case"clear":{let J=JSON.parse(Y);for(let G of J)this.add(G);break}case"tx":{let J=Y.split(";");for(let G=J.length-1;G>=0;G--)this.undoStep(J[G])}}}undo(W){let $=W.indexOf("=");if(Number(W.substring(0,$))===this.cacheUpdateNumber){this.mode="playback";let Y=W.substring($+1);return this.undoStep(Y),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function PG(W){return W.startsWith("\uD83D\uDD0D ")}class FX{listeners;globalListeners;handleEvent(W,...$){for(let Y of this.globalListeners)Y(W,...$);let X=this.listeners.get(W);if(X)for(let Y of X)Y(...$)}id="no_id_retrieved";emit;constructor(W){this.emit=W,this.listeners=new Map,this.globalListeners=new Set}on(W,$){let X=this.listeners.get(W);if(X)X.add($);else this.listeners.set(W,new Set([$]));return this}onAny(W){return this.globalListeners.add(W),this}off(W,$){let X=this.listeners.get(W);if(X)if($)X.delete($);else this.listeners.delete(W);return this}offAny(W){return this.globalListeners.delete(W),this}}class yG extends FX{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(W){super((...$)=>{return this.out.next($),this});this.id=W,this.in=new S0,this.out=new S0,this.in.subscribe("socket",($)=>{this.handleEvent(...$)})}dispose(){for(let W of this.disposalFunctions)W()}}class v9 extends FX{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...W){this.process.stderr.write(S1(W.map(($)=>$ instanceof v8?`{ ${$.toJSON().members.join(" | ")} }`:$))+"\x03")}logger={info:(...W)=>{this.log("i",...W)},warn:(...W)=>{this.log("w",...W)},error:(...W)=>{this.log("e",...W)}};constructor(){super((W,...$)=>{let X=JSON.stringify([W,...$]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(W)=>{let $=W.toString();this.unprocessedEvents.push(...$.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let Y=d$(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",Y),this.handleEvent(...Y);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let G=d$(J);this.handleEvent(...G)}}this.incompleteData=""}catch(Y){if(Y instanceof Error)this.logger.error("\u2757",Y.message,Y.cause,Y.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(W)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${W}`)}),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",(W)=>{this.logger.info("\uD83D\uDC64","user",W,"joined");let $=new yG(`user:${W}`);this.relays.set(W,$),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let Y=X($);if(Y)$.disposalFunctions.push(Y)}this.on(`user:${W}`,(...X)=>{$.in.next(X)}),$.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(W)=>{let $=this.relays.get(W);if(this.off(`relay:${W}`),$)$.dispose(),this.relays.delete(W)}),process.stdout.write("ALIVE")}relay(W){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(W)}}var gG=Symbol("Let zodToJsonSchema decide on which parser to use");var hG={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},mG=(W)=>typeof W==="string"?{...hG,name:W}:{...hG,...W};var pG=(W)=>{let $=mG(W),X=$.name!==void 0?[...$.basePath,$.definitionPath,$.name]:$.basePath;return{...$,currentPath:X,propertyPath:void 0,seen:new Map(Object.entries($.definitions).map(([Y,J])=>[J._def,{def:J._def,path:[...$.basePath,$.definitionPath,Y],jsonSchema:void 0}]))}};function b9(W,$,X,Y){if(!Y?.errorMessages)return;if(X)W.errorMessage={...W.errorMessage,[$]:X}}function O0(W,$,X,Y,J){W[$]=X,b9(W,$,Y,J)}var A0;(function(W){W.assertEqual=(J)=>J;function $(J){}W.assertIs=$;function X(J){throw new Error}W.assertNever=X,W.arrayToEnum=(J)=>{let G={};for(let H of J)G[H]=H;return G},W.getValidEnumValues=(J)=>{let G=W.objectKeys(J).filter((Q)=>typeof J[J[Q]]!=="number"),H={};for(let Q of G)H[Q]=J[Q];return W.objectValues(H)},W.objectValues=(J)=>{return W.objectKeys(J).map(function(G){return J[G]})},W.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let G=[];for(let H in J)if(Object.prototype.hasOwnProperty.call(J,H))G.push(H);return G},W.find=(J,G)=>{for(let H of J)if(G(H))return H;return},W.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&isFinite(J)&&Math.floor(J)===J;function Y(J,G=" | "){return J.map((H)=>typeof H==="string"?`'${H}'`:H).join(G)}W.joinValues=Y,W.jsonStringifyReplacer=(J,G)=>{if(typeof G==="bigint")return G.toString();return G}})(A0||(A0={}));var uG;(function(W){W.mergeShapes=($,X)=>{return{...$,...X}}})(uG||(uG={}));var p=A0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),L2=(W)=>{switch(typeof W){case"undefined":return p.undefined;case"string":return p.string;case"number":return isNaN(W)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":if(Array.isArray(W))return p.array;if(W===null)return p.null;if(W.then&&typeof W.then==="function"&&W.catch&&typeof W.catch==="function")return p.promise;if(typeof Map!=="undefined"&&W instanceof Map)return p.map;if(typeof Set!=="undefined"&&W instanceof Set)return p.set;if(typeof Date!=="undefined"&&W instanceof Date)return p.date;return p.object;default:return p.unknown}},Z=A0.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"]);class XW extends Error{get errors(){return this.issues}constructor(W){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=W}format(W){let $=W||function(J){return J.message},X={_errors:[]},Y=(J)=>{for(let G of J.issues)if(G.code==="invalid_union")G.unionErrors.map(Y);else if(G.code==="invalid_return_type")Y(G.returnTypeError);else if(G.code==="invalid_arguments")Y(G.argumentsError);else if(G.path.length===0)X._errors.push($(G));else{let H=X,Q=0;while(Q<G.path.length){let z=G.path[Q];if(Q!==G.path.length-1)H[z]=H[z]||{_errors:[]};else H[z]=H[z]||{_errors:[]},H[z]._errors.push($(G));H=H[z],Q++}}};return Y(this),X}static assert(W){if(!(W instanceof XW))throw new Error(`Not a ZodError: ${W}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,A0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(W=($)=>$.message){let $={},X=[];for(let Y of this.issues)if(Y.path.length>0)$[Y.path[0]]=$[Y.path[0]]||[],$[Y.path[0]].push(W(Y));else X.push(W(Y));return{formErrors:X,fieldErrors:$}}get formErrors(){return this.flatten()}}XW.create=(W)=>{return new XW(W)};var $4=(W,$)=>{let X;switch(W.code){case Z.invalid_type:if(W.received===p.undefined)X="Required";else X=`Expected ${W.expected}, received ${W.received}`;break;case Z.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify(W.expected,A0.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:X=`Unrecognized key(s) in object: ${A0.joinValues(W.keys,", ")}`;break;case Z.invalid_union:X="Invalid input";break;case Z.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${A0.joinValues(W.options)}`;break;case Z.invalid_enum_value:X=`Invalid enum value. Expected ${A0.joinValues(W.options)}, received '${W.received}'`;break;case Z.invalid_arguments:X="Invalid function arguments";break;case Z.invalid_return_type:X="Invalid function return type";break;case Z.invalid_date:X="Invalid date";break;case Z.invalid_string:if(typeof W.validation==="object")if("includes"in W.validation){if(X=`Invalid input: must include "${W.validation.includes}"`,typeof W.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${W.validation.position}`}else if("startsWith"in W.validation)X=`Invalid input: must start with "${W.validation.startsWith}"`;else if("endsWith"in W.validation)X=`Invalid input: must end with "${W.validation.endsWith}"`;else A0.assertNever(W.validation);else if(W.validation!=="regex")X=`Invalid ${W.validation}`;else X="Invalid";break;case Z.too_small:if(W.type==="array")X=`Array must contain ${W.exact?"exactly":W.inclusive?"at least":"more than"} ${W.minimum} element(s)`;else if(W.type==="string")X=`String must contain ${W.exact?"exactly":W.inclusive?"at least":"over"} ${W.minimum} character(s)`;else if(W.type==="number")X=`Number must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${W.minimum}`;else if(W.type==="date")X=`Date must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(W.minimum))}`;else X="Invalid input";break;case Z.too_big:if(W.type==="array")X=`Array must contain ${W.exact?"exactly":W.inclusive?"at most":"less than"} ${W.maximum} element(s)`;else if(W.type==="string")X=`String must contain ${W.exact?"exactly":W.inclusive?"at most":"under"} ${W.maximum} character(s)`;else if(W.type==="number")X=`Number must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="bigint")X=`BigInt must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="date")X=`Date must be ${W.exact?"exactly":W.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(W.maximum))}`;else X="Invalid input";break;case Z.custom:X="Invalid input";break;case Z.invalid_intersection_types:X="Intersection results could not be merged";break;case Z.not_multiple_of:X=`Number must be a multiple of ${W.multipleOf}`;break;case Z.not_finite:X="Number must be finite";break;default:X=$.defaultError,A0.assertNever(W)}return{message:X}},gD=$4;function h9(){return gD}var g9=(W)=>{let{data:$,path:X,errorMaps:Y,issueData:J}=W,G=[...X,...J.path||[]],H={...J,path:G};if(J.message!==void 0)return{...J,path:G,message:J.message};let Q="",z=Y.filter((F)=>!!F).slice().reverse();for(let F of z)Q=F(H,{data:$,defaultError:Q}).message;return{...J,path:G,message:Q}};function b(W,$){let X=h9(),Y=g9({issueData:$,data:W.data,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,X,X===$4?void 0:$4].filter((J)=>!!J)});W.common.issues.push(Y)}class q1{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(W,$){let X=[];for(let Y of $){if(Y.status==="aborted")return $0;if(Y.status==="dirty")W.dirty();X.push(Y.value)}return{status:W.value,value:X}}static async mergeObjectAsync(W,$){let X=[];for(let Y of $){let J=await Y.key,G=await Y.value;X.push({key:J,value:G})}return q1.mergeObjectSync(W,X)}static mergeObjectSync(W,$){let X={};for(let Y of $){let{key:J,value:G}=Y;if(J.status==="aborted")return $0;if(G.status==="aborted")return $0;if(J.status==="dirty")W.dirty();if(G.status==="dirty")W.dirty();if(J.value!=="__proto__"&&(typeof G.value!=="undefined"||Y.alwaysSet))X[J.value]=G.value}return{status:W.value,value:X}}}var $0=Object.freeze({status:"aborted"}),a$=(W)=>({status:"dirty",value:W}),v1=(W)=>({status:"valid",value:W}),cG=(W)=>W.status==="aborted",dG=(W)=>W.status==="dirty",y8=(W)=>W.status==="valid",TX=(W)=>typeof Promise!=="undefined"&&W instanceof Promise;function UX(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)}function oG(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X}var l;(function(W){W.errToObj=($)=>typeof $==="string"?{message:$}:$||{},W.toString=($)=>typeof $==="string"?$:$===null||$===void 0?void 0:$.message})(l||(l={}));var s$,e$;class OW{constructor(W,$,X,Y){this._cachedPath=[],this.parent=W,this.data=$,this._path=X,this._key=Y}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 lG=(W,$)=>{if(y8($))return{success:!0,data:$.value};else{if(!W.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new XW(W.common.issues);return this._error=X,this._error}}}};function Q0(W){if(!W)return{};let{errorMap:$,invalid_type_error:X,required_error:Y,description:J}=W;if($&&(X||Y))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:J};return{errorMap:(H,Q)=>{var z,F;let{message:T}=W;if(H.code==="invalid_enum_value")return{message:T!==null&&T!==void 0?T:Q.defaultError};if(typeof Q.data==="undefined")return{message:(z=T!==null&&T!==void 0?T:Y)!==null&&z!==void 0?z:Q.defaultError};if(H.code!=="invalid_type")return{message:Q.defaultError};return{message:(F=T!==null&&T!==void 0?T:X)!==null&&F!==void 0?F:Q.defaultError}},description:J}}class U0{get description(){return this._def.description}_getType(W){return L2(W.data)}_getOrReturnCtx(W,$){return $||{common:W.parent.common,data:W.data,parsedType:L2(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}_processInputParams(W){return{status:new q1,ctx:{common:W.parent.common,data:W.data,parsedType:L2(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}}_parseSync(W){let $=this._parse(W);if(TX($))throw new Error("Synchronous parse encountered promise.");return $}_parseAsync(W){let $=this._parse(W);return Promise.resolve($)}parse(W,$){let X=this.safeParse(W,$);if(X.success)return X.data;throw X.error}safeParse(W,$){var X;let Y={common:{issues:[],async:(X=$===null||$===void 0?void 0:$.async)!==null&&X!==void 0?X:!1,contextualErrorMap:$===null||$===void 0?void 0:$.errorMap},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:L2(W)},J=this._parseSync({data:W,path:Y.path,parent:Y});return lG(Y,J)}"~validate"(W){var $,X;let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:L2(W)};if(!this["~standard"].async)try{let J=this._parseSync({data:W,path:[],parent:Y});return y8(J)?{value:J.value}:{issues:Y.common.issues}}catch(J){if((X=($=J===null||J===void 0?void 0:J.message)===null||$===void 0?void 0:$.toLowerCase())===null||X===void 0?void 0:X.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:W,path:[],parent:Y}).then((J)=>y8(J)?{value:J.value}:{issues:Y.common.issues})}async parseAsync(W,$){let X=await this.safeParseAsync(W,$);if(X.success)return X.data;throw X.error}async safeParseAsync(W,$){let X={common:{issues:[],contextualErrorMap:$===null||$===void 0?void 0:$.errorMap,async:!0},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:L2(W)},Y=this._parse({data:W,path:X.path,parent:X}),J=await(TX(Y)?Y:Promise.resolve(Y));return lG(X,J)}refine(W,$){let X=(Y)=>{if(typeof $==="string"||typeof $==="undefined")return{message:$};else if(typeof $==="function")return $(Y);else return $};return this._refinement((Y,J)=>{let G=W(Y),H=()=>J.addIssue({code:Z.custom,...X(Y)});if(typeof Promise!=="undefined"&&G instanceof Promise)return G.then((Q)=>{if(!Q)return H(),!1;else return!0});if(!G)return H(),!1;else return!0})}refinement(W,$){return this._refinement((X,Y)=>{if(!W(X))return Y.addIssue(typeof $==="function"?$(X,Y):$),!1;else return!0})}_refinement(W){return new vW({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:W}})}superRefine(W){return this._refinement(W)}constructor(W){this.spa=this.safeParseAsync,this._def=W,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return YW.create(this,this._def)}nullable(){return B2.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xW.create(this)}promise(){return p8.create(this,this._def)}or(W){return G4.create([this,W],this._def)}and(W){return H4.create(this,W,this._def)}transform(W){return new vW({...Q0(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:W}})}default(W){let $=typeof W==="function"?W:()=>W;return new T4({...Q0(this._def),innerType:this,defaultValue:$,typeName:S.ZodDefault})}brand(){return new u9({typeName:S.ZodBranded,type:this,...Q0(this._def)})}catch(W){let $=typeof W==="function"?W:()=>W;return new U4({...Q0(this._def),innerType:this,catchValue:$,typeName:S.ZodCatch})}describe(W){return new this.constructor({...this._def,description:W})}pipe(W){return AX.create(this,W)}readonly(){return w4.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var mD=/^c[^\s-]{8,}$/i,pD=/^[0-9a-z]+$/,uD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cD=/^[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,dD=/^[a-z0-9_-]{21}$/i,lD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oD=/^[-+]?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)?)??$/,iD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y9,rD=/^(?:(?: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])$/,tD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,aD=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sD=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,eD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,WM=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,iG="((\\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])))",$M=new RegExp(`^${iG}$`);function nG(W){let $="[0-5]\\d";if(W.precision)$=`${$}\\.\\d{${W.precision}}`;else if(W.precision==null)$=`${$}(\\.\\d+)?`;let X=W.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${X}`}function XM(W){return new RegExp(`^${nG(W)}$`)}function YM(W){let $=`${iG}T${nG(W)}`,X=[];if(X.push(W.local?"Z?":"Z"),W.offset)X.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${X.join("|")})`,new RegExp(`^${$}$`)}function JM(W,$){if(($==="v4"||!$)&&rD.test(W))return!0;if(($==="v6"||!$)&&aD.test(W))return!0;return!1}function GM(W,$){if(!lD.test(W))return!1;try{let[X]=W.split("."),Y=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),J=JSON.parse(atob(Y));if(typeof J!=="object"||J===null)return!1;if(!J.typ||!J.alg)return!1;if($&&J.alg!==$)return!1;return!0}catch(X){return!1}}function HM(W,$){if(($==="v4"||!$)&&tD.test(W))return!0;if(($==="v6"||!$)&&sD.test(W))return!0;return!1}class oW extends U0{_parse(W){if(this._def.coerce)W.data=String(W.data);if(this._getType(W)!==p.string){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_type,expected:p.string,received:J.parsedType}),$0}let X=new q1,Y=void 0;for(let J of this._def.checks)if(J.kind==="min"){if(W.data.length<J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="max"){if(W.data.length>J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="length"){let G=W.data.length>J.value,H=W.data.length<J.value;if(G||H){if(Y=this._getOrReturnCtx(W,Y),G)b(Y,{code:Z.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(H)b(Y,{code:Z.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});X.dirty()}}else if(J.kind==="email"){if(!iD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"email",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="emoji"){if(!y9)y9=new RegExp(nD,"u");if(!y9.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"emoji",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="uuid"){if(!cD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"uuid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="nanoid"){if(!dD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"nanoid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cuid"){if(!mD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"cuid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cuid2"){if(!pD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"cuid2",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="ulid"){if(!uD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"ulid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="url")try{new URL(W.data)}catch(G){Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"url",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"regex",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="trim")W.data=W.data.trim();else if(J.kind==="includes"){if(!W.data.includes(J.value,J.position))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),X.dirty()}else if(J.kind==="toLowerCase")W.data=W.data.toLowerCase();else if(J.kind==="toUpperCase")W.data=W.data.toUpperCase();else if(J.kind==="startsWith"){if(!W.data.startsWith(J.value))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:{startsWith:J.value},message:J.message}),X.dirty()}else if(J.kind==="endsWith"){if(!W.data.endsWith(J.value))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:{endsWith:J.value},message:J.message}),X.dirty()}else if(J.kind==="datetime"){if(!YM(J).test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:"datetime",message:J.message}),X.dirty()}else if(J.kind==="date"){if(!$M.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:"date",message:J.message}),X.dirty()}else if(J.kind==="time"){if(!XM(J).test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:"time",message:J.message}),X.dirty()}else if(J.kind==="duration"){if(!oD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"duration",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="ip"){if(!JM(W.data,J.version))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"ip",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="jwt"){if(!GM(W.data,J.alg))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"jwt",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cidr"){if(!HM(W.data,J.version))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"cidr",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="base64"){if(!eD.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"base64",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="base64url"){if(!WM.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"base64url",code:Z.invalid_string,message:J.message}),X.dirty()}else A0.assertNever(J);return{status:X.value,value:W.data}}_regex(W,$,X){return this.refinement((Y)=>W.test(Y),{validation:$,code:Z.invalid_string,...l.errToObj(X)})}_addCheck(W){return new oW({...this._def,checks:[...this._def.checks,W]})}email(W){return this._addCheck({kind:"email",...l.errToObj(W)})}url(W){return this._addCheck({kind:"url",...l.errToObj(W)})}emoji(W){return this._addCheck({kind:"emoji",...l.errToObj(W)})}uuid(W){return this._addCheck({kind:"uuid",...l.errToObj(W)})}nanoid(W){return this._addCheck({kind:"nanoid",...l.errToObj(W)})}cuid(W){return this._addCheck({kind:"cuid",...l.errToObj(W)})}cuid2(W){return this._addCheck({kind:"cuid2",...l.errToObj(W)})}ulid(W){return this._addCheck({kind:"ulid",...l.errToObj(W)})}base64(W){return this._addCheck({kind:"base64",...l.errToObj(W)})}base64url(W){return this._addCheck({kind:"base64url",...l.errToObj(W)})}jwt(W){return this._addCheck({kind:"jwt",...l.errToObj(W)})}ip(W){return this._addCheck({kind:"ip",...l.errToObj(W)})}cidr(W){return this._addCheck({kind:"cidr",...l.errToObj(W)})}datetime(W){var $,X;if(typeof W==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:W});return this._addCheck({kind:"datetime",precision:typeof(W===null||W===void 0?void 0:W.precision)==="undefined"?null:W===null||W===void 0?void 0:W.precision,offset:($=W===null||W===void 0?void 0:W.offset)!==null&&$!==void 0?$:!1,local:(X=W===null||W===void 0?void 0:W.local)!==null&&X!==void 0?X:!1,...l.errToObj(W===null||W===void 0?void 0:W.message)})}date(W){return this._addCheck({kind:"date",message:W})}time(W){if(typeof W==="string")return this._addCheck({kind:"time",precision:null,message:W});return this._addCheck({kind:"time",precision:typeof(W===null||W===void 0?void 0:W.precision)==="undefined"?null:W===null||W===void 0?void 0:W.precision,...l.errToObj(W===null||W===void 0?void 0:W.message)})}duration(W){return this._addCheck({kind:"duration",...l.errToObj(W)})}regex(W,$){return this._addCheck({kind:"regex",regex:W,...l.errToObj($)})}includes(W,$){return this._addCheck({kind:"includes",value:W,position:$===null||$===void 0?void 0:$.position,...l.errToObj($===null||$===void 0?void 0:$.message)})}startsWith(W,$){return this._addCheck({kind:"startsWith",value:W,...l.errToObj($)})}endsWith(W,$){return this._addCheck({kind:"endsWith",value:W,...l.errToObj($)})}min(W,$){return this._addCheck({kind:"min",value:W,...l.errToObj($)})}max(W,$){return this._addCheck({kind:"max",value:W,...l.errToObj($)})}length(W,$){return this._addCheck({kind:"length",value:W,...l.errToObj($)})}nonempty(W){return this.min(1,l.errToObj(W))}trim(){return new oW({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new oW({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new oW({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((W)=>W.kind==="datetime")}get isDate(){return!!this._def.checks.find((W)=>W.kind==="date")}get isTime(){return!!this._def.checks.find((W)=>W.kind==="time")}get isDuration(){return!!this._def.checks.find((W)=>W.kind==="duration")}get isEmail(){return!!this._def.checks.find((W)=>W.kind==="email")}get isURL(){return!!this._def.checks.find((W)=>W.kind==="url")}get isEmoji(){return!!this._def.checks.find((W)=>W.kind==="emoji")}get isUUID(){return!!this._def.checks.find((W)=>W.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((W)=>W.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((W)=>W.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((W)=>W.kind==="cuid2")}get isULID(){return!!this._def.checks.find((W)=>W.kind==="ulid")}get isIP(){return!!this._def.checks.find((W)=>W.kind==="ip")}get isCIDR(){return!!this._def.checks.find((W)=>W.kind==="cidr")}get isBase64(){return!!this._def.checks.find((W)=>W.kind==="base64")}get isBase64url(){return!!this._def.checks.find((W)=>W.kind==="base64url")}get minLength(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxLength(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}}oW.create=(W)=>{var $;return new oW({checks:[],typeName:S.ZodString,coerce:($=W===null||W===void 0?void 0:W.coerce)!==null&&$!==void 0?$:!1,...Q0(W)})};function QM(W,$){let X=(W.toString().split(".")[1]||"").length,Y=($.toString().split(".")[1]||"").length,J=X>Y?X:Y,G=parseInt(W.toFixed(J).replace(".","")),H=parseInt($.toFixed(J).replace(".",""));return G%H/Math.pow(10,J)}class h8 extends U0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(W){if(this._def.coerce)W.data=Number(W.data);if(this._getType(W)!==p.number){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_type,expected:p.number,received:J.parsedType}),$0}let X=void 0,Y=new q1;for(let J of this._def.checks)if(J.kind==="int"){if(!A0.isInteger(W.data))X=this._getOrReturnCtx(W,X),b(X,{code:Z.invalid_type,expected:"integer",received:"float",message:J.message}),Y.dirty()}else if(J.kind==="min"){if(J.inclusive?W.data<J.value:W.data<=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),Y.dirty()}else if(J.kind==="max"){if(J.inclusive?W.data>J.value:W.data>=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),Y.dirty()}else if(J.kind==="multipleOf"){if(QM(W.data,J.value)!==0)X=this._getOrReturnCtx(W,X),b(X,{code:Z.not_multiple_of,multipleOf:J.value,message:J.message}),Y.dirty()}else if(J.kind==="finite"){if(!Number.isFinite(W.data))X=this._getOrReturnCtx(W,X),b(X,{code:Z.not_finite,message:J.message}),Y.dirty()}else A0.assertNever(J);return{status:Y.value,value:W.data}}gte(W,$){return this.setLimit("min",W,!0,l.toString($))}gt(W,$){return this.setLimit("min",W,!1,l.toString($))}lte(W,$){return this.setLimit("max",W,!0,l.toString($))}lt(W,$){return this.setLimit("max",W,!1,l.toString($))}setLimit(W,$,X,Y){return new h8({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:X,message:l.toString(Y)}]})}_addCheck(W){return new h8({...this._def,checks:[...this._def.checks,W]})}int(W){return this._addCheck({kind:"int",message:l.toString(W)})}positive(W){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(W)})}negative(W){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(W)})}nonpositive(W){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(W)})}nonnegative(W){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(W)})}multipleOf(W,$){return this._addCheck({kind:"multipleOf",value:W,message:l.toString($)})}finite(W){return this._addCheck({kind:"finite",message:l.toString(W)})}safe(W){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(W)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(W)})}get minValue(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxValue(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}get isInt(){return!!this._def.checks.find((W)=>W.kind==="int"||W.kind==="multipleOf"&&A0.isInteger(W.value))}get isFinite(){let W=null,$=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if($===null||X.value>$)$=X.value}else if(X.kind==="max"){if(W===null||X.value<W)W=X.value}return Number.isFinite($)&&Number.isFinite(W)}}h8.create=(W)=>{return new h8({checks:[],typeName:S.ZodNumber,coerce:(W===null||W===void 0?void 0:W.coerce)||!1,...Q0(W)})};class g8 extends U0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(W){if(this._def.coerce)try{W.data=BigInt(W.data)}catch(J){return this._getInvalidInput(W)}if(this._getType(W)!==p.bigint)return this._getInvalidInput(W);let X=void 0,Y=new q1;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?W.data<J.value:W.data<=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),Y.dirty()}else if(J.kind==="max"){if(J.inclusive?W.data>J.value:W.data>=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),Y.dirty()}else if(J.kind==="multipleOf"){if(W.data%J.value!==BigInt(0))X=this._getOrReturnCtx(W,X),b(X,{code:Z.not_multiple_of,multipleOf:J.value,message:J.message}),Y.dirty()}else A0.assertNever(J);return{status:Y.value,value:W.data}}_getInvalidInput(W){let $=this._getOrReturnCtx(W);return b($,{code:Z.invalid_type,expected:p.bigint,received:$.parsedType}),$0}gte(W,$){return this.setLimit("min",W,!0,l.toString($))}gt(W,$){return this.setLimit("min",W,!1,l.toString($))}lte(W,$){return this.setLimit("max",W,!0,l.toString($))}lt(W,$){return this.setLimit("max",W,!1,l.toString($))}setLimit(W,$,X,Y){return new g8({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:X,message:l.toString(Y)}]})}_addCheck(W){return new g8({...this._def,checks:[...this._def.checks,W]})}positive(W){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(W)})}negative(W){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(W)})}nonpositive(W){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(W)})}nonnegative(W){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(W)})}multipleOf(W,$){return this._addCheck({kind:"multipleOf",value:W,message:l.toString($)})}get minValue(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxValue(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}}g8.create=(W)=>{var $;return new g8({checks:[],typeName:S.ZodBigInt,coerce:($=W===null||W===void 0?void 0:W.coerce)!==null&&$!==void 0?$:!1,...Q0(W)})};class wX extends U0{_parse(W){if(this._def.coerce)W.data=Boolean(W.data);if(this._getType(W)!==p.boolean){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.boolean,received:X.parsedType}),$0}return v1(W.data)}}wX.create=(W)=>{return new wX({typeName:S.ZodBoolean,coerce:(W===null||W===void 0?void 0:W.coerce)||!1,...Q0(W)})};class X4 extends U0{_parse(W){if(this._def.coerce)W.data=new Date(W.data);if(this._getType(W)!==p.date){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_type,expected:p.date,received:J.parsedType}),$0}if(isNaN(W.data.getTime())){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_date}),$0}let X=new q1,Y=void 0;for(let J of this._def.checks)if(J.kind==="min"){if(W.data.getTime()<J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),X.dirty()}else if(J.kind==="max"){if(W.data.getTime()>J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),X.dirty()}else A0.assertNever(J);return{status:X.value,value:new Date(W.data.getTime())}}_addCheck(W){return new X4({...this._def,checks:[...this._def.checks,W]})}min(W,$){return this._addCheck({kind:"min",value:W.getTime(),message:l.toString($)})}max(W,$){return this._addCheck({kind:"max",value:W.getTime(),message:l.toString($)})}get minDate(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W!=null?new Date(W):null}get maxDate(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W!=null?new Date(W):null}}X4.create=(W)=>{return new X4({checks:[],coerce:(W===null||W===void 0?void 0:W.coerce)||!1,typeName:S.ZodDate,...Q0(W)})};class _X extends U0{_parse(W){if(this._getType(W)!==p.symbol){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.symbol,received:X.parsedType}),$0}return v1(W.data)}}_X.create=(W)=>{return new _X({typeName:S.ZodSymbol,...Q0(W)})};class Y4 extends U0{_parse(W){if(this._getType(W)!==p.undefined){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.undefined,received:X.parsedType}),$0}return v1(W.data)}}Y4.create=(W)=>{return new Y4({typeName:S.ZodUndefined,...Q0(W)})};class J4 extends U0{_parse(W){if(this._getType(W)!==p.null){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.null,received:X.parsedType}),$0}return v1(W.data)}}J4.create=(W)=>{return new J4({typeName:S.ZodNull,...Q0(W)})};class DX extends U0{constructor(){super(...arguments);this._any=!0}_parse(W){return v1(W.data)}}DX.create=(W)=>{return new DX({typeName:S.ZodAny,...Q0(W)})};class l2 extends U0{constructor(){super(...arguments);this._unknown=!0}_parse(W){return v1(W.data)}}l2.create=(W)=>{return new l2({typeName:S.ZodUnknown,...Q0(W)})};class iW extends U0{_parse(W){let $=this._getOrReturnCtx(W);return b($,{code:Z.invalid_type,expected:p.never,received:$.parsedType}),$0}}iW.create=(W)=>{return new iW({typeName:S.ZodNever,...Q0(W)})};class MX extends U0{_parse(W){if(this._getType(W)!==p.undefined){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.void,received:X.parsedType}),$0}return v1(W.data)}}MX.create=(W)=>{return new MX({typeName:S.ZodVoid,...Q0(W)})};class xW extends U0{_parse(W){let{ctx:$,status:X}=this._processInputParams(W),Y=this._def;if($.parsedType!==p.array)return b($,{code:Z.invalid_type,expected:p.array,received:$.parsedType}),$0;if(Y.exactLength!==null){let G=$.data.length>Y.exactLength.value,H=$.data.length<Y.exactLength.value;if(G||H)b($,{code:G?Z.too_big:Z.too_small,minimum:H?Y.exactLength.value:void 0,maximum:G?Y.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Y.exactLength.message}),X.dirty()}if(Y.minLength!==null){if($.data.length<Y.minLength.value)b($,{code:Z.too_small,minimum:Y.minLength.value,type:"array",inclusive:!0,exact:!1,message:Y.minLength.message}),X.dirty()}if(Y.maxLength!==null){if($.data.length>Y.maxLength.value)b($,{code:Z.too_big,maximum:Y.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Y.maxLength.message}),X.dirty()}if($.common.async)return Promise.all([...$.data].map((G,H)=>{return Y.type._parseAsync(new OW($,G,$.path,H))})).then((G)=>{return q1.mergeArray(X,G)});let J=[...$.data].map((G,H)=>{return Y.type._parseSync(new OW($,G,$.path,H))});return q1.mergeArray(X,J)}get element(){return this._def.type}min(W,$){return new xW({...this._def,minLength:{value:W,message:l.toString($)}})}max(W,$){return new xW({...this._def,maxLength:{value:W,message:l.toString($)}})}length(W,$){return new xW({...this._def,exactLength:{value:W,message:l.toString($)}})}nonempty(W){return this.min(1,W)}}xW.create=(W,$)=>{return new xW({type:W,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...Q0($)})};function b8(W){if(W instanceof o0){let $={};for(let X in W.shape){let Y=W.shape[X];$[X]=YW.create(b8(Y))}return new o0({...W._def,shape:()=>$})}else if(W instanceof xW)return new xW({...W._def,type:b8(W.element)});else if(W instanceof YW)return YW.create(b8(W.unwrap()));else if(W instanceof B2)return B2.create(b8(W.unwrap()));else if(W instanceof nW)return nW.create(W.items.map(($)=>b8($)));else return W}class o0 extends U0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let W=this._def.shape(),$=A0.objectKeys(W);return this._cached={shape:W,keys:$}}_parse(W){if(this._getType(W)!==p.object){let z=this._getOrReturnCtx(W);return b(z,{code:Z.invalid_type,expected:p.object,received:z.parsedType}),$0}let{status:X,ctx:Y}=this._processInputParams(W),{shape:J,keys:G}=this._getCached(),H=[];if(!(this._def.catchall instanceof iW&&this._def.unknownKeys==="strip")){for(let z in Y.data)if(!G.includes(z))H.push(z)}let Q=[];for(let z of G){let F=J[z],T=Y.data[z];Q.push({key:{status:"valid",value:z},value:F._parse(new OW(Y,T,Y.path,z)),alwaysSet:z in Y.data})}if(this._def.catchall instanceof iW){let z=this._def.unknownKeys;if(z==="passthrough")for(let F of H)Q.push({key:{status:"valid",value:F},value:{status:"valid",value:Y.data[F]}});else if(z==="strict"){if(H.length>0)b(Y,{code:Z.unrecognized_keys,keys:H}),X.dirty()}else if(z==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let z=this._def.catchall;for(let F of H){let T=Y.data[F];Q.push({key:{status:"valid",value:F},value:z._parse(new OW(Y,T,Y.path,F)),alwaysSet:F in Y.data})}}if(Y.common.async)return Promise.resolve().then(async()=>{let z=[];for(let F of Q){let T=await F.key,U=await F.value;z.push({key:T,value:U,alwaysSet:F.alwaysSet})}return z}).then((z)=>{return q1.mergeObjectSync(X,z)});else return q1.mergeObjectSync(X,Q)}get shape(){return this._def.shape()}strict(W){return l.errToObj,new o0({...this._def,unknownKeys:"strict",...W!==void 0?{errorMap:($,X)=>{var Y,J,G,H;let Q=(G=(J=(Y=this._def).errorMap)===null||J===void 0?void 0:J.call(Y,$,X).message)!==null&&G!==void 0?G:X.defaultError;if($.code==="unrecognized_keys")return{message:(H=l.errToObj(W).message)!==null&&H!==void 0?H:Q};return{message:Q}}}:{}})}strip(){return new o0({...this._def,unknownKeys:"strip"})}passthrough(){return new o0({...this._def,unknownKeys:"passthrough"})}extend(W){return new o0({...this._def,shape:()=>({...this._def.shape(),...W})})}merge(W){return new o0({unknownKeys:W._def.unknownKeys,catchall:W._def.catchall,shape:()=>({...this._def.shape(),...W._def.shape()}),typeName:S.ZodObject})}setKey(W,$){return this.augment({[W]:$})}catchall(W){return new o0({...this._def,catchall:W})}pick(W){let $={};return A0.objectKeys(W).forEach((X)=>{if(W[X]&&this.shape[X])$[X]=this.shape[X]}),new o0({...this._def,shape:()=>$})}omit(W){let $={};return A0.objectKeys(this.shape).forEach((X)=>{if(!W[X])$[X]=this.shape[X]}),new o0({...this._def,shape:()=>$})}deepPartial(){return b8(this)}partial(W){let $={};return A0.objectKeys(this.shape).forEach((X)=>{let Y=this.shape[X];if(W&&!W[X])$[X]=Y;else $[X]=Y.optional()}),new o0({...this._def,shape:()=>$})}required(W){let $={};return A0.objectKeys(this.shape).forEach((X)=>{if(W&&!W[X])$[X]=this.shape[X];else{let J=this.shape[X];while(J instanceof YW)J=J._def.innerType;$[X]=J}}),new o0({...this._def,shape:()=>$})}keyof(){return rG(A0.objectKeys(this.shape))}}o0.create=(W,$)=>{return new o0({shape:()=>W,unknownKeys:"strip",catchall:iW.create(),typeName:S.ZodObject,...Q0($)})};o0.strictCreate=(W,$)=>{return new o0({shape:()=>W,unknownKeys:"strict",catchall:iW.create(),typeName:S.ZodObject,...Q0($)})};o0.lazycreate=(W,$)=>{return new o0({shape:W,unknownKeys:"strip",catchall:iW.create(),typeName:S.ZodObject,...Q0($)})};class G4 extends U0{_parse(W){let{ctx:$}=this._processInputParams(W),X=this._def.options;function Y(J){for(let H of J)if(H.result.status==="valid")return H.result;for(let H of J)if(H.result.status==="dirty")return $.common.issues.push(...H.ctx.common.issues),H.result;let G=J.map((H)=>new XW(H.ctx.common.issues));return b($,{code:Z.invalid_union,unionErrors:G}),$0}if($.common.async)return Promise.all(X.map(async(J)=>{let G={...$,common:{...$.common,issues:[]},parent:null};return{result:await J._parseAsync({data:$.data,path:$.path,parent:G}),ctx:G}})).then(Y);else{let J=void 0,G=[];for(let Q of X){let z={...$,common:{...$.common,issues:[]},parent:null},F=Q._parseSync({data:$.data,path:$.path,parent:z});if(F.status==="valid")return F;else if(F.status==="dirty"&&!J)J={result:F,ctx:z};if(z.common.issues.length)G.push(z.common.issues)}if(J)return $.common.issues.push(...J.ctx.common.issues),J.result;let H=G.map((Q)=>new XW(Q));return b($,{code:Z.invalid_union,unionErrors:H}),$0}}get options(){return this._def.options}}G4.create=(W,$)=>{return new G4({options:W,typeName:S.ZodUnion,...Q0($)})};var lW=(W)=>{if(W instanceof Q4)return lW(W.schema);else if(W instanceof vW)return lW(W.innerType());else if(W instanceof z4)return[W.value];else if(W instanceof o2)return W.options;else if(W instanceof F4)return A0.objectValues(W.enum);else if(W instanceof T4)return lW(W._def.innerType);else if(W instanceof Y4)return[void 0];else if(W instanceof J4)return[null];else if(W instanceof YW)return[void 0,...lW(W.unwrap())];else if(W instanceof B2)return[null,...lW(W.unwrap())];else if(W instanceof u9)return lW(W.unwrap());else if(W instanceof w4)return lW(W.unwrap());else if(W instanceof U4)return lW(W._def.innerType);else return[]};class p9 extends U0{_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==p.object)return b($,{code:Z.invalid_type,expected:p.object,received:$.parsedType}),$0;let X=this.discriminator,Y=$.data[X],J=this.optionsMap.get(Y);if(!J)return b($,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),$0;if($.common.async)return J._parseAsync({data:$.data,path:$.path,parent:$});else return J._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(W,$,X){let Y=new Map;for(let J of $){let G=lW(J.shape[W]);if(!G.length)throw new Error(`A discriminator value for key \`${W}\` could not be extracted from all schema options`);for(let H of G){if(Y.has(H))throw new Error(`Discriminator property ${String(W)} has duplicate value ${String(H)}`);Y.set(H,J)}}return new p9({typeName:S.ZodDiscriminatedUnion,discriminator:W,options:$,optionsMap:Y,...Q0(X)})}}function m9(W,$){let X=L2(W),Y=L2($);if(W===$)return{valid:!0,data:W};else if(X===p.object&&Y===p.object){let J=A0.objectKeys($),G=A0.objectKeys(W).filter((Q)=>J.indexOf(Q)!==-1),H={...W,...$};for(let Q of G){let z=m9(W[Q],$[Q]);if(!z.valid)return{valid:!1};H[Q]=z.data}return{valid:!0,data:H}}else if(X===p.array&&Y===p.array){if(W.length!==$.length)return{valid:!1};let J=[];for(let G=0;G<W.length;G++){let H=W[G],Q=$[G],z=m9(H,Q);if(!z.valid)return{valid:!1};J.push(z.data)}return{valid:!0,data:J}}else if(X===p.date&&Y===p.date&&+W===+$)return{valid:!0,data:W};else return{valid:!1}}class H4 extends U0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W),Y=(J,G)=>{if(cG(J)||cG(G))return $0;let H=m9(J.value,G.value);if(!H.valid)return b(X,{code:Z.invalid_intersection_types}),$0;if(dG(J)||dG(G))$.dirty();return{status:$.value,value:H.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([J,G])=>Y(J,G));else return Y(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}H4.create=(W,$,X)=>{return new H4({left:W,right:$,typeName:S.ZodIntersection,...Q0(X)})};class nW extends U0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.array)return b(X,{code:Z.invalid_type,expected:p.array,received:X.parsedType}),$0;if(X.data.length<this._def.items.length)return b(X,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$0;if(!this._def.rest&&X.data.length>this._def.items.length)b(X,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let J=[...X.data].map((G,H)=>{let Q=this._def.items[H]||this._def.rest;if(!Q)return null;return Q._parse(new OW(X,G,X.path,H))}).filter((G)=>!!G);if(X.common.async)return Promise.all(J).then((G)=>{return q1.mergeArray($,G)});else return q1.mergeArray($,J)}get items(){return this._def.items}rest(W){return new nW({...this._def,rest:W})}}nW.create=(W,$)=>{if(!Array.isArray(W))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nW({items:W,typeName:S.ZodTuple,rest:null,...Q0($)})};class VX extends U0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.object)return b(X,{code:Z.invalid_type,expected:p.object,received:X.parsedType}),$0;let Y=[],J=this._def.keyType,G=this._def.valueType;for(let H in X.data)Y.push({key:J._parse(new OW(X,H,X.path,H)),value:G._parse(new OW(X,X.data[H],X.path,H)),alwaysSet:H in X.data});if(X.common.async)return q1.mergeObjectAsync($,Y);else return q1.mergeObjectSync($,Y)}get element(){return this._def.valueType}static create(W,$,X){if($ instanceof U0)return new VX({keyType:W,valueType:$,typeName:S.ZodRecord,...Q0(X)});return new VX({keyType:oW.create(),valueType:W,typeName:S.ZodRecord,...Q0($)})}}class OX extends U0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.map)return b(X,{code:Z.invalid_type,expected:p.map,received:X.parsedType}),$0;let Y=this._def.keyType,J=this._def.valueType,G=[...X.data.entries()].map(([H,Q],z)=>{return{key:Y._parse(new OW(X,H,X.path,[z,"key"])),value:J._parse(new OW(X,Q,X.path,[z,"value"]))}});if(X.common.async){let H=new Map;return Promise.resolve().then(async()=>{for(let Q of G){let z=await Q.key,F=await Q.value;if(z.status==="aborted"||F.status==="aborted")return $0;if(z.status==="dirty"||F.status==="dirty")$.dirty();H.set(z.value,F.value)}return{status:$.value,value:H}})}else{let H=new Map;for(let Q of G){let{key:z,value:F}=Q;if(z.status==="aborted"||F.status==="aborted")return $0;if(z.status==="dirty"||F.status==="dirty")$.dirty();H.set(z.value,F.value)}return{status:$.value,value:H}}}}OX.create=(W,$,X)=>{return new OX({valueType:$,keyType:W,typeName:S.ZodMap,...Q0(X)})};class m8 extends U0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.set)return b(X,{code:Z.invalid_type,expected:p.set,received:X.parsedType}),$0;let Y=this._def;if(Y.minSize!==null){if(X.data.size<Y.minSize.value)b(X,{code:Z.too_small,minimum:Y.minSize.value,type:"set",inclusive:!0,exact:!1,message:Y.minSize.message}),$.dirty()}if(Y.maxSize!==null){if(X.data.size>Y.maxSize.value)b(X,{code:Z.too_big,maximum:Y.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Y.maxSize.message}),$.dirty()}let J=this._def.valueType;function G(Q){let z=new Set;for(let F of Q){if(F.status==="aborted")return $0;if(F.status==="dirty")$.dirty();z.add(F.value)}return{status:$.value,value:z}}let H=[...X.data.values()].map((Q,z)=>J._parse(new OW(X,Q,X.path,z)));if(X.common.async)return Promise.all(H).then((Q)=>G(Q));else return G(H)}min(W,$){return new m8({...this._def,minSize:{value:W,message:l.toString($)}})}max(W,$){return new m8({...this._def,maxSize:{value:W,message:l.toString($)}})}size(W,$){return this.min(W,$).max(W,$)}nonempty(W){return this.min(1,W)}}m8.create=(W,$)=>{return new m8({valueType:W,minSize:null,maxSize:null,typeName:S.ZodSet,...Q0($)})};class W4 extends U0{constructor(){super(...arguments);this.validate=this.implement}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==p.function)return b($,{code:Z.invalid_type,expected:p.function,received:$.parsedType}),$0;function X(H,Q){return g9({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,h9(),$4].filter((z)=>!!z),issueData:{code:Z.invalid_arguments,argumentsError:Q}})}function Y(H,Q){return g9({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,h9(),$4].filter((z)=>!!z),issueData:{code:Z.invalid_return_type,returnTypeError:Q}})}let J={errorMap:$.common.contextualErrorMap},G=$.data;if(this._def.returns instanceof p8){let H=this;return v1(async function(...Q){let z=new XW([]),F=await H._def.args.parseAsync(Q,J).catch((_)=>{throw z.addIssue(X(Q,_)),z}),T=await Reflect.apply(G,this,F);return await H._def.returns._def.type.parseAsync(T,J).catch((_)=>{throw z.addIssue(Y(T,_)),z})})}else{let H=this;return v1(function(...Q){let z=H._def.args.safeParse(Q,J);if(!z.success)throw new XW([X(Q,z.error)]);let F=Reflect.apply(G,this,z.data),T=H._def.returns.safeParse(F,J);if(!T.success)throw new XW([Y(F,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...W){return new W4({...this._def,args:nW.create(W).rest(l2.create())})}returns(W){return new W4({...this._def,returns:W})}implement(W){return this.parse(W)}strictImplement(W){return this.parse(W)}static create(W,$,X){return new W4({args:W?W:nW.create([]).rest(l2.create()),returns:$||l2.create(),typeName:S.ZodFunction,...Q0(X)})}}class Q4 extends U0{get schema(){return this._def.getter()}_parse(W){let{ctx:$}=this._processInputParams(W);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}Q4.create=(W,$)=>{return new Q4({getter:W,typeName:S.ZodLazy,...Q0($)})};class z4 extends U0{_parse(W){if(W.data!==this._def.value){let $=this._getOrReturnCtx(W);return b($,{received:$.data,code:Z.invalid_literal,expected:this._def.value}),$0}return{status:"valid",value:W.data}}get value(){return this._def.value}}z4.create=(W,$)=>{return new z4({value:W,typeName:S.ZodLiteral,...Q0($)})};function rG(W,$){return new o2({values:W,typeName:S.ZodEnum,...Q0($)})}class o2 extends U0{constructor(){super(...arguments);s$.set(this,void 0)}_parse(W){if(typeof W.data!=="string"){let $=this._getOrReturnCtx(W),X=this._def.values;return b($,{expected:A0.joinValues(X),received:$.parsedType,code:Z.invalid_type}),$0}if(!UX(this,s$,"f"))oG(this,s$,new Set(this._def.values),"f");if(!UX(this,s$,"f").has(W.data)){let $=this._getOrReturnCtx(W),X=this._def.values;return b($,{received:$.data,code:Z.invalid_enum_value,options:X}),$0}return v1(W.data)}get options(){return this._def.values}get enum(){let W={};for(let $ of this._def.values)W[$]=$;return W}get Values(){let W={};for(let $ of this._def.values)W[$]=$;return W}get Enum(){let W={};for(let $ of this._def.values)W[$]=$;return W}extract(W,$=this._def){return o2.create(W,{...this._def,...$})}exclude(W,$=this._def){return o2.create(this.options.filter((X)=>!W.includes(X)),{...this._def,...$})}}s$=new WeakMap;o2.create=rG;class F4 extends U0{constructor(){super(...arguments);e$.set(this,void 0)}_parse(W){let $=A0.getValidEnumValues(this._def.values),X=this._getOrReturnCtx(W);if(X.parsedType!==p.string&&X.parsedType!==p.number){let Y=A0.objectValues($);return b(X,{expected:A0.joinValues(Y),received:X.parsedType,code:Z.invalid_type}),$0}if(!UX(this,e$,"f"))oG(this,e$,new Set(A0.getValidEnumValues(this._def.values)),"f");if(!UX(this,e$,"f").has(W.data)){let Y=A0.objectValues($);return b(X,{received:X.data,code:Z.invalid_enum_value,options:Y}),$0}return v1(W.data)}get enum(){return this._def.values}}e$=new WeakMap;F4.create=(W,$)=>{return new F4({values:W,typeName:S.ZodNativeEnum,...Q0($)})};class p8 extends U0{unwrap(){return this._def.type}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==p.promise&&$.common.async===!1)return b($,{code:Z.invalid_type,expected:p.promise,received:$.parsedType}),$0;let X=$.parsedType===p.promise?$.data:Promise.resolve($.data);return v1(X.then((Y)=>{return this._def.type.parseAsync(Y,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}p8.create=(W,$)=>{return new p8({type:W,typeName:S.ZodPromise,...Q0($)})};class vW extends U0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(W){let{status:$,ctx:X}=this._processInputParams(W),Y=this._def.effect||null,J={addIssue:(G)=>{if(b(X,G),G.fatal)$.abort();else $.dirty()},get path(){return X.path}};if(J.addIssue=J.addIssue.bind(J),Y.type==="preprocess"){let G=Y.transform(X.data,J);if(X.common.async)return Promise.resolve(G).then(async(H)=>{if($.value==="aborted")return $0;let Q=await this._def.schema._parseAsync({data:H,path:X.path,parent:X});if(Q.status==="aborted")return $0;if(Q.status==="dirty")return a$(Q.value);if($.value==="dirty")return a$(Q.value);return Q});else{if($.value==="aborted")return $0;let H=this._def.schema._parseSync({data:G,path:X.path,parent:X});if(H.status==="aborted")return $0;if(H.status==="dirty")return a$(H.value);if($.value==="dirty")return a$(H.value);return H}}if(Y.type==="refinement"){let G=(H)=>{let Q=Y.refinement(H,J);if(X.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return H};if(X.common.async===!1){let H=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(H.status==="aborted")return $0;if(H.status==="dirty")$.dirty();return G(H.value),{status:$.value,value:H.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((H)=>{if(H.status==="aborted")return $0;if(H.status==="dirty")$.dirty();return G(H.value).then(()=>{return{status:$.value,value:H.value}})})}if(Y.type==="transform")if(X.common.async===!1){let G=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!y8(G))return G;let H=Y.transform(G.value,J);if(H instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:H}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((G)=>{if(!y8(G))return G;return Promise.resolve(Y.transform(G.value,J)).then((H)=>({status:$.value,value:H}))});A0.assertNever(Y)}}vW.create=(W,$,X)=>{return new vW({schema:W,typeName:S.ZodEffects,effect:$,...Q0(X)})};vW.createWithPreprocess=(W,$,X)=>{return new vW({schema:$,effect:{type:"preprocess",transform:W},typeName:S.ZodEffects,...Q0(X)})};class YW extends U0{_parse(W){if(this._getType(W)===p.undefined)return v1(void 0);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}YW.create=(W,$)=>{return new YW({innerType:W,typeName:S.ZodOptional,...Q0($)})};class B2 extends U0{_parse(W){if(this._getType(W)===p.null)return v1(null);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}B2.create=(W,$)=>{return new B2({innerType:W,typeName:S.ZodNullable,...Q0($)})};class T4 extends U0{_parse(W){let{ctx:$}=this._processInputParams(W),X=$.data;if($.parsedType===p.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}T4.create=(W,$)=>{return new T4({innerType:W,typeName:S.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...Q0($)})};class U4 extends U0{_parse(W){let{ctx:$}=this._processInputParams(W),X={...$,common:{...$.common,issues:[]}},Y=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(TX(Y))return Y.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new XW(X.common.issues)},input:X.data})}});else return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new XW(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}U4.create=(W,$)=>{return new U4({innerType:W,typeName:S.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...Q0($)})};class KX extends U0{_parse(W){if(this._getType(W)!==p.nan){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.nan,received:X.parsedType}),$0}return{status:"valid",value:W.data}}}KX.create=(W)=>{return new KX({typeName:S.ZodNaN,...Q0(W)})};var jZ=Symbol("zod_brand");class u9 extends U0{_parse(W){let{ctx:$}=this._processInputParams(W),X=$.data;return this._def.type._parse({data:X,path:$.path,parent:$})}unwrap(){return this._def.type}}class AX extends U0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(J.status==="aborted")return $0;if(J.status==="dirty")return $.dirty(),a$(J.value);else return this._def.out._parseAsync({data:J.value,path:X.path,parent:X})})();else{let Y=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(Y.status==="aborted")return $0;if(Y.status==="dirty")return $.dirty(),{status:"dirty",value:Y.value};else return this._def.out._parseSync({data:Y.value,path:X.path,parent:X})}}static create(W,$){return new AX({in:W,out:$,typeName:S.ZodPipeline})}}class w4 extends U0{_parse(W){let $=this._def.innerType._parse(W),X=(Y)=>{if(y8(Y))Y.value=Object.freeze(Y.value);return Y};return TX($)?$.then((Y)=>X(Y)):X($)}unwrap(){return this._def.innerType}}w4.create=(W,$)=>{return new w4({innerType:W,typeName:S.ZodReadonly,...Q0($)})};var IZ={object:o0.lazycreate},S;(function(W){W.ZodString="ZodString",W.ZodNumber="ZodNumber",W.ZodNaN="ZodNaN",W.ZodBigInt="ZodBigInt",W.ZodBoolean="ZodBoolean",W.ZodDate="ZodDate",W.ZodSymbol="ZodSymbol",W.ZodUndefined="ZodUndefined",W.ZodNull="ZodNull",W.ZodAny="ZodAny",W.ZodUnknown="ZodUnknown",W.ZodNever="ZodNever",W.ZodVoid="ZodVoid",W.ZodArray="ZodArray",W.ZodObject="ZodObject",W.ZodUnion="ZodUnion",W.ZodDiscriminatedUnion="ZodDiscriminatedUnion",W.ZodIntersection="ZodIntersection",W.ZodTuple="ZodTuple",W.ZodRecord="ZodRecord",W.ZodMap="ZodMap",W.ZodSet="ZodSet",W.ZodFunction="ZodFunction",W.ZodLazy="ZodLazy",W.ZodLiteral="ZodLiteral",W.ZodEnum="ZodEnum",W.ZodEffects="ZodEffects",W.ZodNativeEnum="ZodNativeEnum",W.ZodOptional="ZodOptional",W.ZodNullable="ZodNullable",W.ZodDefault="ZodDefault",W.ZodCatch="ZodCatch",W.ZodPromise="ZodPromise",W.ZodBranded="ZodBranded",W.ZodPipeline="ZodPipeline",W.ZodReadonly="ZodReadonly"})(S||(S={}));var fZ=oW.create,PZ=h8.create,xZ=KX.create,vZ=g8.create,bZ=wX.create,yZ=X4.create,hZ=_X.create,gZ=Y4.create,mZ=J4.create,pZ=DX.create,uZ=l2.create,cZ=iW.create,dZ=MX.create,lZ=xW.create,oZ=o0.create,iZ=o0.strictCreate,nZ=G4.create,rZ=p9.create,tZ=H4.create,aZ=nW.create,sZ=VX.create,eZ=OX.create,WS=m8.create,$S=W4.create,XS=Q4.create,YS=z4.create,JS=o2.create,GS=F4.create,HS=p8.create,QS=vW.create,zS=YW.create,FS=B2.create,TS=vW.createWithPreprocess,US=AX.create;function tG(){return{}}function aG(W,$){let X={type:"array"};if(W.type?._def&&W.type?._def?.typeName!==S.ZodAny)X.items=e(W.type._def,{...$,currentPath:[...$.currentPath,"items"]});if(W.minLength)O0(X,"minItems",W.minLength.value,W.minLength.message,$);if(W.maxLength)O0(X,"maxItems",W.maxLength.value,W.maxLength.message,$);if(W.exactLength)O0(X,"minItems",W.exactLength.value,W.exactLength.message,$),O0(X,"maxItems",W.exactLength.value,W.exactLength.message,$);return X}function sG(W,$){let X={type:"integer",format:"int64"};if(!W.checks)return X;for(let Y of W.checks)switch(Y.kind){case"min":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"minimum",Y.value,Y.message,$);else O0(X,"exclusiveMinimum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMinimum=!0;O0(X,"minimum",Y.value,Y.message,$)}break;case"max":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"maximum",Y.value,Y.message,$);else O0(X,"exclusiveMaximum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMaximum=!0;O0(X,"maximum",Y.value,Y.message,$)}break;case"multipleOf":O0(X,"multipleOf",Y.value,Y.message,$);break}return X}function eG(){return{type:"boolean"}}function EX(W,$){return e(W.type._def,$)}var W3=(W,$)=>{return e(W.innerType._def,$)};function c9(W,$,X){let Y=X??$.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((J,G)=>c9(W,$,J))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zM(W,$)}}var zM=(W,$)=>{let X={type:"integer",format:"unix-time"};if($.target==="openApi3")return X;for(let Y of W.checks)switch(Y.kind){case"min":O0(X,"minimum",Y.value,Y.message,$);break;case"max":O0(X,"maximum",Y.value,Y.message,$);break}return X};function $3(W,$){return{...e(W.innerType._def,$),default:W.defaultValue()}}function X3(W,$){return $.effectStrategy==="input"?e(W.schema._def,$):{}}function Y3(W){return{type:"string",enum:Array.from(W.values)}}var FM=(W)=>{if("type"in W&&W.type==="string")return!1;return"allOf"in W};function J3(W,$){let X=[e(W.left._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),e(W.right._def,{...$,currentPath:[...$.currentPath,"allOf","1"]})].filter((G)=>!!G),Y=$.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,J=[];return X.forEach((G)=>{if(FM(G)){if(J.push(...G.allOf),G.unevaluatedProperties===void 0)Y=void 0}else{let H=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Q,...z}=G;H=z}else Y=void 0;J.push(H)}}),J.length?{allOf:J,...Y}:void 0}function G3(W,$){let X=typeof W.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(W.value)?"array":"object"};if($.target==="openApi3")return{type:X==="bigint"?"integer":X,enum:[W.value]};return{type:X==="bigint"?"integer":X,const:W.value}}var d9=void 0,KW={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(d9===void 0)d9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return d9},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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,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})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function LX(W,$){let X={type:"string"};if(W.checks)for(let Y of W.checks)switch(Y.kind){case"min":O0(X,"minLength",typeof X.minLength==="number"?Math.max(X.minLength,Y.value):Y.value,Y.message,$);break;case"max":O0(X,"maxLength",typeof X.maxLength==="number"?Math.min(X.maxLength,Y.value):Y.value,Y.message,$);break;case"email":switch($.emailStrategy){case"format:email":AW(X,"email",Y.message,$);break;case"format:idn-email":AW(X,"idn-email",Y.message,$);break;case"pattern:zod":C1(X,KW.email,Y.message,$);break}break;case"url":AW(X,"uri",Y.message,$);break;case"uuid":AW(X,"uuid",Y.message,$);break;case"regex":C1(X,Y.regex,Y.message,$);break;case"cuid":C1(X,KW.cuid,Y.message,$);break;case"cuid2":C1(X,KW.cuid2,Y.message,$);break;case"startsWith":C1(X,RegExp(`^${l9(Y.value,$)}`),Y.message,$);break;case"endsWith":C1(X,RegExp(`${l9(Y.value,$)}$`),Y.message,$);break;case"datetime":AW(X,"date-time",Y.message,$);break;case"date":AW(X,"date",Y.message,$);break;case"time":AW(X,"time",Y.message,$);break;case"duration":AW(X,"duration",Y.message,$);break;case"length":O0(X,"minLength",typeof X.minLength==="number"?Math.max(X.minLength,Y.value):Y.value,Y.message,$),O0(X,"maxLength",typeof X.maxLength==="number"?Math.min(X.maxLength,Y.value):Y.value,Y.message,$);break;case"includes":{C1(X,RegExp(l9(Y.value,$)),Y.message,$);break}case"ip":{if(Y.version!=="v6")AW(X,"ipv4",Y.message,$);if(Y.version!=="v4")AW(X,"ipv6",Y.message,$);break}case"base64url":C1(X,KW.base64url,Y.message,$);break;case"jwt":C1(X,KW.jwt,Y.message,$);break;case"cidr":{if(Y.version!=="v6")C1(X,KW.ipv4Cidr,Y.message,$);if(Y.version!=="v4")C1(X,KW.ipv6Cidr,Y.message,$);break}case"emoji":C1(X,KW.emoji(),Y.message,$);break;case"ulid":{C1(X,KW.ulid,Y.message,$);break}case"base64":{switch($.base64Strategy){case"format:binary":{AW(X,"binary",Y.message,$);break}case"contentEncoding:base64":{O0(X,"contentEncoding","base64",Y.message,$);break}case"pattern:zod":{C1(X,KW.base64,Y.message,$);break}}break}case"nanoid":C1(X,KW.nanoid,Y.message,$);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(Y)}return X}function l9(W,$){return $.patternStrategy==="escape"?UM(W):W}var TM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function UM(W){let $="";for(let X=0;X<W.length;X++){if(!TM.has(W[X]))$+="\\";$+=W[X]}return $}function AW(W,$,X,Y){if(W.format||W.anyOf?.some((J)=>J.format)){if(!W.anyOf)W.anyOf=[];if(W.format){if(W.anyOf.push({format:W.format,...W.errorMessage&&Y.errorMessages&&{errorMessage:{format:W.errorMessage.format}}}),delete W.format,W.errorMessage){if(delete W.errorMessage.format,Object.keys(W.errorMessage).length===0)delete W.errorMessage}}W.anyOf.push({format:$,...X&&Y.errorMessages&&{errorMessage:{format:X}}})}else O0(W,"format",$,X,Y)}function C1(W,$,X,Y){if(W.pattern||W.allOf?.some((J)=>J.pattern)){if(!W.allOf)W.allOf=[];if(W.pattern){if(W.allOf.push({pattern:W.pattern,...W.errorMessage&&Y.errorMessages&&{errorMessage:{pattern:W.errorMessage.pattern}}}),delete W.pattern,W.errorMessage){if(delete W.errorMessage.pattern,Object.keys(W.errorMessage).length===0)delete W.errorMessage}}W.allOf.push({pattern:H3($,Y),...X&&Y.errorMessages&&{errorMessage:{pattern:X}}})}else O0(W,"pattern",H3($,Y),X,Y)}function H3(W,$){if(!$.applyRegexFlags||!W.flags)return W.source;let X={i:W.flags.includes("i"),m:W.flags.includes("m"),s:W.flags.includes("s")},Y=X.i?W.source.toLowerCase():W.source,J="",G=!1,H=!1,Q=!1;for(let z=0;z<Y.length;z++){if(G){J+=Y[z],G=!1;continue}if(X.i){if(H){if(Y[z].match(/[a-z]/)){if(Q)J+=Y[z],J+=`${Y[z-2]}-${Y[z]}`.toUpperCase(),Q=!1;else if(Y[z+1]==="-"&&Y[z+2]?.match(/[a-z]/))J+=Y[z],Q=!0;else J+=`${Y[z]}${Y[z].toUpperCase()}`;continue}}else if(Y[z].match(/[a-z]/)){J+=`[${Y[z]}${Y[z].toUpperCase()}]`;continue}}if(X.m){if(Y[z]==="^"){J+=`(^|(?<=[\r
6
- ]))`;continue}else if(Y[z]==="$"){J+=`($|(?=[\r
7
- ]))`;continue}}if(X.s&&Y[z]==="."){J+=H?`${Y[z]}\r
3
+ var jD=Object.create;var{getPrototypeOf:ID,defineProperty:N9,getOwnPropertyNames:PD}=Object;var fD=Object.prototype.hasOwnProperty;var xD=(W,$,X)=>{X=W!=null?jD(ID(W)):{};let Y=$||!W||!W.__esModule?N9(X,"default",{value:W,enumerable:!0}):X;for(let G of PD(W))if(!fD.call(Y,G))N9(Y,G,{get:()=>W[G],enumerable:!0});return Y};var bD=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var vD=(W,$)=>{for(var X in $)N9(W,X,{get:$[X],enumerable:!0,configurable:!0,set:(Y)=>$[X]=()=>Y})};var _B=(W,$)=>()=>(W&&($=W(W=0)),$);var wJ=import.meta.require;var f3=bD((Qk,P3)=>{var M$=wJ("os"),O$=wJ("path");function I3(W){let $=process.env.XDG_CACHE_HOME||O$.join(M$.homedir(),".cache");return O$.join($,W)}function AV(W){return O$.join(M$.homedir(),"Library","Caches",W)}function EV(W){let $=process.env.LOCALAPPDATA||O$.join(M$.homedir(),"AppData","Local");return O$.join($,W,"Cache")}var LV=function(){switch(M$.platform()){case"darwin":return AV;case"win32":return EV;case"aix":case"android":case"freebsd":case"linux":case"netbsd":case"openbsd":case"sunos":return I3;default:return console.error(`(node:${process.pid}) [cachedir] Warning: the platform "${M$.platform()}" is not currently supported by node-cachedir, falling back to "posix". Please file an issue with your platform here: https://github.com/LinusU/node-cachedir/issues/new`),I3}}();P3.exports=function W($){if(typeof $!=="string")throw new TypeError("id is not a string");if($.length===0)throw new Error("id cannot be empty");if(/[^0-9a-zA-Z-]/.test($))throw new Error("id cannot contain special characters");return LV($)}});class l4 extends Promise{fate;resolve;reject;done=!1;constructor(W){let $,X;super((Y,G)=>{$=Y,X=G});this.resolve=$,this.reject=X,this.use(W instanceof Promise?W:new Promise(W))}pass(W,$){if(W===this.fate)this.resolve($),this.done=!0}fail(W,$){if(W===this.fate)this.reject($),this.done=!0}use(W){if(W instanceof Promise){let $=W;this.fate=$,$.then((X)=>{this.pass($,X)},(X)=>{this.fail($,X)})}else this.resolve(W),this.fate=void 0}}var VB=(W,$,X=DJ.STORE)=>{return UJ(X,{key:`${W.key}:JSON`,get:({get:Y})=>$.toJson(Y(W)),set:({set:Y},G)=>{Y(W,$.fromJson(G))}})};function KB(W,$,X){return Z9(W,{key:`${$.key}:JSON`,get:(G)=>({get:J})=>{let H=J($,G);return X.toJson(H)},set:(G)=>({set:J},H)=>{J($,G,X.fromJson(H))}},["mutable","json"])}var o4=(W)=>JSON.parse(W),S1=(W)=>JSON.stringify(W),EB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function s(W){while(W.child!==null)W=W.child;return W}class GX{_buffer;_index=0;constructor(W){let $;if(typeof W==="number")$=W;else $=W.length;this._buffer=Array.from({length:$})}get buffer(){return this._buffer}get index(){return this._index}add(W){this._buffer[this._index]=W,this._index=(this._index+1)%this._buffer.length}copy(){let W=new GX([...this._buffer]);return W._index=this._index,W}}var yD={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function VJ(W,$){let X=S1($),Y=`${W.key}(${X})`,G=yD[W.type],J={key:Y,type:G};return Object.assign(J,{family:{key:W.key,subKey:X}}),Object.assign(J,{counterfeit:!0}),J}function i4(W){let $={key:W.key,type:W.type};if("family"in W)$.family=W.family;return $}var S9=(W)=>($,X,Y,G,...J)=>{console[W](`${$} ${X} "${Y}" ${G}`,...J)},hD={error:S9("error"),info:S9("info"),warn:S9("warn")};class q9{logLevel;filter;logger;constructor(W,$,X=hD){this.logLevel=W,this.filter=$,this.logger=X}error=(...W)=>{let $=this.filter?.(...W)??!0;if(this.logLevel!==null){if($===!0)this.logger.error(...W);else if($!==!1)this.logger.error(...$)}};info=(...W)=>{let $=this.filter?.(...W)??!0;if(this.logLevel==="info"){if($===!0)this.logger.info(...W);else if($!==!1)this.logger.info(...$)}};warn=(...W)=>{let $=this.filter?.(...W)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if($===!0)this.logger.warn(...W);else if($!==!1)this.logger.warn(...$)}}}class fW{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(W,$)=>`${W}:${$}`;warn;getRelatedKeys(W){return this.relations.get(W)}addRelation(W,$){let X=this.relations.get(W),Y=this.relations.get($);if(X)X.add($);else X=new Set([$]),this.relations.set(W,X);if(Y)Y.add(W);else Y=new Set([W]),this.relations.set($,Y)}deleteRelation(W,$){let X=this.relations.get(W);if(X){if(X.delete($),X.size===0)this.relations.delete(W);let Y=this.relations.get($);if(Y){if(Y.delete(W),Y.size===0)this.relations.delete($)}}}replaceRelationsUnsafely(W,$){this.relations.set(W,new Set($));for(let X of $){let Y=new Set().add(W);this.relations.set(X,Y)}}replaceRelationsSafely(W,$){let X=this.relations.get(W),Y=this.isAType?.(W)?W:void 0,G=Y===void 0?W:void 0;if(X)for(let J of X){Y??=J,G??=J;let H=this.relations.get(J);if(H){if(H.size===1)this.relations.delete(J);else H.delete(W);this.contents.delete(this.makeContentKey(Y,G))}}this.relations.set(W,new Set($));for(let J of $){let H=this.relations.get(J);if(H)H.add(W);else H=new Set().add(W),this.relations.set(J,H)}}getContentInternal(W){return this.contents.get(W)}setContent(W,$){this.contents.set(W,$)}deleteContent(W){this.contents.delete(W)}constructor(W,$){if(this.a=W.between[0],this.b=W.between[1],this.cardinality=W.cardinality,!$?.externalStore)this.relations=new Map(W.relations?.map(([X,Y])=>[X,new Set(Y)])),this.contents=new Map(W.contents);if(this.isAType=$?.isAType??null,this.isBType=$?.isBType??null,this.isContent=$?.isContent??null,$?.makeContentKey)this.makeContentKey=$.makeContentKey;if($?.externalStore){let X=$.externalStore;if(this.has=(Y,G)=>X.has(Y,G),this.addRelation=(Y,G)=>{X.addRelation(Y,G)},this.deleteRelation=(Y,G)=>{X.deleteRelation(Y,G)},this.replaceRelationsSafely=(Y,G)=>{X.replaceRelationsSafely(Y,G)},this.replaceRelationsUnsafely=(Y,G)=>{X.replaceRelationsUnsafely(Y,G)},this.getRelatedKeys=(Y)=>X.getRelatedKeys(Y),X.getContent)this.getContentInternal=(Y)=>{return X.getContent(Y)},this.setContent=(Y,G)=>{X.setContent(Y,G)},this.deleteContent=(Y)=>{X.deleteContent(Y)};for(let[Y,G]of W.relations??[]){let J=this.isAType?.(Y)?Y:void 0,H=J===void 0?Y:void 0;for(let Q of G)J??=Q,H??=Q,this.addRelation(J,H)}for(let[Y,G]of W.contents??[])this.setContent(Y,G)}if($?.warn)this.warn=$.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([W,$])=>[W,[...$]]),contents:[...this.contents.entries()]}}set(...W){let $,X,Y;switch(W.length){case 1:{let G=W[0];$=G[this.a],X=G[this.b],Y=void 0;break}case 2:{let G=W[0];if(typeof G==="string")[$,X]=W;else $=G[this.a],X=G[this.b],Y=W[1];break}default:{$=W[0],X=W[1],Y=W[2];break}}switch(this.cardinality){case"1:1":{let G=this.getRelatedKey($);if(G&&G!==X)this.delete($,G)}case"1:n":{let G=this.getRelatedKey(X);if(G&&G!==$)this.delete(G,X)}break;case"n:n":}if(Y){let G=this.makeContentKey($,X);this.setContent(G,Y)}return this.addRelation($,X),this}delete(W,$){$=typeof $==="string"?$:W[this.b];let X=typeof W==="string"?W:W[this.a];if(X===void 0&&typeof $==="string"){let Y=this.getRelatedKeys($);if(Y)for(let G of Y)this.delete(G,$)}if(typeof X==="string"&&$===void 0){let Y=this.getRelatedKeys(X);if(Y)for(let G of Y)this.delete(X,G)}if(typeof X==="string"&&typeof $==="string"){this.deleteRelation(X,$);let Y=this.makeContentKey(X,$);this.deleteContent(Y)}return this}getRelatedKey(W){let $=this.getRelatedKeys(W);if($){if($.size>1)this.warn?.(`${$.size} related keys were found for key "${W}": (${[...$].map((Y)=>`"${Y}"`).join(", ")}). Only one related key was expected.`);let X;for(let Y of $){X=Y;break}return X}}replaceRelations(W,$,X){let Y=!Array.isArray($),G=Y?Object.keys($):$;if(X?.reckless)this.replaceRelationsUnsafely(W,G);else this.replaceRelationsSafely(W,G);if(Y)for(let J of G){let H=this.makeContentKey(W,J),Q=$[J];this.setContent(H,Q)}return this}getContent(W,$){let X=this.makeContentKey(W,$);return this.getContentInternal(X)}getRelationEntries(W){let $=W[this.a],X=W[this.b];if($!==void 0&&X===void 0){let Y=this.getRelatedKeys($);if(Y)return[...Y].map((G)=>{return[G,this.getContent($,G)]})}if($===void 0&&X!==void 0){let Y=this.getRelatedKeys(X);if(Y)return[...Y].map((G)=>{return[G,this.getContent(G,X)]})}return[]}has(W,$){if($)return this.getRelatedKeys(W)?.has($)??!1;return this.relations.has(W)}}class B0{Subscriber;subscribers=new Map;subscribe(W,$){return this.subscribers.set(W,$),()=>{this.unsubscribe(W)}}unsubscribe(W){this.subscribers.delete(W)}next(W){let $=this.subscribers.values();for(let X of $)X(W)}}class C9 extends B0{state;constructor(W){super();this.state=W}next(W){this.state=W,super.next(W)}}function A2(W){return"epoch"in W.transactionMeta}function o1(W){return"phase"in W.transactionMeta}function MJ(W){return W[0].toUpperCase()+W.slice(1)}function JX(W){return W.type.split("_").map(MJ).join(" ")}class n4 extends Error{constructor(W,$){super(`${JX(W)} ${S1(W.key)} not found in store "${$.config.name}".`)}}var b8=(W)=>($)=>W instanceof Function?W($):W;var E2=(W,$)=>{if(W.valueMap.has($.key))return W.logger.info("\uD83D\uDCD6",$.type,$.key,"reading cached value"),OJ($,W);switch($.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return W.logger.info("\uD83E\uDDEE",$.type,$.key,"computing value"),$.get();case"atom":case"mutable_atom":{let X=$.default,Y;if(X instanceof Function)Y=X();else Y=X;return W.logger.info("\uD83D\uDC81","atom",$.key,"could not find cached value; using default",Y),Y}}};var KJ=(W,$)=>{if(W.operation.open){let X=performance.now();return W.logger.info("\u2757",$.type,$.key,`deferring setState at T-${X} until setState for "${W.operation.token.key}" is done`),X}W.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:$},W.logger.info("\u2B55",$.type,$.key,`operation start in store "${W.config.name}"${!o1(W)?"":` ${W.transactionMeta.phase} "${W.transactionMeta.update.key}"`}`)},AJ=(W)=>{if(W.operation.open)W.logger.info("\uD83D\uDD34",W.operation.token.type,W.operation.token.key,`operation done in store "${W.config.name}"`);W.operation={open:!1},W.on.operationClose.next(W.operation)},EJ=(W,$)=>{if(!W.operation.open)return W.logger.error("\uD83D\uDC1E","unknown",$,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return W.operation.done.has($)},L2=(W,$)=>{if(!W.operation.open){W.logger.error("\uD83D\uDC1E","unknown",$,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}W.operation.done.add($)};var LJ=(W,$,X)=>{switch($.type){case"mutable_atom":W.logger.info("\uD83D\uDCE2",$.type,$.key,"is now (",X.newValue,") subscribers:",$.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":W.logger.info("\uD83D\uDCE2",$.type,$.key,"went (",X.oldValue,"->",X.newValue,") subscribers:",$.subject.subscribers)}$.subject.next(X)};var k9=(W,$)=>{let X=s(W),Y=X.selectorAtoms.getRelatedKeys($.key);if(X.logger.info("\uD83E\uDDF9",$.type,$.key,Y?`evicting ${Y.size} states downstream:`:"no downstream states",Y??"to evict"),Y){if(X.operation.open)X.logger.info("\uD83E\uDDF9",$.type,$.key,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let G of Y){if(EJ(X,G))continue;BJ(G,X),L2(X,G)}}};var RJ=(W,$,X)=>{let Y=E2(W,$),G=Y;if($.type==="mutable_atom"&&o1(W)){let{parent:H}=W;G=r4(W,$,H)}if(G=b8(X)(G),W.logger.info("\uD83D\uDCDD","atom",$.key,"set to",G),G=q1(W,$.key,G,$.subject),ZJ(W,$.key))SJ(W,$.key);L2(W,$.key),k9(W,$);let J={oldValue:Y,newValue:G};if(!o1(W)){LJ(W,$,J);return}if(W.on.transactionApplying.state===null){let{key:H}=$;if(NJ(J.newValue))return;let Q={type:"atom_update",key:H,...J};if($.family)Q.family=$.family;W.transactionMeta.update.updates.push(Q),W.logger.info("\uD83D\uDCC1","atom",H,"stowed (",J.oldValue,"->",J.newValue,")")}else if($.key.startsWith("*")){let H=$.key.slice(1),Q=W.atoms.get(H),z=W.valueMap.get(H);if(Q.type==="mutable_atom"&&o1(W)){let{parent:F}=W;z=r4(W,Q,F)}if(z.do(J.newValue)===null)k9(W,Q)}};var HX=(W,$,X)=>{switch($.type){case"atom":case"mutable_atom":RJ(W,$,X);break;case"writable_pure_selector":case"writable_held_selector":$.set(X);break}};var QX=(W,$)=>s(W).atoms.has($),gD=(W,$)=>s(W).writableSelectors.has($),mD=(W,$)=>s(W).readonlySelectors.has($),qJ=(W,$)=>QX(W,$)||gD(W,$)||mD(W,$);var zX=(W,$)=>{return s(W).selectorGraph.getRelationEntries({downstreamSelectorKey:$}).filter(([Y,{source:G}])=>G!==$).map(([Y,{source:G}])=>G).filter((Y)=>qJ(W,Y))};var j9=(W,$,X)=>{let Y=[],G=zX(W,$);while(G.length>0){let J=G.shift();if(X.has(J))continue;if(X.add(J),!QX(W,J))G.push(...zX(W,J));else if(!Y.includes(J))Y.push(J)}return Y},CJ=(W,$)=>{let X=W.key,Y=zX($,X),G=new Set;return Y.flatMap((J)=>QX($,J)?J:j9($,J,G))};var kJ=(W,$,X,Y,G)=>{let J=s(W),{type:H,key:Q}=Y;if(H==="atom"||H==="mutable_atom")J.selectorAtoms.set({selectorKey:X,atomKey:Q}),W.logger.info("\uD83D\uDD0D",$,X,`discovers root atom "${Q}"`);else{let z=j9(W,Q,G);W.logger.info("\uD83D\uDD0D",$,X,`discovers root atoms: [ ${z.map((T)=>`"${T}"`).join(", ")} ]`);for(let T of z)J.selectorAtoms=J.selectorAtoms.set({selectorKey:X,atomKey:T})}G.add(Q)};var B2=(W,$,X,Y)=>({get:(...G)=>{let J=s(W),H;if(G.length===2){let[F,_]=G;H=i1(W,F,_)}else[H]=G;let Q=b1(W,H),z=E2(W,Q),T=H.key;return W.logger.info("\uD83D\uDD0C",$,X,`registers dependency ( "${T}" =`,z,")"),J.selectorGraph.set({upstreamSelectorKey:T,downstreamSelectorKey:X},{source:H.key}),kJ(W,$,X,H,Y),z},set:(...G)=>{let J,H;if(G.length===2)J=G[0],H=G[1];else{let T=G[0],F=G[1];H=G[2],J=i1(W,T,F)}let Q=s(W),z=b1(Q,J);HX(Q,z,H)},find:(...G)=>i1(W,...G),json:(G)=>v8(W,G)});var I9=(W,$,X)=>{let Y=s(W),G=new B0,J=new Set,{key:H,const:Q}=$,z="readonly_held_selector",{get:T,find:F,json:_}=B2(Y,"readonly_held_selector",H,J),O={...$,type:"readonly_held_selector",subject:G,install:(A)=>I9(A,$,X),get:()=>{return $.get({get:T,find:F,json:_},Q),q1(s(W),H,Q,G),J.clear(),Q},...X&&{family:X}};Y.readonlySelectors.set(H,O),W.logger.info("\u2728","readonly_held_selector",H,"=",Q);let M={key:H,type:"readonly_held_selector"};if(X)M.family=X;return M};var P9=(W,$,X)=>{let Y=s(W),G=new B0,J=new Set,H=$.key,Q="readonly_pure_selector",{get:z,find:T,json:F}=B2(Y,"readonly_pure_selector",H,J),_=()=>{let A=$.get({get:z,find:T,json:F});return q1(s(W),H,A,G),J.clear(),A},w={...$,type:"readonly_pure_selector",subject:G,install:(A)=>P9(A,$,X),get:_,...X&&{family:X}};Y.readonlySelectors.set(H,w);let O=_();W.logger.info("\u2728","readonly_pure_selector",H,"=",O);let M={key:H,type:"readonly_pure_selector"};if(X)M.family=X;return M};var f9=(W,$,X)=>{let Y=s(W),G=new B0,J=new Set,{key:H,const:Q}=$,z="writable_held_selector",T=B2(Y,"writable_held_selector",H,J),{find:F,get:_,json:w}=T,O={find:F,get:_,json:w},M=(Z=$.get,P=s(W))=>{return Z(O,Q),q1(P,H,Q,G),J.clear(),Q},I={...$,type:"writable_held_selector",subject:G,install:(Z)=>f9(Z,$,X),get:M,set:(Z)=>{let P=s(W),h=M($.get,P),x=b8(Z)(h);if(W.logger.info("\uD83D\uDCDD","writable_held_selector",H,"set (",h,"->",x,")"),q1(P,H,x,G),L2(P,H),A2(P))G.next({newValue:x,oldValue:h});$.set(T,x)},...X&&{family:X}};Y.writableSelectors.set(H,I);let j=M();W.logger.info("\u2728","writable_held_selector",H,"=",j);let R={key:H,type:"writable_held_selector"};if(X)R.family=X;return R};var t4=(W,$,X)=>{let Y=s(W),G=new B0,J=new Set,H=$.key,Q="writable_pure_selector",z=B2(Y,"writable_pure_selector",H,J),{find:T,get:F,json:_}=z,w={find:T,get:F,json:_},O=(R=$.get,Z=s(W))=>{let P=R(w);return q1(Z,H,P,G),J.clear(),P},A={...$,type:"writable_pure_selector",subject:G,install:(R)=>t4(R,$,X),get:O,set:(R)=>{let Z=s(W),P=O($.get,Z),h=b8(R)(P);if(W.logger.info("\uD83D\uDCDD","writable_pure_selector",H,"set (",P,"->",h,")"),q1(Z,$.key,h,G),L2(Z,$.key),A2(Z))G.next({newValue:h,oldValue:P});$.set(z,h)},...X&&{family:X}};Y.writableSelectors.set(H,A);let I=O();W.logger.info("\u2728",A.type,A.key,"=",I);let j={key:H,type:"writable_pure_selector"};if(X)j.family=X;return j};function UJ(W,$){let X="set"in $,Y="const"in $;if(Y&&X){let J=f9(W,$,void 0);return W.on.selectorCreation.next(J),J}if(Y){let J=I9(W,$,void 0);return W.on.selectorCreation.next(J),J}if(X){let J=t4(W,$,void 0);return W.on.selectorCreation.next(J),J}let G=P9(W,$,void 0);return W.on.selectorCreation.next(G),G}function Z9(W,$,X){let Y=$.key,G="writable_pure_selector_family",J={key:Y,type:"writable_pure_selector_family"},H=W.families.get(Y);if(H)W.logger.error("\u2757","writable_pure_selector_family",Y,`Overwriting an existing ${JX(H)} "${H.key}" in store "${W.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let Q=new B0,T=Object.assign((F)=>{let _=S1(F),w={key:Y,subKey:_},O=`${Y}(${_})`,M=s(W),A=t4(M,{key:O,get:$.get(F),set:$.set(F)},w);return Q.next({type:"state_creation",token:A}),A},J,{internalRoles:X,subject:Q,install:(F)=>Z9(F,$),default:(F)=>{return $.get(F)({get:(...w)=>a4(W,...w),find:(...w)=>i1(W,...w),json:(w)=>v8(W,w)})}});return W.families.set(Y,T),J}function jJ(W,$,X){let Y=W.families.get($.key);if(Y===void 0)throw new n4($,W);let G=Y(X),J=s(W);if(G.family){if(A2(J))switch(G.type){case"atom":case"mutable_atom":W.on.atomCreation.next(G);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":W.on.selectorCreation.next(G);break}else if(o1(J)&&J.on.transactionApplying.state===null)J.transactionMeta.update.updates.push({type:"state_creation",token:G})}return G}function IJ(W,$,X){let Y=S1(X),G=`${$.key}(${Y})`,J=s(W),H;switch($.type){case"atom_family":case"mutable_atom_family":H=J.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":H=J.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":H=J.readonlySelectors.get(G);break}if(H)return i4(H);return H}function i1(W,$,X){let Y=IJ(W,$,X);if(Y)return Y;let G=S1(X),J=W.molecules.get(G);if(!J&&W.config.lifespan==="immortal"){let H=VJ($,X);return W.logger.error("\u274C",H.type,H.key,`was not found in store "${W.config.name}"; returned a counterfeit token.`),H}if(Y=jJ(W,$,X),J)s(W).moleculeData.set(G,$.key);return Y}function PJ(W,$){if($.family){let X=W.families.get($.family.key);if(X)return X}}function R2(W,...$){let X,Y,G,J;if($.length===2){if(X=$[0],J=$[1],Y=PJ(W,X)??null,Y)G=X.family?o4(X.family.subKey):null,X=i1(W,Y,G)}else Y=$[0],G=$[1],J=$[2],X=i1(W,Y,G);if("counterfeit"in X&&"family"in X){let z=X.family.subKey,T=W.disposalTraces.buffer.find((F)=>F?.key===z);W.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${W.config.name}".`,T?`This state was previously disposed:
4
+ ${T.trace}`:"No previous disposal trace was found.");return}let H=KJ(W,X);if(H){let z=W.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${H}`,()=>{z(),W.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${H}`),R2(W,X,J)});return}let Q=b1(W,X);HX(W,Q,J),AJ(W)}function a4(W,...$){let X,Y,G;if($.length===1)X=$[0];else Y=$[0],G=$[1],X=i1(W,Y,G);if("counterfeit"in X&&"family"in X){Y=W.families.get(X.family.key);let J=X.family.subKey,H=W.disposalTraces.buffer.find((Q)=>Q?.key===J);switch(W.logger.error("\u274C",X.type,X.key,`could not be retrieved because it was not found in the store "${W.config.name}".`,H?`This state was previously disposed:
5
+ ${H.trace}`:"No previous disposal trace was found."),Y.type){case"atom_family":case"mutable_atom_family":return W.defaults.get(Y.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(W.defaults.has(Y.key))return W.defaults.get(X.family.key);let Q=b1(W,Y).default(J);return W.defaults.set(Y.key,Q),Q}}}return E2(W,b1(W,X))}class fJ{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new fW({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new fW({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new fW({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new fW({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new GX(100);molecules=new Map;moleculeJoins=new fW({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});moleculeGraph=new fW({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});moleculeData=new fW({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});miscResources=new Map;on={atomCreation:new B0,atomDisposal:new B0,selectorCreation:new B0,selectorDisposal:new B0,timelineCreation:new B0,transactionCreation:new B0,transactionApplying:new C9(null),operationClose:new B0,moleculeCreation:new B0,moleculeDisposal:new B0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new q9("warn",(W,$,X)=>!bJ(X))];logger={error:(...W)=>{for(let $ of this.loggers)$.error(...W)},info:(...W)=>{for(let $ of this.loggers)$.info(...W)},warn:(...W)=>{for(let $ of this.loggers)$.warn(...W)}};constructor(W,$=null){if(this.config={...$?.config,...W},$!==null){if(this.valueMap=new Map($?.valueMap),this.operation={...$?.operation},A2($))this.transactionMeta={epoch:new Map($?.transactionMeta.epoch),actionContinuities:new fW($?.transactionMeta.actionContinuities.toJSON())};for(let[,Y]of $.families){if(Y.internalRoles?.includes("mutable")||Y.internalRoles?.includes("join"))continue;Y.install(this)}let X=new Set;for(let[,Y]of $.atoms){if(X.has(Y.key))continue;if(Y.install(this),Y.type==="mutable_atom"){let G=v8($,Y),J=xJ(Y);X.add(G.key),X.add(J.key)}}for(let[,Y]of $.readonlySelectors)Y.install(this);for(let[,Y]of $.writableSelectors){if(X.has(Y.key))continue;Y.install(this)}for(let[,Y]of $.transactions)Y.install(this);for(let[,Y]of $.timelines)Y.install(this)}}}var DJ={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new fJ({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function b1(W,$){let X,Y=W;while(Y!==null){switch($.type){case"atom":case"mutable_atom":X=Y.atoms.get($.key);break;case"writable_pure_selector":case"writable_held_selector":X=Y.writableSelectors.get($.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=Y.readonlySelectors.get($.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":X=Y.families.get($.key);break;case"timeline":X=Y.timelines.get($.key);break;case"transaction":X=Y.transactions.get($.key);break}if(X)return X;Y=Y.child}throw new n4($,W)}var vJ=(W,$)=>{let X=s(W);if(X.operation.open)return X.operation.prev.get($.key);return X.valueMap.get($.key)};var x9=(W,$)=>{let X=s(W);return CJ($,W).map((G)=>{let J=X.atoms.get(G);if(J===void 0)throw new Error(`Atom "${G}", a dependency of selector "${$.key}", not found in store "${W.config.name}".`);return J.subject.subscribe(`${$.type}:${$.key}`,(H)=>{W.logger.info("\uD83D\uDCE2",$.type,$.key,"root",G,"went",H.oldValue,"->",H.newValue);let Q=vJ(X,$),z=E2(X,$);W.logger.info("\u2728",$.type,$.key,"went",Q,"->",z),$.subject.next({newValue:z,oldValue:Q})})})};function s4(W,$,X,Y){function G(_){if(W.operation.open){let w=W.on.operationClose.subscribe(`state subscription ${X}`,()=>{w(),Y(_)})}else Y(_)}let J=b1(W,$);W.logger.info("\uD83D\uDC40",J.type,J.key,`Adding subscription "${X}"`);let H=J.type==="writable_pure_selector"||J.type==="readonly_pure_selector",Q=null,z=G;if(H)Q=x9(W,J),z=(_)=>{if(Q)Q.length=0,Q.push(...x9(W,J));G(_)};let T=J.subject.subscribe(X,z);return()=>{if(W.logger.info("\uD83D\uDE48",J.type,J.key,`Removing subscription "${X}"`),T(),Q)for(let _ of Q)_()}}var yJ=(W,$,X,Y)=>{let G=b1(W,$);W.logger.info("\uD83D\uDC40","timeline",$.key,`Adding subscription "${X}"`);let J=G.subject.subscribe(X,Y);return()=>{W.logger.info("\uD83D\uDE48","timeline",$.key,`Removing subscription "${X}" from timeline`),J()}};class b9{initializeState(W,$){let X=`*${W.key}`;$.atoms.delete(X),$.valueMap.delete(X);let Y=W.family?{key:`*${W.family.key}`,subKey:W.family.subKey}:void 0,G=v9($,{key:X,default:null},Y);if($.parent?.valueMap.has(X)){let J=$.parent.valueMap.get(X);$.valueMap.set(X,J)}return G}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(W,$,X){let Y=`tracker:${X.config.name}:${o1(X)?X.transactionMeta.update.key:"main"}:${W.key}`,G=a4(X,W);this.unsubscribeFromInnerValue=G.subscribe(Y,(J)=>{R2(X,$,J)}),this.unsubscribeFromState=s4(X,W,Y,(J)=>{if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(Y,(H)=>{R2(X,$,H)})})}updateCore(W,$,X){let Y=`tracker:${X.config.name}:${o1(X)?X.transactionMeta.update.key:"main"}:${W.key}`;s4(X,$,Y,({newValue:G,oldValue:J})=>{let H=X.timelineTopics.getRelatedKey($.key);if(H){if(X.timelines.get(H)?.timeTraveling){let T=yJ(X,{key:H,type:"timeline"},Y,(F)=>{T(),R2(X,W,(_)=>{if(F==="redo"&&G)_.do(G);else if(F==="undo"&&J)_.undo(J);return _})});return}}let Q=X.on.operationClose.subscribe(Y,()=>{Q();let z=a4(X,W),T=G===null?-1:z.getUpdateNumber(G),F=T-z.cacheUpdateNumber;if(G&&F===1)R2(X,W,(_)=>(_.do(G),_));else X.logger.info("\u274C","mutable_atom",W.key,`could not be updated. Expected update number ${z.cacheUpdateNumber+1}, but got ${T}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(W,$){this.mutableState=W;let X=s($);this.latestUpdateState=this.initializeState(W,X),this.observeCore(W,this.latestUpdateState,X),this.updateCore(W,this.latestUpdateState,X),X.trackers.set(W.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(W.key)}}}var v8=(W,$)=>{if($.family){let Y=s(W),J={key:`${$.family.key}:JSON`,type:"writable_pure_selector_family"},H=b1(Y,J),Q=JSON.parse($.family.subKey);return i1(W,H,Q)}return{type:"writable_pure_selector",key:`${$.key}:JSON`}};var xJ=(W)=>{let X={type:"atom",key:`*${W.key}`};if(W.family)X.family={key:`*${W.family.key}`,subKey:W.family.subKey};return X};function NJ(W){return typeof W==="object"&&W!==null&&"do"in W&&"undo"in W&&"subscribe"in W}function r4(W,$,X){let Y=X.valueMap.get($.key),G=W.valueMap.get($.key);if(Y!==G)return G;if(Y===void 0)return $.default();X.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let J=$.toJson(Y),H=$.fromJson(J);return W.valueMap.set($.key,H),new b9($,X),H}function q1(W,$,X,Y){let G=W.valueMap.get($);if(G instanceof l4)G.use(X);if(X instanceof Promise){let J=new l4(X);return W.valueMap.set($,J),J.then((H)=>{q1(W,$,H,Y),Y.next({newValue:H,oldValue:J})}).catch((H)=>{W.logger.error("\uD83D\uDCA5","state",$,"rejected:",H)}),J}return W.valueMap.set($,X),X}var OJ=(W,$)=>{let X=$.valueMap.get(W.key);if(W.type==="mutable_atom"&&o1($)){let{parent:Y}=$;X=r4($,W,Y)}return X},BJ=(W,$)=>{let X=$.valueMap.get(W);if(X instanceof l4){let Y=X,G=$.writableSelectors.get(W)??$.readonlySelectors.get(W);if(G)Y.use(G.get());return}if($.operation.open)$.operation.prev.set(W,X);$.valueMap.delete(W),$.logger.info("\uD83D\uDDD1","state",W,"evicted")};var ZJ=(W,$)=>{return s(W).atomsThatAreDefault.has($)},hJ=(W,$)=>{let X=s(W);X.atomsThatAreDefault=new Set(X.atomsThatAreDefault).add($)},SJ=(W,$)=>{let X=s(W);X.atomsThatAreDefault=new Set(s(W).atomsThatAreDefault),X.atomsThatAreDefault.delete($)};function v9(W,$,X){let{key:G,default:J}=$;W.logger.info("\uD83D\uDD28","atom",G,`creating in store "${W.config.name}"`);let H=s(W),Q=H.atoms.get(G);if(Q&&Q.type==="atom")return W.logger.error("\u274C","atom",G,"Tried to create atom, but it already exists in the store."),i4(Q);let z=new B0,T={...$,type:"atom",install:(w)=>{return w.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${w.config.name}"`),v9(w,$,X)},subject:z};if(X)T.family=X;let F=J;if(J instanceof Function)F=J();H.atoms.set(G,T),hJ(W,G),q1(H,G,F,z);let _=i4(T);if($.effects){let w=0,O=[];for(let M of $.effects){let A=M({setSelf:(I)=>{R2(W,_,I)},onSet:(I)=>s4(W,_,`effect[${w}]`,I)});if(A)O.push(A);++w}T.cleanup=()=>{for(let M of O)M()}}return _}class y8 extends Set{mode="record";subject=new B0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(W,$=0){super(W);if(W instanceof y8)this.parent=W,this.cacheUpdateNumber=W.cacheUpdateNumber;if($)this.cacheLimit=$,this.cache=new Array($),this.subscribe("auto cache",(X)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=X})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(W){let $=new y8(W.members,W.cacheLimit);return $.cache=W.cache,$.cacheIdx=W.cacheIdx,$.cacheUpdateNumber=W.cacheUpdateNumber,$}add(W){let $=super.add(W);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S1(W)}`);return $}clear(){let W=this.mode==="record"?[...this]:null;if(super.clear(),W)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(W)}`)}delete(W){let $=super.delete(W);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S1(W)}`);return $}parent=null;child=null;transactionUpdates=null;transaction(W){this.mode="transaction",this.transactionUpdates=[],this.child=new y8(this);let $=this.child._subscribe("transaction",(X)=>{this.transactionUpdates?.push(X)});try{if(W(this.child)){for(let Y of this.transactionUpdates)this.doStep(Y);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(X){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",X),X}finally{$(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(W,$){return this.subject.subscribe(W,$)}subscribe(W,$){return this.subject.subscribe(W,(X)=>{$(`${this.cacheUpdateNumber}=${X}`)})}emit(W){this.subject.next(W)}doStep(W){let $=W.indexOf(":"),X=W.substring(0,$),Y=W.substring($+1);switch(X){case"add":this.add(JSON.parse(Y));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(Y));break;case"tx":for(let G of Y.split(";"))this.doStep(G)}}getUpdateNumber(W){let $=W.indexOf("=");return Number(W.substring(0,$))}do(W){let $=W.indexOf("="),X=Number(W.substring(0,$)),Y=X-this.cacheUpdateNumber;if(Y>0){if(Y===1){this.mode="playback";let J=W.substring($+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=X,null}return this.cacheUpdateNumber+1}if(Math.abs(Y)<this.cacheLimit){let J=this.cacheIdx+Y;if(this.cache[J]===W)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let T=this.cache[this.cacheIdx];if(this.cacheIdx--,!T)return"OUT_OF_RANGE";this.undo(T),Q=this.cacheIdx===J-1}let z=W.substring($+1);return this.doStep(z),this.mode="record",this.cacheUpdateNumber=X,null}return"OUT_OF_RANGE"}undoStep(W){let $=W.indexOf(":"),X=W.substring(0,$),Y=W.substring($+1);switch(X){case"add":this.delete(JSON.parse(Y));break;case"del":this.add(JSON.parse(Y));break;case"clear":{let G=JSON.parse(Y);for(let J of G)this.add(J);break}case"tx":{let G=Y.split(";");for(let J=G.length-1;J>=0;J--)this.undoStep(G[J])}}}undo(W){let $=W.indexOf("=");if(Number(W.substring(0,$))===this.cacheUpdateNumber){this.mode="playback";let Y=W.substring($+1);return this.undoStep(Y),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function bJ(W){return W.startsWith("\uD83D\uDD0D ")}class TX{listeners;globalListeners;handleEvent(W,...$){for(let Y of this.globalListeners)Y(W,...$);let X=this.listeners.get(W);if(X)for(let Y of X)Y(...$)}id="no_id_retrieved";emit;constructor(W){this.emit=W,this.listeners=new Map,this.globalListeners=new Set}on(W,$){let X=this.listeners.get(W);if(X)X.add($);else this.listeners.set(W,new Set([$]));return this}onAny(W){return this.globalListeners.add(W),this}off(W,$){let X=this.listeners.get(W);if(X)if($)X.delete($);else this.listeners.delete(W);return this}offAny(W){return this.globalListeners.delete(W),this}}class gJ extends TX{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(W){super((...$)=>{return this.out.next($),this});this.id=W,this.in=new B0,this.out=new B0,this.in.subscribe("socket",($)=>{this.handleEvent(...$)})}dispose(){for(let W of this.disposalFunctions)W()}}class y9 extends TX{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...W){this.process.stderr.write(S1(W.map(($)=>$ instanceof y8?`{ ${$.toJSON().members.join(" | ")} }`:$))+"\x03")}logger={info:(...W)=>{this.log("i",...W)},warn:(...W)=>{this.log("w",...W)},error:(...W)=>{this.log("e",...W)}};constructor(){super((W,...$)=>{let X=JSON.stringify([W,...$]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(W)=>{let $=W.toString();this.unprocessedEvents.push(...$.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let Y=o4(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",Y),this.handleEvent(...Y);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let J=o4(G);this.handleEvent(...J)}}this.incompleteData=""}catch(Y){if(Y instanceof Error)this.logger.error("\u2757",Y.message,Y.cause,Y.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(W)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${W}`)}),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",(W)=>{this.logger.info("\uD83D\uDC64","user",W,"joined");let $=new gJ(`user:${W}`);this.relays.set(W,$),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let Y=X($);if(Y)$.disposalFunctions.push(Y)}this.on(`user:${W}`,(...X)=>{$.in.next(X)}),$.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(W)=>{let $=this.relays.get(W);if(this.off(`relay:${W}`),$)$.dispose(),this.relays.delete(W)}),process.stdout.write("ALIVE")}relay(W){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(W)}}var pJ=Symbol("Let zodToJsonSchema decide on which parser to use");var mJ={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},uJ=(W)=>typeof W==="string"?{...mJ,name:W}:{...mJ,...W};var cJ=(W)=>{let $=uJ(W),X=$.name!==void 0?[...$.basePath,$.definitionPath,$.name]:$.basePath;return{...$,currentPath:X,propertyPath:void 0,seen:new Map(Object.entries($.definitions).map(([Y,G])=>[G._def,{def:G._def,path:[...$.basePath,$.definitionPath,Y],jsonSchema:void 0}]))}};function h9(W,$,X,Y){if(!Y?.errorMessages)return;if(X)W.errorMessage={...W.errorMessage,[$]:X}}function O0(W,$,X,Y,G){W[$]=X,h9(W,$,Y,G)}var A0;(function(W){W.assertEqual=(G)=>G;function $(G){}W.assertIs=$;function X(G){throw new Error}W.assertNever=X,W.arrayToEnum=(G)=>{let J={};for(let H of G)J[H]=H;return J},W.getValidEnumValues=(G)=>{let J=W.objectKeys(G).filter((Q)=>typeof G[G[Q]]!=="number"),H={};for(let Q of J)H[Q]=G[Q];return W.objectValues(H)},W.objectValues=(G)=>{return W.objectKeys(G).map(function(J){return G[J]})},W.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let J=[];for(let H in G)if(Object.prototype.hasOwnProperty.call(G,H))J.push(H);return J},W.find=(G,J)=>{for(let H of G)if(J(H))return H;return},W.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&isFinite(G)&&Math.floor(G)===G;function Y(G,J=" | "){return G.map((H)=>typeof H==="string"?`'${H}'`:H).join(J)}W.joinValues=Y,W.jsonStringifyReplacer=(G,J)=>{if(typeof J==="bigint")return J.toString();return J}})(A0||(A0={}));var dJ;(function(W){W.mergeShapes=($,X)=>{return{...$,...X}}})(dJ||(dJ={}));var u=A0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N2=(W)=>{switch(typeof W){case"undefined":return u.undefined;case"string":return u.string;case"number":return isNaN(W)?u.nan:u.number;case"boolean":return u.boolean;case"function":return u.function;case"bigint":return u.bigint;case"symbol":return u.symbol;case"object":if(Array.isArray(W))return u.array;if(W===null)return u.null;if(W.then&&typeof W.then==="function"&&W.catch&&typeof W.catch==="function")return u.promise;if(typeof Map!=="undefined"&&W instanceof Map)return u.map;if(typeof Set!=="undefined"&&W instanceof Set)return u.set;if(typeof Date!=="undefined"&&W instanceof Date)return u.date;return u.object;default:return u.unknown}},S=A0.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"]);class YW extends Error{get errors(){return this.issues}constructor(W){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=W}format(W){let $=W||function(G){return G.message},X={_errors:[]},Y=(G)=>{for(let J of G.issues)if(J.code==="invalid_union")J.unionErrors.map(Y);else if(J.code==="invalid_return_type")Y(J.returnTypeError);else if(J.code==="invalid_arguments")Y(J.argumentsError);else if(J.path.length===0)X._errors.push($(J));else{let H=X,Q=0;while(Q<J.path.length){let z=J.path[Q];if(Q!==J.path.length-1)H[z]=H[z]||{_errors:[]};else H[z]=H[z]||{_errors:[]},H[z]._errors.push($(J));H=H[z],Q++}}};return Y(this),X}static assert(W){if(!(W instanceof YW))throw new Error(`Not a ZodError: ${W}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,A0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(W=($)=>$.message){let $={},X=[];for(let Y of this.issues)if(Y.path.length>0)$[Y.path[0]]=$[Y.path[0]]||[],$[Y.path[0]].push(W(Y));else X.push(W(Y));return{formErrors:X,fieldErrors:$}}get formErrors(){return this.flatten()}}YW.create=(W)=>{return new YW(W)};var Y$=(W,$)=>{let X;switch(W.code){case S.invalid_type:if(W.received===u.undefined)X="Required";else X=`Expected ${W.expected}, received ${W.received}`;break;case S.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify(W.expected,A0.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:X=`Unrecognized key(s) in object: ${A0.joinValues(W.keys,", ")}`;break;case S.invalid_union:X="Invalid input";break;case S.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${A0.joinValues(W.options)}`;break;case S.invalid_enum_value:X=`Invalid enum value. Expected ${A0.joinValues(W.options)}, received '${W.received}'`;break;case S.invalid_arguments:X="Invalid function arguments";break;case S.invalid_return_type:X="Invalid function return type";break;case S.invalid_date:X="Invalid date";break;case S.invalid_string:if(typeof W.validation==="object")if("includes"in W.validation){if(X=`Invalid input: must include "${W.validation.includes}"`,typeof W.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${W.validation.position}`}else if("startsWith"in W.validation)X=`Invalid input: must start with "${W.validation.startsWith}"`;else if("endsWith"in W.validation)X=`Invalid input: must end with "${W.validation.endsWith}"`;else A0.assertNever(W.validation);else if(W.validation!=="regex")X=`Invalid ${W.validation}`;else X="Invalid";break;case S.too_small:if(W.type==="array")X=`Array must contain ${W.exact?"exactly":W.inclusive?"at least":"more than"} ${W.minimum} element(s)`;else if(W.type==="string")X=`String must contain ${W.exact?"exactly":W.inclusive?"at least":"over"} ${W.minimum} character(s)`;else if(W.type==="number")X=`Number must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${W.minimum}`;else if(W.type==="date")X=`Date must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(W.minimum))}`;else X="Invalid input";break;case S.too_big:if(W.type==="array")X=`Array must contain ${W.exact?"exactly":W.inclusive?"at most":"less than"} ${W.maximum} element(s)`;else if(W.type==="string")X=`String must contain ${W.exact?"exactly":W.inclusive?"at most":"under"} ${W.maximum} character(s)`;else if(W.type==="number")X=`Number must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="bigint")X=`BigInt must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="date")X=`Date must be ${W.exact?"exactly":W.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(W.maximum))}`;else X="Invalid input";break;case S.custom:X="Invalid input";break;case S.invalid_intersection_types:X="Intersection results could not be merged";break;case S.not_multiple_of:X=`Number must be a multiple of ${W.multipleOf}`;break;case S.not_finite:X="Number must be finite";break;default:X=$.defaultError,A0.assertNever(W)}return{message:X}},pD=Y$;function m9(){return pD}var p9=(W)=>{let{data:$,path:X,errorMaps:Y,issueData:G}=W,J=[...X,...G.path||[]],H={...G,path:J};if(G.message!==void 0)return{...G,path:J,message:G.message};let Q="",z=Y.filter((T)=>!!T).slice().reverse();for(let T of z)Q=T(H,{data:$,defaultError:Q}).message;return{...G,path:J,message:Q}};function y(W,$){let X=m9(),Y=p9({issueData:$,data:W.data,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,X,X===Y$?void 0:Y$].filter((G)=>!!G)});W.common.issues.push(Y)}class C1{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(W,$){let X=[];for(let Y of $){if(Y.status==="aborted")return X0;if(Y.status==="dirty")W.dirty();X.push(Y.value)}return{status:W.value,value:X}}static async mergeObjectAsync(W,$){let X=[];for(let Y of $){let G=await Y.key,J=await Y.value;X.push({key:G,value:J})}return C1.mergeObjectSync(W,X)}static mergeObjectSync(W,$){let X={};for(let Y of $){let{key:G,value:J}=Y;if(G.status==="aborted")return X0;if(J.status==="aborted")return X0;if(G.status==="dirty")W.dirty();if(J.status==="dirty")W.dirty();if(G.value!=="__proto__"&&(typeof J.value!=="undefined"||Y.alwaysSet))X[G.value]=J.value}return{status:W.value,value:X}}}var X0=Object.freeze({status:"aborted"}),e4=(W)=>({status:"dirty",value:W}),v1=(W)=>({status:"valid",value:W}),lJ=(W)=>W.status==="aborted",oJ=(W)=>W.status==="dirty",g8=(W)=>W.status==="valid",FX=(W)=>typeof Promise!=="undefined"&&W instanceof Promise;function _X(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)}function nJ(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X}var l;(function(W){W.errToObj=($)=>typeof $==="string"?{message:$}:$||{},W.toString=($)=>typeof $==="string"?$:$===null||$===void 0?void 0:$.message})(l||(l={}));var W$,$$;class KW{constructor(W,$,X,Y){this._cachedPath=[],this.parent=W,this.data=$,this._path=X,this._key=Y}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 iJ=(W,$)=>{if(g8($))return{success:!0,data:$.value};else{if(!W.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new YW(W.common.issues);return this._error=X,this._error}}}};function Q0(W){if(!W)return{};let{errorMap:$,invalid_type_error:X,required_error:Y,description:G}=W;if($&&(X||Y))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:G};return{errorMap:(H,Q)=>{var z,T;let{message:F}=W;if(H.code==="invalid_enum_value")return{message:F!==null&&F!==void 0?F:Q.defaultError};if(typeof Q.data==="undefined")return{message:(z=F!==null&&F!==void 0?F:Y)!==null&&z!==void 0?z:Q.defaultError};if(H.code!=="invalid_type")return{message:Q.defaultError};return{message:(T=F!==null&&F!==void 0?F:X)!==null&&T!==void 0?T:Q.defaultError}},description:G}}class _0{get description(){return this._def.description}_getType(W){return N2(W.data)}_getOrReturnCtx(W,$){return $||{common:W.parent.common,data:W.data,parsedType:N2(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}_processInputParams(W){return{status:new C1,ctx:{common:W.parent.common,data:W.data,parsedType:N2(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}}_parseSync(W){let $=this._parse(W);if(FX($))throw new Error("Synchronous parse encountered promise.");return $}_parseAsync(W){let $=this._parse(W);return Promise.resolve($)}parse(W,$){let X=this.safeParse(W,$);if(X.success)return X.data;throw X.error}safeParse(W,$){var X;let Y={common:{issues:[],async:(X=$===null||$===void 0?void 0:$.async)!==null&&X!==void 0?X:!1,contextualErrorMap:$===null||$===void 0?void 0:$.errorMap},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:N2(W)},G=this._parseSync({data:W,path:Y.path,parent:Y});return iJ(Y,G)}"~validate"(W){var $,X;let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:N2(W)};if(!this["~standard"].async)try{let G=this._parseSync({data:W,path:[],parent:Y});return g8(G)?{value:G.value}:{issues:Y.common.issues}}catch(G){if((X=($=G===null||G===void 0?void 0:G.message)===null||$===void 0?void 0:$.toLowerCase())===null||X===void 0?void 0:X.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:W,path:[],parent:Y}).then((G)=>g8(G)?{value:G.value}:{issues:Y.common.issues})}async parseAsync(W,$){let X=await this.safeParseAsync(W,$);if(X.success)return X.data;throw X.error}async safeParseAsync(W,$){let X={common:{issues:[],contextualErrorMap:$===null||$===void 0?void 0:$.errorMap,async:!0},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:N2(W)},Y=this._parse({data:W,path:X.path,parent:X}),G=await(FX(Y)?Y:Promise.resolve(Y));return iJ(X,G)}refine(W,$){let X=(Y)=>{if(typeof $==="string"||typeof $==="undefined")return{message:$};else if(typeof $==="function")return $(Y);else return $};return this._refinement((Y,G)=>{let J=W(Y),H=()=>G.addIssue({code:S.custom,...X(Y)});if(typeof Promise!=="undefined"&&J instanceof Promise)return J.then((Q)=>{if(!Q)return H(),!1;else return!0});if(!J)return H(),!1;else return!0})}refinement(W,$){return this._refinement((X,Y)=>{if(!W(X))return Y.addIssue(typeof $==="function"?$(X,Y):$),!1;else return!0})}_refinement(W){return new bW({schema:this,typeName:q.ZodEffects,effect:{type:"refinement",refinement:W}})}superRefine(W){return this._refinement(W)}constructor(W){this.spa=this.safeParseAsync,this._def=W,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return GW.create(this,this._def)}nullable(){return Z2.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xW.create(this)}promise(){return c8.create(this,this._def)}or(W){return Q$.create([this,W],this._def)}and(W){return z$.create(this,W,this._def)}transform(W){return new bW({...Q0(this._def),schema:this,typeName:q.ZodEffects,effect:{type:"transform",transform:W}})}default(W){let $=typeof W==="function"?W:()=>W;return new w$({...Q0(this._def),innerType:this,defaultValue:$,typeName:q.ZodDefault})}brand(){return new d9({typeName:q.ZodBranded,type:this,...Q0(this._def)})}catch(W){let $=typeof W==="function"?W:()=>W;return new U$({...Q0(this._def),innerType:this,catchValue:$,typeName:q.ZodCatch})}describe(W){return new this.constructor({...this._def,description:W})}pipe(W){return AX.create(this,W)}readonly(){return D$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var uD=/^c[^\s-]{8,}$/i,cD=/^[0-9a-z]+$/,dD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lD=/^[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,oD=/^[a-z0-9_-]{21}$/i,iD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nD=/^[-+]?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)?)??$/,rD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",g9,aD=/^(?:(?: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])$/,sD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,eD=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,WV=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$V=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,XV=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rJ="((\\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])))",YV=new RegExp(`^${rJ}$`);function tJ(W){let $="[0-5]\\d";if(W.precision)$=`${$}\\.\\d{${W.precision}}`;else if(W.precision==null)$=`${$}(\\.\\d+)?`;let X=W.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${X}`}function GV(W){return new RegExp(`^${tJ(W)}$`)}function JV(W){let $=`${rJ}T${tJ(W)}`,X=[];if(X.push(W.local?"Z?":"Z"),W.offset)X.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${X.join("|")})`,new RegExp(`^${$}$`)}function HV(W,$){if(($==="v4"||!$)&&aD.test(W))return!0;if(($==="v6"||!$)&&eD.test(W))return!0;return!1}function QV(W,$){if(!iD.test(W))return!1;try{let[X]=W.split("."),Y=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),G=JSON.parse(atob(Y));if(typeof G!=="object"||G===null)return!1;if(!G.typ||!G.alg)return!1;if($&&G.alg!==$)return!1;return!0}catch(X){return!1}}function zV(W,$){if(($==="v4"||!$)&&sD.test(W))return!0;if(($==="v6"||!$)&&WV.test(W))return!0;return!1}class oW extends _0{_parse(W){if(this._def.coerce)W.data=String(W.data);if(this._getType(W)!==u.string){let G=this._getOrReturnCtx(W);return y(G,{code:S.invalid_type,expected:u.string,received:G.parsedType}),X0}let X=new C1,Y=void 0;for(let G of this._def.checks)if(G.kind==="min"){if(W.data.length<G.value)Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="max"){if(W.data.length>G.value)Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="length"){let J=W.data.length>G.value,H=W.data.length<G.value;if(J||H){if(Y=this._getOrReturnCtx(W,Y),J)y(Y,{code:S.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(H)y(Y,{code:S.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});X.dirty()}}else if(G.kind==="email"){if(!rD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"email",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="emoji"){if(!g9)g9=new RegExp(tD,"u");if(!g9.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"emoji",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="uuid"){if(!lD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"uuid",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="nanoid"){if(!oD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"nanoid",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="cuid"){if(!uD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"cuid",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="cuid2"){if(!cD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"cuid2",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="ulid"){if(!dD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"ulid",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="url")try{new URL(W.data)}catch(J){Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"url",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"regex",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="trim")W.data=W.data.trim();else if(G.kind==="includes"){if(!W.data.includes(G.value,G.position))Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),X.dirty()}else if(G.kind==="toLowerCase")W.data=W.data.toLowerCase();else if(G.kind==="toUpperCase")W.data=W.data.toUpperCase();else if(G.kind==="startsWith"){if(!W.data.startsWith(G.value))Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.invalid_string,validation:{startsWith:G.value},message:G.message}),X.dirty()}else if(G.kind==="endsWith"){if(!W.data.endsWith(G.value))Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.invalid_string,validation:{endsWith:G.value},message:G.message}),X.dirty()}else if(G.kind==="datetime"){if(!JV(G).test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.invalid_string,validation:"datetime",message:G.message}),X.dirty()}else if(G.kind==="date"){if(!YV.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.invalid_string,validation:"date",message:G.message}),X.dirty()}else if(G.kind==="time"){if(!GV(G).test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.invalid_string,validation:"time",message:G.message}),X.dirty()}else if(G.kind==="duration"){if(!nD.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"duration",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="ip"){if(!HV(W.data,G.version))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"ip",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="jwt"){if(!QV(W.data,G.alg))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"jwt",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="cidr"){if(!zV(W.data,G.version))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"cidr",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="base64"){if(!$V.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"base64",code:S.invalid_string,message:G.message}),X.dirty()}else if(G.kind==="base64url"){if(!XV.test(W.data))Y=this._getOrReturnCtx(W,Y),y(Y,{validation:"base64url",code:S.invalid_string,message:G.message}),X.dirty()}else A0.assertNever(G);return{status:X.value,value:W.data}}_regex(W,$,X){return this.refinement((Y)=>W.test(Y),{validation:$,code:S.invalid_string,...l.errToObj(X)})}_addCheck(W){return new oW({...this._def,checks:[...this._def.checks,W]})}email(W){return this._addCheck({kind:"email",...l.errToObj(W)})}url(W){return this._addCheck({kind:"url",...l.errToObj(W)})}emoji(W){return this._addCheck({kind:"emoji",...l.errToObj(W)})}uuid(W){return this._addCheck({kind:"uuid",...l.errToObj(W)})}nanoid(W){return this._addCheck({kind:"nanoid",...l.errToObj(W)})}cuid(W){return this._addCheck({kind:"cuid",...l.errToObj(W)})}cuid2(W){return this._addCheck({kind:"cuid2",...l.errToObj(W)})}ulid(W){return this._addCheck({kind:"ulid",...l.errToObj(W)})}base64(W){return this._addCheck({kind:"base64",...l.errToObj(W)})}base64url(W){return this._addCheck({kind:"base64url",...l.errToObj(W)})}jwt(W){return this._addCheck({kind:"jwt",...l.errToObj(W)})}ip(W){return this._addCheck({kind:"ip",...l.errToObj(W)})}cidr(W){return this._addCheck({kind:"cidr",...l.errToObj(W)})}datetime(W){var $,X;if(typeof W==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:W});return this._addCheck({kind:"datetime",precision:typeof(W===null||W===void 0?void 0:W.precision)==="undefined"?null:W===null||W===void 0?void 0:W.precision,offset:($=W===null||W===void 0?void 0:W.offset)!==null&&$!==void 0?$:!1,local:(X=W===null||W===void 0?void 0:W.local)!==null&&X!==void 0?X:!1,...l.errToObj(W===null||W===void 0?void 0:W.message)})}date(W){return this._addCheck({kind:"date",message:W})}time(W){if(typeof W==="string")return this._addCheck({kind:"time",precision:null,message:W});return this._addCheck({kind:"time",precision:typeof(W===null||W===void 0?void 0:W.precision)==="undefined"?null:W===null||W===void 0?void 0:W.precision,...l.errToObj(W===null||W===void 0?void 0:W.message)})}duration(W){return this._addCheck({kind:"duration",...l.errToObj(W)})}regex(W,$){return this._addCheck({kind:"regex",regex:W,...l.errToObj($)})}includes(W,$){return this._addCheck({kind:"includes",value:W,position:$===null||$===void 0?void 0:$.position,...l.errToObj($===null||$===void 0?void 0:$.message)})}startsWith(W,$){return this._addCheck({kind:"startsWith",value:W,...l.errToObj($)})}endsWith(W,$){return this._addCheck({kind:"endsWith",value:W,...l.errToObj($)})}min(W,$){return this._addCheck({kind:"min",value:W,...l.errToObj($)})}max(W,$){return this._addCheck({kind:"max",value:W,...l.errToObj($)})}length(W,$){return this._addCheck({kind:"length",value:W,...l.errToObj($)})}nonempty(W){return this.min(1,l.errToObj(W))}trim(){return new oW({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new oW({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new oW({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((W)=>W.kind==="datetime")}get isDate(){return!!this._def.checks.find((W)=>W.kind==="date")}get isTime(){return!!this._def.checks.find((W)=>W.kind==="time")}get isDuration(){return!!this._def.checks.find((W)=>W.kind==="duration")}get isEmail(){return!!this._def.checks.find((W)=>W.kind==="email")}get isURL(){return!!this._def.checks.find((W)=>W.kind==="url")}get isEmoji(){return!!this._def.checks.find((W)=>W.kind==="emoji")}get isUUID(){return!!this._def.checks.find((W)=>W.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((W)=>W.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((W)=>W.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((W)=>W.kind==="cuid2")}get isULID(){return!!this._def.checks.find((W)=>W.kind==="ulid")}get isIP(){return!!this._def.checks.find((W)=>W.kind==="ip")}get isCIDR(){return!!this._def.checks.find((W)=>W.kind==="cidr")}get isBase64(){return!!this._def.checks.find((W)=>W.kind==="base64")}get isBase64url(){return!!this._def.checks.find((W)=>W.kind==="base64url")}get minLength(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxLength(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}}oW.create=(W)=>{var $;return new oW({checks:[],typeName:q.ZodString,coerce:($=W===null||W===void 0?void 0:W.coerce)!==null&&$!==void 0?$:!1,...Q0(W)})};function TV(W,$){let X=(W.toString().split(".")[1]||"").length,Y=($.toString().split(".")[1]||"").length,G=X>Y?X:Y,J=parseInt(W.toFixed(G).replace(".","")),H=parseInt($.toFixed(G).replace(".",""));return J%H/Math.pow(10,G)}class m8 extends _0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(W){if(this._def.coerce)W.data=Number(W.data);if(this._getType(W)!==u.number){let G=this._getOrReturnCtx(W);return y(G,{code:S.invalid_type,expected:u.number,received:G.parsedType}),X0}let X=void 0,Y=new C1;for(let G of this._def.checks)if(G.kind==="int"){if(!A0.isInteger(W.data))X=this._getOrReturnCtx(W,X),y(X,{code:S.invalid_type,expected:"integer",received:"float",message:G.message}),Y.dirty()}else if(G.kind==="min"){if(G.inclusive?W.data<G.value:W.data<=G.value)X=this._getOrReturnCtx(W,X),y(X,{code:S.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),Y.dirty()}else if(G.kind==="max"){if(G.inclusive?W.data>G.value:W.data>=G.value)X=this._getOrReturnCtx(W,X),y(X,{code:S.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),Y.dirty()}else if(G.kind==="multipleOf"){if(TV(W.data,G.value)!==0)X=this._getOrReturnCtx(W,X),y(X,{code:S.not_multiple_of,multipleOf:G.value,message:G.message}),Y.dirty()}else if(G.kind==="finite"){if(!Number.isFinite(W.data))X=this._getOrReturnCtx(W,X),y(X,{code:S.not_finite,message:G.message}),Y.dirty()}else A0.assertNever(G);return{status:Y.value,value:W.data}}gte(W,$){return this.setLimit("min",W,!0,l.toString($))}gt(W,$){return this.setLimit("min",W,!1,l.toString($))}lte(W,$){return this.setLimit("max",W,!0,l.toString($))}lt(W,$){return this.setLimit("max",W,!1,l.toString($))}setLimit(W,$,X,Y){return new m8({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:X,message:l.toString(Y)}]})}_addCheck(W){return new m8({...this._def,checks:[...this._def.checks,W]})}int(W){return this._addCheck({kind:"int",message:l.toString(W)})}positive(W){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(W)})}negative(W){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(W)})}nonpositive(W){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(W)})}nonnegative(W){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(W)})}multipleOf(W,$){return this._addCheck({kind:"multipleOf",value:W,message:l.toString($)})}finite(W){return this._addCheck({kind:"finite",message:l.toString(W)})}safe(W){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(W)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(W)})}get minValue(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxValue(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}get isInt(){return!!this._def.checks.find((W)=>W.kind==="int"||W.kind==="multipleOf"&&A0.isInteger(W.value))}get isFinite(){let W=null,$=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if($===null||X.value>$)$=X.value}else if(X.kind==="max"){if(W===null||X.value<W)W=X.value}return Number.isFinite($)&&Number.isFinite(W)}}m8.create=(W)=>{return new m8({checks:[],typeName:q.ZodNumber,coerce:(W===null||W===void 0?void 0:W.coerce)||!1,...Q0(W)})};class p8 extends _0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(W){if(this._def.coerce)try{W.data=BigInt(W.data)}catch(G){return this._getInvalidInput(W)}if(this._getType(W)!==u.bigint)return this._getInvalidInput(W);let X=void 0,Y=new C1;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?W.data<G.value:W.data<=G.value)X=this._getOrReturnCtx(W,X),y(X,{code:S.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),Y.dirty()}else if(G.kind==="max"){if(G.inclusive?W.data>G.value:W.data>=G.value)X=this._getOrReturnCtx(W,X),y(X,{code:S.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),Y.dirty()}else if(G.kind==="multipleOf"){if(W.data%G.value!==BigInt(0))X=this._getOrReturnCtx(W,X),y(X,{code:S.not_multiple_of,multipleOf:G.value,message:G.message}),Y.dirty()}else A0.assertNever(G);return{status:Y.value,value:W.data}}_getInvalidInput(W){let $=this._getOrReturnCtx(W);return y($,{code:S.invalid_type,expected:u.bigint,received:$.parsedType}),X0}gte(W,$){return this.setLimit("min",W,!0,l.toString($))}gt(W,$){return this.setLimit("min",W,!1,l.toString($))}lte(W,$){return this.setLimit("max",W,!0,l.toString($))}lt(W,$){return this.setLimit("max",W,!1,l.toString($))}setLimit(W,$,X,Y){return new p8({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:X,message:l.toString(Y)}]})}_addCheck(W){return new p8({...this._def,checks:[...this._def.checks,W]})}positive(W){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(W)})}negative(W){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(W)})}nonpositive(W){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(W)})}nonnegative(W){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(W)})}multipleOf(W,$){return this._addCheck({kind:"multipleOf",value:W,message:l.toString($)})}get minValue(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxValue(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}}p8.create=(W)=>{var $;return new p8({checks:[],typeName:q.ZodBigInt,coerce:($=W===null||W===void 0?void 0:W.coerce)!==null&&$!==void 0?$:!1,...Q0(W)})};class wX extends _0{_parse(W){if(this._def.coerce)W.data=Boolean(W.data);if(this._getType(W)!==u.boolean){let X=this._getOrReturnCtx(W);return y(X,{code:S.invalid_type,expected:u.boolean,received:X.parsedType}),X0}return v1(W.data)}}wX.create=(W)=>{return new wX({typeName:q.ZodBoolean,coerce:(W===null||W===void 0?void 0:W.coerce)||!1,...Q0(W)})};class G$ extends _0{_parse(W){if(this._def.coerce)W.data=new Date(W.data);if(this._getType(W)!==u.date){let G=this._getOrReturnCtx(W);return y(G,{code:S.invalid_type,expected:u.date,received:G.parsedType}),X0}if(isNaN(W.data.getTime())){let G=this._getOrReturnCtx(W);return y(G,{code:S.invalid_date}),X0}let X=new C1,Y=void 0;for(let G of this._def.checks)if(G.kind==="min"){if(W.data.getTime()<G.value)Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),X.dirty()}else if(G.kind==="max"){if(W.data.getTime()>G.value)Y=this._getOrReturnCtx(W,Y),y(Y,{code:S.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),X.dirty()}else A0.assertNever(G);return{status:X.value,value:new Date(W.data.getTime())}}_addCheck(W){return new G$({...this._def,checks:[...this._def.checks,W]})}min(W,$){return this._addCheck({kind:"min",value:W.getTime(),message:l.toString($)})}max(W,$){return this._addCheck({kind:"max",value:W.getTime(),message:l.toString($)})}get minDate(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W!=null?new Date(W):null}get maxDate(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W!=null?new Date(W):null}}G$.create=(W)=>{return new G$({checks:[],coerce:(W===null||W===void 0?void 0:W.coerce)||!1,typeName:q.ZodDate,...Q0(W)})};class UX extends _0{_parse(W){if(this._getType(W)!==u.symbol){let X=this._getOrReturnCtx(W);return y(X,{code:S.invalid_type,expected:u.symbol,received:X.parsedType}),X0}return v1(W.data)}}UX.create=(W)=>{return new UX({typeName:q.ZodSymbol,...Q0(W)})};class J$ extends _0{_parse(W){if(this._getType(W)!==u.undefined){let X=this._getOrReturnCtx(W);return y(X,{code:S.invalid_type,expected:u.undefined,received:X.parsedType}),X0}return v1(W.data)}}J$.create=(W)=>{return new J$({typeName:q.ZodUndefined,...Q0(W)})};class H$ extends _0{_parse(W){if(this._getType(W)!==u.null){let X=this._getOrReturnCtx(W);return y(X,{code:S.invalid_type,expected:u.null,received:X.parsedType}),X0}return v1(W.data)}}H$.create=(W)=>{return new H$({typeName:q.ZodNull,...Q0(W)})};class DX extends _0{constructor(){super(...arguments);this._any=!0}_parse(W){return v1(W.data)}}DX.create=(W)=>{return new DX({typeName:q.ZodAny,...Q0(W)})};class n2 extends _0{constructor(){super(...arguments);this._unknown=!0}_parse(W){return v1(W.data)}}n2.create=(W)=>{return new n2({typeName:q.ZodUnknown,...Q0(W)})};class iW extends _0{_parse(W){let $=this._getOrReturnCtx(W);return y($,{code:S.invalid_type,expected:u.never,received:$.parsedType}),X0}}iW.create=(W)=>{return new iW({typeName:q.ZodNever,...Q0(W)})};class VX extends _0{_parse(W){if(this._getType(W)!==u.undefined){let X=this._getOrReturnCtx(W);return y(X,{code:S.invalid_type,expected:u.void,received:X.parsedType}),X0}return v1(W.data)}}VX.create=(W)=>{return new VX({typeName:q.ZodVoid,...Q0(W)})};class xW extends _0{_parse(W){let{ctx:$,status:X}=this._processInputParams(W),Y=this._def;if($.parsedType!==u.array)return y($,{code:S.invalid_type,expected:u.array,received:$.parsedType}),X0;if(Y.exactLength!==null){let J=$.data.length>Y.exactLength.value,H=$.data.length<Y.exactLength.value;if(J||H)y($,{code:J?S.too_big:S.too_small,minimum:H?Y.exactLength.value:void 0,maximum:J?Y.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Y.exactLength.message}),X.dirty()}if(Y.minLength!==null){if($.data.length<Y.minLength.value)y($,{code:S.too_small,minimum:Y.minLength.value,type:"array",inclusive:!0,exact:!1,message:Y.minLength.message}),X.dirty()}if(Y.maxLength!==null){if($.data.length>Y.maxLength.value)y($,{code:S.too_big,maximum:Y.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Y.maxLength.message}),X.dirty()}if($.common.async)return Promise.all([...$.data].map((J,H)=>{return Y.type._parseAsync(new KW($,J,$.path,H))})).then((J)=>{return C1.mergeArray(X,J)});let G=[...$.data].map((J,H)=>{return Y.type._parseSync(new KW($,J,$.path,H))});return C1.mergeArray(X,G)}get element(){return this._def.type}min(W,$){return new xW({...this._def,minLength:{value:W,message:l.toString($)}})}max(W,$){return new xW({...this._def,maxLength:{value:W,message:l.toString($)}})}length(W,$){return new xW({...this._def,exactLength:{value:W,message:l.toString($)}})}nonempty(W){return this.min(1,W)}}xW.create=(W,$)=>{return new xW({type:W,minLength:null,maxLength:null,exactLength:null,typeName:q.ZodArray,...Q0($)})};function h8(W){if(W instanceof o0){let $={};for(let X in W.shape){let Y=W.shape[X];$[X]=GW.create(h8(Y))}return new o0({...W._def,shape:()=>$})}else if(W instanceof xW)return new xW({...W._def,type:h8(W.element)});else if(W instanceof GW)return GW.create(h8(W.unwrap()));else if(W instanceof Z2)return Z2.create(h8(W.unwrap()));else if(W instanceof nW)return nW.create(W.items.map(($)=>h8($)));else return W}class o0 extends _0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let W=this._def.shape(),$=A0.objectKeys(W);return this._cached={shape:W,keys:$}}_parse(W){if(this._getType(W)!==u.object){let z=this._getOrReturnCtx(W);return y(z,{code:S.invalid_type,expected:u.object,received:z.parsedType}),X0}let{status:X,ctx:Y}=this._processInputParams(W),{shape:G,keys:J}=this._getCached(),H=[];if(!(this._def.catchall instanceof iW&&this._def.unknownKeys==="strip")){for(let z in Y.data)if(!J.includes(z))H.push(z)}let Q=[];for(let z of J){let T=G[z],F=Y.data[z];Q.push({key:{status:"valid",value:z},value:T._parse(new KW(Y,F,Y.path,z)),alwaysSet:z in Y.data})}if(this._def.catchall instanceof iW){let z=this._def.unknownKeys;if(z==="passthrough")for(let T of H)Q.push({key:{status:"valid",value:T},value:{status:"valid",value:Y.data[T]}});else if(z==="strict"){if(H.length>0)y(Y,{code:S.unrecognized_keys,keys:H}),X.dirty()}else if(z==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let z=this._def.catchall;for(let T of H){let F=Y.data[T];Q.push({key:{status:"valid",value:T},value:z._parse(new KW(Y,F,Y.path,T)),alwaysSet:T in Y.data})}}if(Y.common.async)return Promise.resolve().then(async()=>{let z=[];for(let T of Q){let F=await T.key,_=await T.value;z.push({key:F,value:_,alwaysSet:T.alwaysSet})}return z}).then((z)=>{return C1.mergeObjectSync(X,z)});else return C1.mergeObjectSync(X,Q)}get shape(){return this._def.shape()}strict(W){return l.errToObj,new o0({...this._def,unknownKeys:"strict",...W!==void 0?{errorMap:($,X)=>{var Y,G,J,H;let Q=(J=(G=(Y=this._def).errorMap)===null||G===void 0?void 0:G.call(Y,$,X).message)!==null&&J!==void 0?J:X.defaultError;if($.code==="unrecognized_keys")return{message:(H=l.errToObj(W).message)!==null&&H!==void 0?H:Q};return{message:Q}}}:{}})}strip(){return new o0({...this._def,unknownKeys:"strip"})}passthrough(){return new o0({...this._def,unknownKeys:"passthrough"})}extend(W){return new o0({...this._def,shape:()=>({...this._def.shape(),...W})})}merge(W){return new o0({unknownKeys:W._def.unknownKeys,catchall:W._def.catchall,shape:()=>({...this._def.shape(),...W._def.shape()}),typeName:q.ZodObject})}setKey(W,$){return this.augment({[W]:$})}catchall(W){return new o0({...this._def,catchall:W})}pick(W){let $={};return A0.objectKeys(W).forEach((X)=>{if(W[X]&&this.shape[X])$[X]=this.shape[X]}),new o0({...this._def,shape:()=>$})}omit(W){let $={};return A0.objectKeys(this.shape).forEach((X)=>{if(!W[X])$[X]=this.shape[X]}),new o0({...this._def,shape:()=>$})}deepPartial(){return h8(this)}partial(W){let $={};return A0.objectKeys(this.shape).forEach((X)=>{let Y=this.shape[X];if(W&&!W[X])$[X]=Y;else $[X]=Y.optional()}),new o0({...this._def,shape:()=>$})}required(W){let $={};return A0.objectKeys(this.shape).forEach((X)=>{if(W&&!W[X])$[X]=this.shape[X];else{let G=this.shape[X];while(G instanceof GW)G=G._def.innerType;$[X]=G}}),new o0({...this._def,shape:()=>$})}keyof(){return aJ(A0.objectKeys(this.shape))}}o0.create=(W,$)=>{return new o0({shape:()=>W,unknownKeys:"strip",catchall:iW.create(),typeName:q.ZodObject,...Q0($)})};o0.strictCreate=(W,$)=>{return new o0({shape:()=>W,unknownKeys:"strict",catchall:iW.create(),typeName:q.ZodObject,...Q0($)})};o0.lazycreate=(W,$)=>{return new o0({shape:W,unknownKeys:"strip",catchall:iW.create(),typeName:q.ZodObject,...Q0($)})};class Q$ extends _0{_parse(W){let{ctx:$}=this._processInputParams(W),X=this._def.options;function Y(G){for(let H of G)if(H.result.status==="valid")return H.result;for(let H of G)if(H.result.status==="dirty")return $.common.issues.push(...H.ctx.common.issues),H.result;let J=G.map((H)=>new YW(H.ctx.common.issues));return y($,{code:S.invalid_union,unionErrors:J}),X0}if($.common.async)return Promise.all(X.map(async(G)=>{let J={...$,common:{...$.common,issues:[]},parent:null};return{result:await G._parseAsync({data:$.data,path:$.path,parent:J}),ctx:J}})).then(Y);else{let G=void 0,J=[];for(let Q of X){let z={...$,common:{...$.common,issues:[]},parent:null},T=Q._parseSync({data:$.data,path:$.path,parent:z});if(T.status==="valid")return T;else if(T.status==="dirty"&&!G)G={result:T,ctx:z};if(z.common.issues.length)J.push(z.common.issues)}if(G)return $.common.issues.push(...G.ctx.common.issues),G.result;let H=J.map((Q)=>new YW(Q));return y($,{code:S.invalid_union,unionErrors:H}),X0}}get options(){return this._def.options}}Q$.create=(W,$)=>{return new Q$({options:W,typeName:q.ZodUnion,...Q0($)})};var lW=(W)=>{if(W instanceof T$)return lW(W.schema);else if(W instanceof bW)return lW(W.innerType());else if(W instanceof F$)return[W.value];else if(W instanceof r2)return W.options;else if(W instanceof _$)return A0.objectValues(W.enum);else if(W instanceof w$)return lW(W._def.innerType);else if(W instanceof J$)return[void 0];else if(W instanceof H$)return[null];else if(W instanceof GW)return[void 0,...lW(W.unwrap())];else if(W instanceof Z2)return[null,...lW(W.unwrap())];else if(W instanceof d9)return lW(W.unwrap());else if(W instanceof D$)return lW(W.unwrap());else if(W instanceof U$)return lW(W._def.innerType);else return[]};class c9 extends _0{_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==u.object)return y($,{code:S.invalid_type,expected:u.object,received:$.parsedType}),X0;let X=this.discriminator,Y=$.data[X],G=this.optionsMap.get(Y);if(!G)return y($,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),X0;if($.common.async)return G._parseAsync({data:$.data,path:$.path,parent:$});else return G._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(W,$,X){let Y=new Map;for(let G of $){let J=lW(G.shape[W]);if(!J.length)throw new Error(`A discriminator value for key \`${W}\` could not be extracted from all schema options`);for(let H of J){if(Y.has(H))throw new Error(`Discriminator property ${String(W)} has duplicate value ${String(H)}`);Y.set(H,G)}}return new c9({typeName:q.ZodDiscriminatedUnion,discriminator:W,options:$,optionsMap:Y,...Q0(X)})}}function u9(W,$){let X=N2(W),Y=N2($);if(W===$)return{valid:!0,data:W};else if(X===u.object&&Y===u.object){let G=A0.objectKeys($),J=A0.objectKeys(W).filter((Q)=>G.indexOf(Q)!==-1),H={...W,...$};for(let Q of J){let z=u9(W[Q],$[Q]);if(!z.valid)return{valid:!1};H[Q]=z.data}return{valid:!0,data:H}}else if(X===u.array&&Y===u.array){if(W.length!==$.length)return{valid:!1};let G=[];for(let J=0;J<W.length;J++){let H=W[J],Q=$[J],z=u9(H,Q);if(!z.valid)return{valid:!1};G.push(z.data)}return{valid:!0,data:G}}else if(X===u.date&&Y===u.date&&+W===+$)return{valid:!0,data:W};else return{valid:!1}}class z$ extends _0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W),Y=(G,J)=>{if(lJ(G)||lJ(J))return X0;let H=u9(G.value,J.value);if(!H.valid)return y(X,{code:S.invalid_intersection_types}),X0;if(oJ(G)||oJ(J))$.dirty();return{status:$.value,value:H.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([G,J])=>Y(G,J));else return Y(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}z$.create=(W,$,X)=>{return new z$({left:W,right:$,typeName:q.ZodIntersection,...Q0(X)})};class nW extends _0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==u.array)return y(X,{code:S.invalid_type,expected:u.array,received:X.parsedType}),X0;if(X.data.length<this._def.items.length)return y(X,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X0;if(!this._def.rest&&X.data.length>this._def.items.length)y(X,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let G=[...X.data].map((J,H)=>{let Q=this._def.items[H]||this._def.rest;if(!Q)return null;return Q._parse(new KW(X,J,X.path,H))}).filter((J)=>!!J);if(X.common.async)return Promise.all(G).then((J)=>{return C1.mergeArray($,J)});else return C1.mergeArray($,G)}get items(){return this._def.items}rest(W){return new nW({...this._def,rest:W})}}nW.create=(W,$)=>{if(!Array.isArray(W))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nW({items:W,typeName:q.ZodTuple,rest:null,...Q0($)})};class MX extends _0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==u.object)return y(X,{code:S.invalid_type,expected:u.object,received:X.parsedType}),X0;let Y=[],G=this._def.keyType,J=this._def.valueType;for(let H in X.data)Y.push({key:G._parse(new KW(X,H,X.path,H)),value:J._parse(new KW(X,X.data[H],X.path,H)),alwaysSet:H in X.data});if(X.common.async)return C1.mergeObjectAsync($,Y);else return C1.mergeObjectSync($,Y)}get element(){return this._def.valueType}static create(W,$,X){if($ instanceof _0)return new MX({keyType:W,valueType:$,typeName:q.ZodRecord,...Q0(X)});return new MX({keyType:oW.create(),valueType:W,typeName:q.ZodRecord,...Q0($)})}}class OX extends _0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==u.map)return y(X,{code:S.invalid_type,expected:u.map,received:X.parsedType}),X0;let Y=this._def.keyType,G=this._def.valueType,J=[...X.data.entries()].map(([H,Q],z)=>{return{key:Y._parse(new KW(X,H,X.path,[z,"key"])),value:G._parse(new KW(X,Q,X.path,[z,"value"]))}});if(X.common.async){let H=new Map;return Promise.resolve().then(async()=>{for(let Q of J){let z=await Q.key,T=await Q.value;if(z.status==="aborted"||T.status==="aborted")return X0;if(z.status==="dirty"||T.status==="dirty")$.dirty();H.set(z.value,T.value)}return{status:$.value,value:H}})}else{let H=new Map;for(let Q of J){let{key:z,value:T}=Q;if(z.status==="aborted"||T.status==="aborted")return X0;if(z.status==="dirty"||T.status==="dirty")$.dirty();H.set(z.value,T.value)}return{status:$.value,value:H}}}}OX.create=(W,$,X)=>{return new OX({valueType:$,keyType:W,typeName:q.ZodMap,...Q0(X)})};class u8 extends _0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==u.set)return y(X,{code:S.invalid_type,expected:u.set,received:X.parsedType}),X0;let Y=this._def;if(Y.minSize!==null){if(X.data.size<Y.minSize.value)y(X,{code:S.too_small,minimum:Y.minSize.value,type:"set",inclusive:!0,exact:!1,message:Y.minSize.message}),$.dirty()}if(Y.maxSize!==null){if(X.data.size>Y.maxSize.value)y(X,{code:S.too_big,maximum:Y.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Y.maxSize.message}),$.dirty()}let G=this._def.valueType;function J(Q){let z=new Set;for(let T of Q){if(T.status==="aborted")return X0;if(T.status==="dirty")$.dirty();z.add(T.value)}return{status:$.value,value:z}}let H=[...X.data.values()].map((Q,z)=>G._parse(new KW(X,Q,X.path,z)));if(X.common.async)return Promise.all(H).then((Q)=>J(Q));else return J(H)}min(W,$){return new u8({...this._def,minSize:{value:W,message:l.toString($)}})}max(W,$){return new u8({...this._def,maxSize:{value:W,message:l.toString($)}})}size(W,$){return this.min(W,$).max(W,$)}nonempty(W){return this.min(1,W)}}u8.create=(W,$)=>{return new u8({valueType:W,minSize:null,maxSize:null,typeName:q.ZodSet,...Q0($)})};class X$ extends _0{constructor(){super(...arguments);this.validate=this.implement}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==u.function)return y($,{code:S.invalid_type,expected:u.function,received:$.parsedType}),X0;function X(H,Q){return p9({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,m9(),Y$].filter((z)=>!!z),issueData:{code:S.invalid_arguments,argumentsError:Q}})}function Y(H,Q){return p9({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,m9(),Y$].filter((z)=>!!z),issueData:{code:S.invalid_return_type,returnTypeError:Q}})}let G={errorMap:$.common.contextualErrorMap},J=$.data;if(this._def.returns instanceof c8){let H=this;return v1(async function(...Q){let z=new YW([]),T=await H._def.args.parseAsync(Q,G).catch((w)=>{throw z.addIssue(X(Q,w)),z}),F=await Reflect.apply(J,this,T);return await H._def.returns._def.type.parseAsync(F,G).catch((w)=>{throw z.addIssue(Y(F,w)),z})})}else{let H=this;return v1(function(...Q){let z=H._def.args.safeParse(Q,G);if(!z.success)throw new YW([X(Q,z.error)]);let T=Reflect.apply(J,this,z.data),F=H._def.returns.safeParse(T,G);if(!F.success)throw new YW([Y(T,F.error)]);return F.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...W){return new X$({...this._def,args:nW.create(W).rest(n2.create())})}returns(W){return new X$({...this._def,returns:W})}implement(W){return this.parse(W)}strictImplement(W){return this.parse(W)}static create(W,$,X){return new X$({args:W?W:nW.create([]).rest(n2.create()),returns:$||n2.create(),typeName:q.ZodFunction,...Q0(X)})}}class T$ extends _0{get schema(){return this._def.getter()}_parse(W){let{ctx:$}=this._processInputParams(W);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}T$.create=(W,$)=>{return new T$({getter:W,typeName:q.ZodLazy,...Q0($)})};class F$ extends _0{_parse(W){if(W.data!==this._def.value){let $=this._getOrReturnCtx(W);return y($,{received:$.data,code:S.invalid_literal,expected:this._def.value}),X0}return{status:"valid",value:W.data}}get value(){return this._def.value}}F$.create=(W,$)=>{return new F$({value:W,typeName:q.ZodLiteral,...Q0($)})};function aJ(W,$){return new r2({values:W,typeName:q.ZodEnum,...Q0($)})}class r2 extends _0{constructor(){super(...arguments);W$.set(this,void 0)}_parse(W){if(typeof W.data!=="string"){let $=this._getOrReturnCtx(W),X=this._def.values;return y($,{expected:A0.joinValues(X),received:$.parsedType,code:S.invalid_type}),X0}if(!_X(this,W$,"f"))nJ(this,W$,new Set(this._def.values),"f");if(!_X(this,W$,"f").has(W.data)){let $=this._getOrReturnCtx(W),X=this._def.values;return y($,{received:$.data,code:S.invalid_enum_value,options:X}),X0}return v1(W.data)}get options(){return this._def.values}get enum(){let W={};for(let $ of this._def.values)W[$]=$;return W}get Values(){let W={};for(let $ of this._def.values)W[$]=$;return W}get Enum(){let W={};for(let $ of this._def.values)W[$]=$;return W}extract(W,$=this._def){return r2.create(W,{...this._def,...$})}exclude(W,$=this._def){return r2.create(this.options.filter((X)=>!W.includes(X)),{...this._def,...$})}}W$=new WeakMap;r2.create=aJ;class _$ extends _0{constructor(){super(...arguments);$$.set(this,void 0)}_parse(W){let $=A0.getValidEnumValues(this._def.values),X=this._getOrReturnCtx(W);if(X.parsedType!==u.string&&X.parsedType!==u.number){let Y=A0.objectValues($);return y(X,{expected:A0.joinValues(Y),received:X.parsedType,code:S.invalid_type}),X0}if(!_X(this,$$,"f"))nJ(this,$$,new Set(A0.getValidEnumValues(this._def.values)),"f");if(!_X(this,$$,"f").has(W.data)){let Y=A0.objectValues($);return y(X,{received:X.data,code:S.invalid_enum_value,options:Y}),X0}return v1(W.data)}get enum(){return this._def.values}}$$=new WeakMap;_$.create=(W,$)=>{return new _$({values:W,typeName:q.ZodNativeEnum,...Q0($)})};class c8 extends _0{unwrap(){return this._def.type}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==u.promise&&$.common.async===!1)return y($,{code:S.invalid_type,expected:u.promise,received:$.parsedType}),X0;let X=$.parsedType===u.promise?$.data:Promise.resolve($.data);return v1(X.then((Y)=>{return this._def.type.parseAsync(Y,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}c8.create=(W,$)=>{return new c8({type:W,typeName:q.ZodPromise,...Q0($)})};class bW extends _0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(W){let{status:$,ctx:X}=this._processInputParams(W),Y=this._def.effect||null,G={addIssue:(J)=>{if(y(X,J),J.fatal)$.abort();else $.dirty()},get path(){return X.path}};if(G.addIssue=G.addIssue.bind(G),Y.type==="preprocess"){let J=Y.transform(X.data,G);if(X.common.async)return Promise.resolve(J).then(async(H)=>{if($.value==="aborted")return X0;let Q=await this._def.schema._parseAsync({data:H,path:X.path,parent:X});if(Q.status==="aborted")return X0;if(Q.status==="dirty")return e4(Q.value);if($.value==="dirty")return e4(Q.value);return Q});else{if($.value==="aborted")return X0;let H=this._def.schema._parseSync({data:J,path:X.path,parent:X});if(H.status==="aborted")return X0;if(H.status==="dirty")return e4(H.value);if($.value==="dirty")return e4(H.value);return H}}if(Y.type==="refinement"){let J=(H)=>{let Q=Y.refinement(H,G);if(X.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return H};if(X.common.async===!1){let H=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(H.status==="aborted")return X0;if(H.status==="dirty")$.dirty();return J(H.value),{status:$.value,value:H.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((H)=>{if(H.status==="aborted")return X0;if(H.status==="dirty")$.dirty();return J(H.value).then(()=>{return{status:$.value,value:H.value}})})}if(Y.type==="transform")if(X.common.async===!1){let J=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!g8(J))return J;let H=Y.transform(J.value,G);if(H instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:H}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((J)=>{if(!g8(J))return J;return Promise.resolve(Y.transform(J.value,G)).then((H)=>({status:$.value,value:H}))});A0.assertNever(Y)}}bW.create=(W,$,X)=>{return new bW({schema:W,typeName:q.ZodEffects,effect:$,...Q0(X)})};bW.createWithPreprocess=(W,$,X)=>{return new bW({schema:$,effect:{type:"preprocess",transform:W},typeName:q.ZodEffects,...Q0(X)})};class GW extends _0{_parse(W){if(this._getType(W)===u.undefined)return v1(void 0);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}GW.create=(W,$)=>{return new GW({innerType:W,typeName:q.ZodOptional,...Q0($)})};class Z2 extends _0{_parse(W){if(this._getType(W)===u.null)return v1(null);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}Z2.create=(W,$)=>{return new Z2({innerType:W,typeName:q.ZodNullable,...Q0($)})};class w$ extends _0{_parse(W){let{ctx:$}=this._processInputParams(W),X=$.data;if($.parsedType===u.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}w$.create=(W,$)=>{return new w$({innerType:W,typeName:q.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...Q0($)})};class U$ extends _0{_parse(W){let{ctx:$}=this._processInputParams(W),X={...$,common:{...$.common,issues:[]}},Y=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(FX(Y))return Y.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new YW(X.common.issues)},input:X.data})}});else return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new YW(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}U$.create=(W,$)=>{return new U$({innerType:W,typeName:q.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...Q0($)})};class KX extends _0{_parse(W){if(this._getType(W)!==u.nan){let X=this._getOrReturnCtx(W);return y(X,{code:S.invalid_type,expected:u.nan,received:X.parsedType}),X0}return{status:"valid",value:W.data}}}KX.create=(W)=>{return new KX({typeName:q.ZodNaN,...Q0(W)})};var iZ=Symbol("zod_brand");class d9 extends _0{_parse(W){let{ctx:$}=this._processInputParams(W),X=$.data;return this._def.type._parse({data:X,path:$.path,parent:$})}unwrap(){return this._def.type}}class AX extends _0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(G.status==="aborted")return X0;if(G.status==="dirty")return $.dirty(),e4(G.value);else return this._def.out._parseAsync({data:G.value,path:X.path,parent:X})})();else{let Y=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(Y.status==="aborted")return X0;if(Y.status==="dirty")return $.dirty(),{status:"dirty",value:Y.value};else return this._def.out._parseSync({data:Y.value,path:X.path,parent:X})}}static create(W,$){return new AX({in:W,out:$,typeName:q.ZodPipeline})}}class D$ extends _0{_parse(W){let $=this._def.innerType._parse(W),X=(Y)=>{if(g8(Y))Y.value=Object.freeze(Y.value);return Y};return FX($)?$.then((Y)=>X(Y)):X($)}unwrap(){return this._def.innerType}}D$.create=(W,$)=>{return new D$({innerType:W,typeName:q.ZodReadonly,...Q0($)})};var nZ={object:o0.lazycreate},q;(function(W){W.ZodString="ZodString",W.ZodNumber="ZodNumber",W.ZodNaN="ZodNaN",W.ZodBigInt="ZodBigInt",W.ZodBoolean="ZodBoolean",W.ZodDate="ZodDate",W.ZodSymbol="ZodSymbol",W.ZodUndefined="ZodUndefined",W.ZodNull="ZodNull",W.ZodAny="ZodAny",W.ZodUnknown="ZodUnknown",W.ZodNever="ZodNever",W.ZodVoid="ZodVoid",W.ZodArray="ZodArray",W.ZodObject="ZodObject",W.ZodUnion="ZodUnion",W.ZodDiscriminatedUnion="ZodDiscriminatedUnion",W.ZodIntersection="ZodIntersection",W.ZodTuple="ZodTuple",W.ZodRecord="ZodRecord",W.ZodMap="ZodMap",W.ZodSet="ZodSet",W.ZodFunction="ZodFunction",W.ZodLazy="ZodLazy",W.ZodLiteral="ZodLiteral",W.ZodEnum="ZodEnum",W.ZodEffects="ZodEffects",W.ZodNativeEnum="ZodNativeEnum",W.ZodOptional="ZodOptional",W.ZodNullable="ZodNullable",W.ZodDefault="ZodDefault",W.ZodCatch="ZodCatch",W.ZodPromise="ZodPromise",W.ZodBranded="ZodBranded",W.ZodPipeline="ZodPipeline",W.ZodReadonly="ZodReadonly"})(q||(q={}));var rZ=oW.create,tZ=m8.create,aZ=KX.create,sZ=p8.create,eZ=wX.create,WS=G$.create,$S=UX.create,XS=J$.create,YS=H$.create,GS=DX.create,JS=n2.create,HS=iW.create,QS=VX.create,zS=xW.create,TS=o0.create,FS=o0.strictCreate,_S=Q$.create,wS=c9.create,US=z$.create,DS=nW.create,VS=MX.create,MS=OX.create,OS=u8.create,KS=X$.create,AS=T$.create,ES=F$.create,LS=r2.create,BS=_$.create,RS=c8.create,NS=bW.create,ZS=GW.create,SS=Z2.create,qS=bW.createWithPreprocess,CS=AX.create;function sJ(){return{}}function eJ(W,$){let X={type:"array"};if(W.type?._def&&W.type?._def?.typeName!==q.ZodAny)X.items=W0(W.type._def,{...$,currentPath:[...$.currentPath,"items"]});if(W.minLength)O0(X,"minItems",W.minLength.value,W.minLength.message,$);if(W.maxLength)O0(X,"maxItems",W.maxLength.value,W.maxLength.message,$);if(W.exactLength)O0(X,"minItems",W.exactLength.value,W.exactLength.message,$),O0(X,"maxItems",W.exactLength.value,W.exactLength.message,$);return X}function W3(W,$){let X={type:"integer",format:"int64"};if(!W.checks)return X;for(let Y of W.checks)switch(Y.kind){case"min":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"minimum",Y.value,Y.message,$);else O0(X,"exclusiveMinimum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMinimum=!0;O0(X,"minimum",Y.value,Y.message,$)}break;case"max":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"maximum",Y.value,Y.message,$);else O0(X,"exclusiveMaximum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMaximum=!0;O0(X,"maximum",Y.value,Y.message,$)}break;case"multipleOf":O0(X,"multipleOf",Y.value,Y.message,$);break}return X}function $3(){return{type:"boolean"}}function EX(W,$){return W0(W.type._def,$)}var X3=(W,$)=>{return W0(W.innerType._def,$)};function l9(W,$,X){let Y=X??$.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((G,J)=>l9(W,$,G))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return FV(W,$)}}var FV=(W,$)=>{let X={type:"integer",format:"unix-time"};if($.target==="openApi3")return X;for(let Y of W.checks)switch(Y.kind){case"min":O0(X,"minimum",Y.value,Y.message,$);break;case"max":O0(X,"maximum",Y.value,Y.message,$);break}return X};function Y3(W,$){return{...W0(W.innerType._def,$),default:W.defaultValue()}}function G3(W,$){return $.effectStrategy==="input"?W0(W.schema._def,$):{}}function J3(W){return{type:"string",enum:Array.from(W.values)}}var _V=(W)=>{if("type"in W&&W.type==="string")return!1;return"allOf"in W};function H3(W,$){let X=[W0(W.left._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),W0(W.right._def,{...$,currentPath:[...$.currentPath,"allOf","1"]})].filter((J)=>!!J),Y=$.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,G=[];return X.forEach((J)=>{if(_V(J)){if(G.push(...J.allOf),J.unevaluatedProperties===void 0)Y=void 0}else{let H=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:Q,...z}=J;H=z}else Y=void 0;G.push(H)}}),G.length?{allOf:G,...Y}:void 0}function Q3(W,$){let X=typeof W.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(W.value)?"array":"object"};if($.target==="openApi3")return{type:X==="bigint"?"integer":X,enum:[W.value]};return{type:X==="bigint"?"integer":X,const:W.value}}var o9=void 0,AW={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(o9===void 0)o9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return o9},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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,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})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function LX(W,$){let X={type:"string"};if(W.checks)for(let Y of W.checks)switch(Y.kind){case"min":O0(X,"minLength",typeof X.minLength==="number"?Math.max(X.minLength,Y.value):Y.value,Y.message,$);break;case"max":O0(X,"maxLength",typeof X.maxLength==="number"?Math.min(X.maxLength,Y.value):Y.value,Y.message,$);break;case"email":switch($.emailStrategy){case"format:email":EW(X,"email",Y.message,$);break;case"format:idn-email":EW(X,"idn-email",Y.message,$);break;case"pattern:zod":k1(X,AW.email,Y.message,$);break}break;case"url":EW(X,"uri",Y.message,$);break;case"uuid":EW(X,"uuid",Y.message,$);break;case"regex":k1(X,Y.regex,Y.message,$);break;case"cuid":k1(X,AW.cuid,Y.message,$);break;case"cuid2":k1(X,AW.cuid2,Y.message,$);break;case"startsWith":k1(X,RegExp(`^${i9(Y.value,$)}`),Y.message,$);break;case"endsWith":k1(X,RegExp(`${i9(Y.value,$)}$`),Y.message,$);break;case"datetime":EW(X,"date-time",Y.message,$);break;case"date":EW(X,"date",Y.message,$);break;case"time":EW(X,"time",Y.message,$);break;case"duration":EW(X,"duration",Y.message,$);break;case"length":O0(X,"minLength",typeof X.minLength==="number"?Math.max(X.minLength,Y.value):Y.value,Y.message,$),O0(X,"maxLength",typeof X.maxLength==="number"?Math.min(X.maxLength,Y.value):Y.value,Y.message,$);break;case"includes":{k1(X,RegExp(i9(Y.value,$)),Y.message,$);break}case"ip":{if(Y.version!=="v6")EW(X,"ipv4",Y.message,$);if(Y.version!=="v4")EW(X,"ipv6",Y.message,$);break}case"base64url":k1(X,AW.base64url,Y.message,$);break;case"jwt":k1(X,AW.jwt,Y.message,$);break;case"cidr":{if(Y.version!=="v6")k1(X,AW.ipv4Cidr,Y.message,$);if(Y.version!=="v4")k1(X,AW.ipv6Cidr,Y.message,$);break}case"emoji":k1(X,AW.emoji(),Y.message,$);break;case"ulid":{k1(X,AW.ulid,Y.message,$);break}case"base64":{switch($.base64Strategy){case"format:binary":{EW(X,"binary",Y.message,$);break}case"contentEncoding:base64":{O0(X,"contentEncoding","base64",Y.message,$);break}case"pattern:zod":{k1(X,AW.base64,Y.message,$);break}}break}case"nanoid":k1(X,AW.nanoid,Y.message,$);case"toLowerCase":case"toUpperCase":case"trim":break;default:((G)=>{})(Y)}return X}function i9(W,$){return $.patternStrategy==="escape"?UV(W):W}var wV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function UV(W){let $="";for(let X=0;X<W.length;X++){if(!wV.has(W[X]))$+="\\";$+=W[X]}return $}function EW(W,$,X,Y){if(W.format||W.anyOf?.some((G)=>G.format)){if(!W.anyOf)W.anyOf=[];if(W.format){if(W.anyOf.push({format:W.format,...W.errorMessage&&Y.errorMessages&&{errorMessage:{format:W.errorMessage.format}}}),delete W.format,W.errorMessage){if(delete W.errorMessage.format,Object.keys(W.errorMessage).length===0)delete W.errorMessage}}W.anyOf.push({format:$,...X&&Y.errorMessages&&{errorMessage:{format:X}}})}else O0(W,"format",$,X,Y)}function k1(W,$,X,Y){if(W.pattern||W.allOf?.some((G)=>G.pattern)){if(!W.allOf)W.allOf=[];if(W.pattern){if(W.allOf.push({pattern:W.pattern,...W.errorMessage&&Y.errorMessages&&{errorMessage:{pattern:W.errorMessage.pattern}}}),delete W.pattern,W.errorMessage){if(delete W.errorMessage.pattern,Object.keys(W.errorMessage).length===0)delete W.errorMessage}}W.allOf.push({pattern:z3($,Y),...X&&Y.errorMessages&&{errorMessage:{pattern:X}}})}else O0(W,"pattern",z3($,Y),X,Y)}function z3(W,$){if(!$.applyRegexFlags||!W.flags)return W.source;let X={i:W.flags.includes("i"),m:W.flags.includes("m"),s:W.flags.includes("s")},Y=X.i?W.source.toLowerCase():W.source,G="",J=!1,H=!1,Q=!1;for(let z=0;z<Y.length;z++){if(J){G+=Y[z],J=!1;continue}if(X.i){if(H){if(Y[z].match(/[a-z]/)){if(Q)G+=Y[z],G+=`${Y[z-2]}-${Y[z]}`.toUpperCase(),Q=!1;else if(Y[z+1]==="-"&&Y[z+2]?.match(/[a-z]/))G+=Y[z],Q=!0;else G+=`${Y[z]}${Y[z].toUpperCase()}`;continue}}else if(Y[z].match(/[a-z]/)){G+=`[${Y[z]}${Y[z].toUpperCase()}]`;continue}}if(X.m){if(Y[z]==="^"){G+=`(^|(?<=[\r
6
+ ]))`;continue}else if(Y[z]==="$"){G+=`($|(?=[\r
7
+ ]))`;continue}}if(X.s&&Y[z]==="."){G+=H?`${Y[z]}\r
8
8
  `:`[${Y[z]}\r
9
- ]`;continue}if(J+=Y[z],Y[z]==="\\")G=!0;else if(H&&Y[z]==="]")H=!1;else if(!H&&Y[z]==="[")H=!0}try{new RegExp(J)}catch{return console.warn(`Could not convert regex pattern at ${$.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),W.source}return J}function BX(W,$){if($.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if($.target==="openApi3"&&W.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:W.keyType._def.values,properties:W.keyType._def.values.reduce((Y,J)=>({...Y,[J]:e(W.valueType._def,{...$,currentPath:[...$.currentPath,"properties",J]})??{}}),{}),additionalProperties:$.rejectedAdditionalProperties};let X={type:"object",additionalProperties:e(W.valueType._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]})??$.allowedAdditionalProperties};if($.target==="openApi3")return X;if(W.keyType?._def.typeName===S.ZodString&&W.keyType._def.checks?.length){let{type:Y,...J}=LX(W.keyType._def,$);return{...X,propertyNames:J}}else if(W.keyType?._def.typeName===S.ZodEnum)return{...X,propertyNames:{enum:W.keyType._def.values}};else if(W.keyType?._def.typeName===S.ZodBranded&&W.keyType._def.type._def.typeName===S.ZodString&&W.keyType._def.type._def.checks?.length){let{type:Y,...J}=EX(W.keyType._def,$);return{...X,propertyNames:J}}return X}function Q3(W,$){if($.mapStrategy==="record")return BX(W,$);let X=e(W.keyType._def,{...$,currentPath:[...$.currentPath,"items","items","0"]})||{},Y=e(W.valueType._def,{...$,currentPath:[...$.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[X,Y],minItems:2,maxItems:2}}}function z3(W){let $=W.values,Y=Object.keys(W.values).filter((G)=>{return typeof $[$[G]]!=="number"}).map((G)=>$[G]),J=Array.from(new Set(Y.map((G)=>typeof G)));return{type:J.length===1?J[0]==="string"?"string":"number":["string","number"],enum:Y}}function F3(){return{not:{}}}function T3(W){return W.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var _4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function w3(W,$){if($.target==="openApi3")return U3(W,$);let X=W.options instanceof Map?Array.from(W.options.values()):W.options;if(X.every((Y)=>(Y._def.typeName in _4)&&(!Y._def.checks||!Y._def.checks.length))){let Y=X.reduce((J,G)=>{let H=_4[G._def.typeName];return H&&!J.includes(H)?[...J,H]:J},[]);return{type:Y.length>1?Y:Y[0]}}else if(X.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=X.reduce((J,G)=>{let H=typeof G._def.value;switch(H){case"string":case"number":case"boolean":return[...J,H];case"bigint":return[...J,"integer"];case"object":if(G._def.value===null)return[...J,"null"];case"symbol":case"undefined":case"function":default:return J}},[]);if(Y.length===X.length){let J=Y.filter((G,H,Q)=>Q.indexOf(G)===H);return{type:J.length>1?J:J[0],enum:X.reduce((G,H)=>{return G.includes(H._def.value)?G:[...G,H._def.value]},[])}}}else if(X.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce((Y,J)=>[...Y,...J._def.values.filter((G)=>!Y.includes(G))],[])};return U3(W,$)}var U3=(W,$)=>{let X=(W.options instanceof Map?Array.from(W.options.values()):W.options).map((Y,J)=>e(Y._def,{...$,currentPath:[...$.currentPath,"anyOf",`${J}`]})).filter((Y)=>!!Y&&(!$.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return X.length?{anyOf:X}:void 0};function _3(W,$){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(W.innerType._def.typeName)&&(!W.innerType._def.checks||!W.innerType._def.checks.length)){if($.target==="openApi3")return{type:_4[W.innerType._def.typeName],nullable:!0};return{type:[_4[W.innerType._def.typeName],"null"]}}if($.target==="openApi3"){let Y=e(W.innerType._def,{...$,currentPath:[...$.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let X=e(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function D3(W,$){let X={type:"number"};if(!W.checks)return X;for(let Y of W.checks)switch(Y.kind){case"int":X.type="integer",b9(X,"type",Y.message,$);break;case"min":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"minimum",Y.value,Y.message,$);else O0(X,"exclusiveMinimum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMinimum=!0;O0(X,"minimum",Y.value,Y.message,$)}break;case"max":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"maximum",Y.value,Y.message,$);else O0(X,"exclusiveMaximum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMaximum=!0;O0(X,"maximum",Y.value,Y.message,$)}break;case"multipleOf":O0(X,"multipleOf",Y.value,Y.message,$);break}return X}function M3(W,$){let X=$.target==="openAi",Y={type:"object",properties:{}},J=[],G=W.shape();for(let Q in G){let z=G[Q];if(z===void 0||z._def===void 0)continue;let F=_M(z);if(F&&X){if(z instanceof YW)z=z._def.innerType;if(!z.isNullable())z=z.nullable();F=!1}let T=e(z._def,{...$,currentPath:[...$.currentPath,"properties",Q],propertyPath:[...$.currentPath,"properties",Q]});if(T===void 0)continue;if(Y.properties[Q]=T,!F)J.push(Q)}if(J.length)Y.required=J;let H=wM(W,$);if(H!==void 0)Y.additionalProperties=H;return Y}function wM(W,$){if(W.catchall._def.typeName!=="ZodNever")return e(W.catchall._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]});switch(W.unknownKeys){case"passthrough":return $.allowedAdditionalProperties;case"strict":return $.rejectedAdditionalProperties;case"strip":return $.removeAdditionalStrategy==="strict"?$.allowedAdditionalProperties:$.rejectedAdditionalProperties}}function _M(W){try{return W.isOptional()}catch{return!0}}var V3=(W,$)=>{if($.currentPath.toString()===$.propertyPath?.toString())return e(W.innerType._def,$);let X=e(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","1"]});return X?{anyOf:[{not:{}},X]}:{}};var O3=(W,$)=>{if($.pipeStrategy==="input")return e(W.in._def,$);else if($.pipeStrategy==="output")return e(W.out._def,$);let X=e(W.in._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),Y=e(W.out._def,{...$,currentPath:[...$.currentPath,"allOf",X?"1":"0"]});return{allOf:[X,Y].filter((J)=>J!==void 0)}};function K3(W,$){return e(W.type._def,$)}function A3(W,$){let Y={type:"array",uniqueItems:!0,items:e(W.valueType._def,{...$,currentPath:[...$.currentPath,"items"]})};if(W.minSize)O0(Y,"minItems",W.minSize.value,W.minSize.message,$);if(W.maxSize)O0(Y,"maxItems",W.maxSize.value,W.maxSize.message,$);return Y}function E3(W,$){if(W.rest)return{type:"array",minItems:W.items.length,items:W.items.map((X,Y)=>e(X._def,{...$,currentPath:[...$.currentPath,"items",`${Y}`]})).reduce((X,Y)=>Y===void 0?X:[...X,Y],[]),additionalItems:e(W.rest._def,{...$,currentPath:[...$.currentPath,"additionalItems"]})};else return{type:"array",minItems:W.items.length,maxItems:W.items.length,items:W.items.map((X,Y)=>e(X._def,{...$,currentPath:[...$.currentPath,"items",`${Y}`]})).reduce((X,Y)=>Y===void 0?X:[...X,Y],[])}}function L3(){return{not:{}}}function B3(){return{}}var R3=(W,$)=>{return e(W.innerType._def,$)};var N3=(W,$,X)=>{switch($){case S.ZodString:return LX(W,X);case S.ZodNumber:return D3(W,X);case S.ZodObject:return M3(W,X);case S.ZodBigInt:return sG(W,X);case S.ZodBoolean:return eG();case S.ZodDate:return c9(W,X);case S.ZodUndefined:return L3();case S.ZodNull:return T3(X);case S.ZodArray:return aG(W,X);case S.ZodUnion:case S.ZodDiscriminatedUnion:return w3(W,X);case S.ZodIntersection:return J3(W,X);case S.ZodTuple:return E3(W,X);case S.ZodRecord:return BX(W,X);case S.ZodLiteral:return G3(W,X);case S.ZodEnum:return Y3(W);case S.ZodNativeEnum:return z3(W);case S.ZodNullable:return _3(W,X);case S.ZodOptional:return V3(W,X);case S.ZodMap:return Q3(W,X);case S.ZodSet:return A3(W,X);case S.ZodLazy:return()=>W.getter()._def;case S.ZodPromise:return K3(W,X);case S.ZodNaN:case S.ZodNever:return F3();case S.ZodEffects:return X3(W,X);case S.ZodAny:return tG();case S.ZodUnknown:return B3();case S.ZodDefault:return $3(W,X);case S.ZodBranded:return EX(W,X);case S.ZodReadonly:return R3(W,X);case S.ZodCatch:return W3(W,X);case S.ZodPipeline:return O3(W,X);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return((Y)=>{return})($)}};function e(W,$,X=!1){let Y=$.seen.get(W);if($.override){let Q=$.override?.(W,$,Y,X);if(Q!==gG)return Q}if(Y&&!X){let Q=DM(Y,$);if(Q!==void 0)return Q}let J={def:W,path:$.currentPath,jsonSchema:void 0};$.seen.set(W,J);let G=N3(W,W.typeName,$),H=typeof G==="function"?e(G(),$):G;if(H)VM(W,$,H);if($.postProcess){let Q=$.postProcess(H,W,$);return J.jsonSchema=H,Q}return J.jsonSchema=H,H}var DM=(W,$)=>{switch($.$refStrategy){case"root":return{$ref:W.path.join("/")};case"relative":return{$ref:MM($.currentPath,W.path)};case"none":case"seen":{if(W.path.length<$.currentPath.length&&W.path.every((X,Y)=>$.currentPath[Y]===X))return console.warn(`Recursive reference detected at ${$.currentPath.join("/")}! Defaulting to any`),{};return $.$refStrategy==="seen"?{}:void 0}}},MM=(W,$)=>{let X=0;for(;X<W.length&&X<$.length;X++)if(W[X]!==$[X])break;return[(W.length-X).toString(),...$.slice(X)].join("/")},VM=(W,$,X)=>{if(W.description){if(X.description=W.description,$.markdownDescription)X.markdownDescription=W.description}return X};var Z3=(W,$)=>{let X=pG($),Y=typeof $==="object"&&$.definitions?Object.entries($.definitions).reduce((z,[F,T])=>({...z,[F]:e(T._def,{...X,currentPath:[...X.basePath,X.definitionPath,F]},!0)??{}}),{}):void 0,J=typeof $==="string"?$:$?.nameStrategy==="title"?void 0:$?.name,G=e(W._def,J===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,J]},!1)??{},H=typeof $==="object"&&$.name!==void 0&&$.nameStrategy==="title"?$.name:void 0;if(H!==void 0)G.title=H;let Q=J===void 0?Y?{...G,[X.definitionPath]:Y}:G:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,J].join("/"),[X.definitionPath]:{...Y,[J]:G}};if(X.target==="jsonSchema7")Q.$schema="http://json-schema.org/draft-07/schema#";else if(X.target==="jsonSchema2019-09"||X.target==="openAi")Q.$schema="https://json-schema.org/draft/2019-09/schema#";if(X.target==="openAi"&&(("anyOf"in Q)||("oneOf"in Q)||("allOf"in Q)||("type"in Q)&&Array.isArray(Q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return Q};var S3=Z3;function q3(W,$){return function X({schema:Y,fallback:J,toJsonSchema:G=S3}){let H=G(Y);return async function Q(z,F=3){let T,U=[];while(U.length<F){T=await W(z,H,J,U);let _=await Y["~standard"].validate(T);if("value"in _)return _.value;$?.warn(`safegen failed to generate well-formed data.
9
+ ]`;continue}if(G+=Y[z],Y[z]==="\\")J=!0;else if(H&&Y[z]==="]")H=!1;else if(!H&&Y[z]==="[")H=!0}try{new RegExp(G)}catch{return console.warn(`Could not convert regex pattern at ${$.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),W.source}return G}function BX(W,$){if($.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if($.target==="openApi3"&&W.keyType?._def.typeName===q.ZodEnum)return{type:"object",required:W.keyType._def.values,properties:W.keyType._def.values.reduce((Y,G)=>({...Y,[G]:W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"properties",G]})??{}}),{}),additionalProperties:$.rejectedAdditionalProperties};let X={type:"object",additionalProperties:W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]})??$.allowedAdditionalProperties};if($.target==="openApi3")return X;if(W.keyType?._def.typeName===q.ZodString&&W.keyType._def.checks?.length){let{type:Y,...G}=LX(W.keyType._def,$);return{...X,propertyNames:G}}else if(W.keyType?._def.typeName===q.ZodEnum)return{...X,propertyNames:{enum:W.keyType._def.values}};else if(W.keyType?._def.typeName===q.ZodBranded&&W.keyType._def.type._def.typeName===q.ZodString&&W.keyType._def.type._def.checks?.length){let{type:Y,...G}=EX(W.keyType._def,$);return{...X,propertyNames:G}}return X}function T3(W,$){if($.mapStrategy==="record")return BX(W,$);let X=W0(W.keyType._def,{...$,currentPath:[...$.currentPath,"items","items","0"]})||{},Y=W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[X,Y],minItems:2,maxItems:2}}}function F3(W){let $=W.values,Y=Object.keys(W.values).filter((J)=>{return typeof $[$[J]]!=="number"}).map((J)=>$[J]),G=Array.from(new Set(Y.map((J)=>typeof J)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:Y}}function _3(){return{not:{}}}function w3(W){return W.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var V$={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function D3(W,$){if($.target==="openApi3")return U3(W,$);let X=W.options instanceof Map?Array.from(W.options.values()):W.options;if(X.every((Y)=>(Y._def.typeName in V$)&&(!Y._def.checks||!Y._def.checks.length))){let Y=X.reduce((G,J)=>{let H=V$[J._def.typeName];return H&&!G.includes(H)?[...G,H]:G},[]);return{type:Y.length>1?Y:Y[0]}}else if(X.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=X.reduce((G,J)=>{let H=typeof J._def.value;switch(H){case"string":case"number":case"boolean":return[...G,H];case"bigint":return[...G,"integer"];case"object":if(J._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(Y.length===X.length){let G=Y.filter((J,H,Q)=>Q.indexOf(J)===H);return{type:G.length>1?G:G[0],enum:X.reduce((J,H)=>{return J.includes(H._def.value)?J:[...J,H._def.value]},[])}}}else if(X.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce((Y,G)=>[...Y,...G._def.values.filter((J)=>!Y.includes(J))],[])};return U3(W,$)}var U3=(W,$)=>{let X=(W.options instanceof Map?Array.from(W.options.values()):W.options).map((Y,G)=>W0(Y._def,{...$,currentPath:[...$.currentPath,"anyOf",`${G}`]})).filter((Y)=>!!Y&&(!$.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return X.length?{anyOf:X}:void 0};function V3(W,$){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(W.innerType._def.typeName)&&(!W.innerType._def.checks||!W.innerType._def.checks.length)){if($.target==="openApi3")return{type:V$[W.innerType._def.typeName],nullable:!0};return{type:[V$[W.innerType._def.typeName],"null"]}}if($.target==="openApi3"){let Y=W0(W.innerType._def,{...$,currentPath:[...$.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let X=W0(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function M3(W,$){let X={type:"number"};if(!W.checks)return X;for(let Y of W.checks)switch(Y.kind){case"int":X.type="integer",h9(X,"type",Y.message,$);break;case"min":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"minimum",Y.value,Y.message,$);else O0(X,"exclusiveMinimum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMinimum=!0;O0(X,"minimum",Y.value,Y.message,$)}break;case"max":if($.target==="jsonSchema7")if(Y.inclusive)O0(X,"maximum",Y.value,Y.message,$);else O0(X,"exclusiveMaximum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMaximum=!0;O0(X,"maximum",Y.value,Y.message,$)}break;case"multipleOf":O0(X,"multipleOf",Y.value,Y.message,$);break}return X}function O3(W,$){let X=$.target==="openAi",Y={type:"object",properties:{}},G=[],J=W.shape();for(let Q in J){let z=J[Q];if(z===void 0||z._def===void 0)continue;let T=VV(z);if(T&&X){if(z instanceof GW)z=z._def.innerType;if(!z.isNullable())z=z.nullable();T=!1}let F=W0(z._def,{...$,currentPath:[...$.currentPath,"properties",Q],propertyPath:[...$.currentPath,"properties",Q]});if(F===void 0)continue;if(Y.properties[Q]=F,!T)G.push(Q)}if(G.length)Y.required=G;let H=DV(W,$);if(H!==void 0)Y.additionalProperties=H;return Y}function DV(W,$){if(W.catchall._def.typeName!=="ZodNever")return W0(W.catchall._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]});switch(W.unknownKeys){case"passthrough":return $.allowedAdditionalProperties;case"strict":return $.rejectedAdditionalProperties;case"strip":return $.removeAdditionalStrategy==="strict"?$.allowedAdditionalProperties:$.rejectedAdditionalProperties}}function VV(W){try{return W.isOptional()}catch{return!0}}var K3=(W,$)=>{if($.currentPath.toString()===$.propertyPath?.toString())return W0(W.innerType._def,$);let X=W0(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","1"]});return X?{anyOf:[{not:{}},X]}:{}};var A3=(W,$)=>{if($.pipeStrategy==="input")return W0(W.in._def,$);else if($.pipeStrategy==="output")return W0(W.out._def,$);let X=W0(W.in._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),Y=W0(W.out._def,{...$,currentPath:[...$.currentPath,"allOf",X?"1":"0"]});return{allOf:[X,Y].filter((G)=>G!==void 0)}};function E3(W,$){return W0(W.type._def,$)}function L3(W,$){let Y={type:"array",uniqueItems:!0,items:W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"items"]})};if(W.minSize)O0(Y,"minItems",W.minSize.value,W.minSize.message,$);if(W.maxSize)O0(Y,"maxItems",W.maxSize.value,W.maxSize.message,$);return Y}function B3(W,$){if(W.rest)return{type:"array",minItems:W.items.length,items:W.items.map((X,Y)=>W0(X._def,{...$,currentPath:[...$.currentPath,"items",`${Y}`]})).reduce((X,Y)=>Y===void 0?X:[...X,Y],[]),additionalItems:W0(W.rest._def,{...$,currentPath:[...$.currentPath,"additionalItems"]})};else return{type:"array",minItems:W.items.length,maxItems:W.items.length,items:W.items.map((X,Y)=>W0(X._def,{...$,currentPath:[...$.currentPath,"items",`${Y}`]})).reduce((X,Y)=>Y===void 0?X:[...X,Y],[])}}function R3(){return{not:{}}}function N3(){return{}}var Z3=(W,$)=>{return W0(W.innerType._def,$)};var S3=(W,$,X)=>{switch($){case q.ZodString:return LX(W,X);case q.ZodNumber:return M3(W,X);case q.ZodObject:return O3(W,X);case q.ZodBigInt:return W3(W,X);case q.ZodBoolean:return $3();case q.ZodDate:return l9(W,X);case q.ZodUndefined:return R3();case q.ZodNull:return w3(X);case q.ZodArray:return eJ(W,X);case q.ZodUnion:case q.ZodDiscriminatedUnion:return D3(W,X);case q.ZodIntersection:return H3(W,X);case q.ZodTuple:return B3(W,X);case q.ZodRecord:return BX(W,X);case q.ZodLiteral:return Q3(W,X);case q.ZodEnum:return J3(W);case q.ZodNativeEnum:return F3(W);case q.ZodNullable:return V3(W,X);case q.ZodOptional:return K3(W,X);case q.ZodMap:return T3(W,X);case q.ZodSet:return L3(W,X);case q.ZodLazy:return()=>W.getter()._def;case q.ZodPromise:return E3(W,X);case q.ZodNaN:case q.ZodNever:return _3();case q.ZodEffects:return G3(W,X);case q.ZodAny:return sJ();case q.ZodUnknown:return N3();case q.ZodDefault:return Y3(W,X);case q.ZodBranded:return EX(W,X);case q.ZodReadonly:return Z3(W,X);case q.ZodCatch:return X3(W,X);case q.ZodPipeline:return A3(W,X);case q.ZodFunction:case q.ZodVoid:case q.ZodSymbol:return;default:return((Y)=>{return})($)}};function W0(W,$,X=!1){let Y=$.seen.get(W);if($.override){let Q=$.override?.(W,$,Y,X);if(Q!==pJ)return Q}if(Y&&!X){let Q=MV(Y,$);if(Q!==void 0)return Q}let G={def:W,path:$.currentPath,jsonSchema:void 0};$.seen.set(W,G);let J=S3(W,W.typeName,$),H=typeof J==="function"?W0(J(),$):J;if(H)KV(W,$,H);if($.postProcess){let Q=$.postProcess(H,W,$);return G.jsonSchema=H,Q}return G.jsonSchema=H,H}var MV=(W,$)=>{switch($.$refStrategy){case"root":return{$ref:W.path.join("/")};case"relative":return{$ref:OV($.currentPath,W.path)};case"none":case"seen":{if(W.path.length<$.currentPath.length&&W.path.every((X,Y)=>$.currentPath[Y]===X))return console.warn(`Recursive reference detected at ${$.currentPath.join("/")}! Defaulting to any`),{};return $.$refStrategy==="seen"?{}:void 0}}},OV=(W,$)=>{let X=0;for(;X<W.length&&X<$.length;X++)if(W[X]!==$[X])break;return[(W.length-X).toString(),...$.slice(X)].join("/")},KV=(W,$,X)=>{if(W.description){if(X.description=W.description,$.markdownDescription)X.markdownDescription=W.description}return X};var q3=(W,$)=>{let X=cJ($),Y=typeof $==="object"&&$.definitions?Object.entries($.definitions).reduce((z,[T,F])=>({...z,[T]:W0(F._def,{...X,currentPath:[...X.basePath,X.definitionPath,T]},!0)??{}}),{}):void 0,G=typeof $==="string"?$:$?.nameStrategy==="title"?void 0:$?.name,J=W0(W._def,G===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,G]},!1)??{},H=typeof $==="object"&&$.name!==void 0&&$.nameStrategy==="title"?$.name:void 0;if(H!==void 0)J.title=H;let Q=G===void 0?Y?{...J,[X.definitionPath]:Y}:J:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,G].join("/"),[X.definitionPath]:{...Y,[G]:J}};if(X.target==="jsonSchema7")Q.$schema="http://json-schema.org/draft-07/schema#";else if(X.target==="jsonSchema2019-09"||X.target==="openAi")Q.$schema="https://json-schema.org/draft/2019-09/schema#";if(X.target==="openAi"&&(("anyOf"in Q)||("oneOf"in Q)||("allOf"in Q)||("type"in Q)&&Array.isArray(Q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return Q};var C3=q3;function k3(W,$){return function X({schema:Y,fallback:G,toJsonSchema:J=C3}){let H=J(Y);return async function Q(z,T=3){let F,_=[];while(_.length<T){F=await W(z,H,G,_);let w=await Y["~standard"].validate(F);if("value"in w)return w.value;$?.warn(`safegen failed to generate well-formed data.
10
10
  `,`Here's what was returned last time:
11
- `,JSON.stringify(T,null,"\t"),`
11
+ `,JSON.stringify(F,null,"\t"),`
12
12
  `,`Here are the issues returned from our validation:
13
- `,JSON.stringify(_.issues,null,"\t")),U.push({response:T,error:_})}return $?.error(`safegen was unable to generate well-formed data after ${F} failed attempts.`),J}}}function C3(W){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(W,null,2)].join(`
14
- `)}var y3=fD(I3(),1);import*as b1 from"fs";import*as u8 from"path";import{resolve as BM}from"path";import{createHash as RM}from"crypto";import{copyFile as NM}from"fs/promises";import{existsSync as o9,mkdirSync as f3,readFileSync as EM,readdirSync as P3,rmSync as x3,statSync as v3,writeFileSync as LM}from"fs";import{resolve as i9}from"path";var b3=class{rootDir;get initialized(){return o9(this.rootDir)}initialize(){if(!this.initialized)f3(this.rootDir,{recursive:!0})}constructor(W){if(this.rootDir=W.path,W.eagerInit)this.initialize()}getItem(W){let $=i9(this.rootDir,W);if(o9($))return EM($,"utf-8");return null}setItem(W,$){this.initialize();let X=i9(this.rootDir,W);LM(X,$)}removeItem(W){let $=i9(this.rootDir,W);if(o9($))this.initialize(),x3($)}key(W){return P3(this.rootDir).sort((Y,J)=>{let G=v3(Y);return v3(J).ctimeMs-G.ctimeMs})[W]??null}clear(){x3(this.rootDir,{recursive:!0}),f3(this.rootDir,{recursive:!0})}get length(){return P3(this.rootDir).length}};var h3=/[^a-zA-Z0-9\-._]/g;function O4(W,$=64){if($%2===1)$+=1;let X=W.replace(h3,"-");if(X.length<=$)return X;let Y=RM("sha256").update(W).digest("base64").slice(0,8).replace("/","_"),J=X;if(J.length>$){let G=J.slice(0,$/2),H=J.slice(-$/2);J=G+"_"+H}return J+"+"+Y}var ZM=y3.default("varmint"),V4=O4(process.cwd(),150),n9=BM(ZM,V4),X1="_-$-_-$-_",g3=`file${X1}`,m3=`list${X1}`,p3=`root${X1}`,SM=`unmatched${X1}`,f0={storage:new b3({path:n9,eagerInit:!1}),startGlobalTracking(){if(console.log(`\uD83D\uDC3F\uFE0F Starting global tracking of varmint files using project identifier "${V4}"`),f0.storage.initialized)console.error(`\uD83D\uDCA5 The global cache for the project "${V4}" was found already initialized. Clearing it and starting fresh.`),f0.storage.clear();f0.storage.initialize()},async prepareUploads(W){console.log(`\uD83D\uDC3F\uFE0F Moving unmatched inputs to /tmp/varmint-uploads using project identifier "${V4}"`);let $=[];for(let X of b1.readdirSync(f0.storage.rootDir))if(RX(`unmatched${X1}`,X))$.push(X);if($.length===0){console.log("\uD83D\uDC3F\uFE0F ","No unmatched input files found.");return}if(console.log("\uD83D\uDC3F\uFE0F ","Found the following unmatched files:",`
13
+ `,JSON.stringify(w.issues,null,"\t")),_.push({response:F,error:w})}return $?.error(`safegen was unable to generate well-formed data after ${T} failed attempts.`),G}}}function j3(W){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(W,null,2)].join(`
14
+ `)}var g3=xD(f3(),1);import*as y1 from"fs";import*as d8 from"path";import{resolve as NV}from"path";import{createHash as ZV}from"crypto";import{copyFile as SV}from"fs/promises";import{existsSync as n9,mkdirSync as x3,readFileSync as BV,readdirSync as b3,rmSync as v3,statSync as y3,writeFileSync as RV}from"fs";import{resolve as r9}from"path";var h3=class{rootDir;get initialized(){return n9(this.rootDir)}initialize(){if(!this.initialized)x3(this.rootDir,{recursive:!0})}constructor(W){if(this.rootDir=W.path,W.eagerInit)this.initialize()}getItem(W){let $=r9(this.rootDir,W);if(n9($))return BV($,"utf-8");return null}setItem(W,$){this.initialize();let X=r9(this.rootDir,W);RV(X,$)}removeItem(W){let $=r9(this.rootDir,W);if(n9($))this.initialize(),v3($)}key(W){return b3(this.rootDir).sort((Y,G)=>{let J=y3(Y);return y3(G).ctimeMs-J.ctimeMs})[W]??null}clear(){v3(this.rootDir,{recursive:!0}),x3(this.rootDir,{recursive:!0})}get length(){return b3(this.rootDir).length}};var m3=/[^a-zA-Z0-9\-._]/g;function A$(W,$=64){if($%2===1)$+=1;let X=W.replace(m3,"-");if(X.length<=$)return X;let Y=ZV("sha256").update(W).digest("base64").slice(0,8).replace("/","_"),G=X;if(G.length>$){let J=G.slice(0,$/2),H=G.slice(-$/2);G=J+"_"+H}return G+"+"+Y}var qV=g3.default("varmint"),K$=A$(process.cwd(),150),t9=NV(qV,K$),X1="_-$-_-$-_",p3=`file${X1}`,u3=`list${X1}`,c3=`root${X1}`,CV=`unmatched${X1}`,P0={storage:new h3({path:t9,eagerInit:!1}),startGlobalTracking(){if(console.log(`\uD83D\uDC3F\uFE0F Starting global tracking of varmint files using project identifier "${K$}"`),P0.storage.initialized)console.error(`\uD83D\uDCA5 The global cache for the project "${K$}" was found already initialized. Clearing it and starting fresh.`),P0.storage.clear();P0.storage.initialize()},async prepareUploads(W){console.log(`\uD83D\uDC3F\uFE0F Moving unmatched inputs to /tmp/varmint-uploads using project identifier "${K$}"`);let $=[];for(let X of y1.readdirSync(P0.storage.rootDir))if(RX(`unmatched${X1}`,X))$.push(X);if($.length===0){console.log("\uD83D\uDC3F\uFE0F ","No unmatched input files found.");return}if(console.log("\uD83D\uDC3F\uFE0F ","Found the following unmatched files:",`
15
15
  - ${$.join(`
16
16
  `)}
17
17
  `,`in root folder:
18
- `,n9),process.env[W])b1.mkdirSync("/tmp/varmint-uploads",{recursive:!0}),await Promise.all($.map(async(X)=>{let Y=u8.join(n9,X),J=u8.join("/tmp/varmint-uploads",X);await NM(Y,J)}));else console.warn("\uD83D\uDCA5 Skipping artifact upload because process.env.CI is not set.")},endGlobalTrackingAndFlushUnusedFiles(){if(console.log(`\uD83D\uDC3F\uFE0F Ending global tracking of varmint files using project identifier "${V4}" and starting cleanup of untouched files.`),!f0.storage.initialized){console.error("\uD83D\uDCA5 called flushGlobal, but the global cache wasn't initialized with startGlobalTracking");return}let W=b1.readdirSync(f0.storage.rootDir),$=new Map,X=[],Y=[],J=[];for(let H of W)if(RX(`root${X1}`,H))X.push(H);else if(RX(`list${X1}`,H))Y.push(H);else if(RX(`file${X1}`,H))J.push(H);if(f0.storage.getItem("DID_CACHE_MISS"))console.log("\uD83D\uDC3F\uFE0F ","Cache miss detected. Since this likely prevented the cache from being fully utilized, we will not attempt to flush unused files.");else{let H=new Map;for(let Q of X){let z=Q.replace(p3,"");H.set(z,new Map);let F=f0.storage.getItem(Q);if(F)$.set(z,F);else console.error(`\uD83D\uDCA5 Could not find folder ${F} referenced in the global cache`)}for(let Q of Y){let z=Q.replace(m3,""),[F,T]=z.split(X1),U=H.get(F);if(U)U.set(T,new Set);else console.error(`\uD83D\uDCA5 Could not find root ${F} for list ${T}`)}for(let Q of J){let z=Q.replace(g3,""),[F,T,U]=z.split(X1),_=H.get(F);if(_){let V=_.get(T);if(V)V.add(U);else console.error(`\uD83D\uDCA5 Could not find list ${T} for file ${z}`)}else console.error(`\uD83D\uDCA5 Could not find root ${F} for file ${z}`)}console.log("\uD83D\uDC3F\uFE0F ",H);for(let[Q,z]of H.entries()){let F=$.get(Q);if(!F){console.error(`\uD83D\uDCA5 Could not find root ${Q}`);continue}if(!b1.existsSync(F)){console.warn(`\uD83D\uDCA5 Root folder ${F}, identified as being used during tracking, no longer exists during cleanup.`);continue}let U=b1.readdirSync(F);for(let _ of U)if(_!==".ferret"&&!z.has(_)){let V=u8.join(F,_);console.log(`\uD83E\uDDF9 globalFlush: removing directory ${V}`),b1.rmSync(V,{recursive:!0})}for(let[_,V]of z.entries()){let K=u8.join(F,_);if(!b1.existsSync(K)){console.warn(`\uD83D\uDCA5 List folder ${K}, identified as being used during tracking, no longer exists.`);continue}let I=b1.readdirSync(K);for(let C of I){let R=C.replace(".input.json","").replace(".output.json","").replace(".stream.txt","");if(!V.has(R)){let q=u8.join(K,C);console.log(`\uD83E\uDDF9 globalFlush: removing file ${q}`),b1.rmSync(q)}}}}}b1.rmSync(f0.storage.rootDir,{recursive:!0})}};function RX(W,$){return $.startsWith(W)}import*as i0 from"fs";import*as EW from"path";import{inspect as u3}from"util";var c3=class{filenameCache=new Map;filesTouched=new Map;mode;baseDir;rootName;constructor(W="off",$=EW.join(process.cwd(),".varmint")){if(this.mode=W,this.baseDir=$,this.rootName=O4(this.baseDir),f0.storage.initialized&&!f0.storage.getItem(`root${X1}${this.rootName}`))f0.storage.setItem(`root${X1}${this.rootName}`,this.baseDir)}read(W,$,X){let Y=EW.join(this.baseDir,W),J=`${$}.input.json`,G=EW.join(Y,J);if(!i0.existsSync(G)){if(!i0.existsSync(Y)){if(f0.storage.initialized&&this.mode==="read")f0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${W}" with "${$}" was not found. Directory "${Y}" does not exist.`)}let U=i0.readdirSync(Y).map((K)=>[K,i0.readFileSync(EW.join(Y,K),"utf-8")]).filter(([K])=>K.endsWith(".input.json")),_=[];for(let[K,B]of U){let I=` ${K}`,C=` ${u3(JSON.parse(B),{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
18
+ `,t9),process.env[W])y1.mkdirSync("/tmp/varmint-uploads",{recursive:!0}),await Promise.all($.map(async(X)=>{let Y=d8.join(t9,X),G=d8.join("/tmp/varmint-uploads",X);await SV(Y,G)}));else console.warn("\uD83D\uDCA5 Skipping artifact upload because process.env.CI is not set.")},endGlobalTrackingAndFlushUnusedFiles(){if(console.log(`\uD83D\uDC3F\uFE0F Ending global tracking of varmint files using project identifier "${K$}" and starting cleanup of untouched files.`),!P0.storage.initialized){console.error("\uD83D\uDCA5 called flushGlobal, but the global cache wasn't initialized with startGlobalTracking");return}let W=y1.readdirSync(P0.storage.rootDir),$=new Map,X=[],Y=[],G=[];for(let H of W)if(RX(`root${X1}`,H))X.push(H);else if(RX(`list${X1}`,H))Y.push(H);else if(RX(`file${X1}`,H))G.push(H);if(P0.storage.getItem("DID_CACHE_MISS"))console.log("\uD83D\uDC3F\uFE0F ","Cache miss detected. Since this likely prevented the cache from being fully utilized, we will not attempt to flush unused files.");else{let H=new Map;for(let Q of X){let z=Q.replace(c3,"");H.set(z,new Map);let T=P0.storage.getItem(Q);if(T)$.set(z,T);else console.error(`\uD83D\uDCA5 Could not find folder ${T} referenced in the global cache`)}for(let Q of Y){let z=Q.replace(u3,""),[T,F]=z.split(X1),_=H.get(T);if(_)_.set(F,new Set);else console.error(`\uD83D\uDCA5 Could not find root ${T} for list ${F}`)}for(let Q of G){let z=Q.replace(p3,""),[T,F,_]=z.split(X1),w=H.get(T);if(w){let O=w.get(F);if(O)O.add(_);else console.error(`\uD83D\uDCA5 Could not find list ${F} for file ${z}`)}else console.error(`\uD83D\uDCA5 Could not find root ${T} for file ${z}`)}console.log("\uD83D\uDC3F\uFE0F ",H);for(let[Q,z]of H.entries()){let T=$.get(Q);if(!T){console.error(`\uD83D\uDCA5 Could not find root ${Q}`);continue}if(!y1.existsSync(T)){console.warn(`\uD83D\uDCA5 Root folder ${T}, identified as being used during tracking, no longer exists during cleanup.`);continue}let _=y1.readdirSync(T);for(let w of _)if(w!==".ferret"&&!z.has(w)){let O=d8.join(T,w);console.log(`\uD83E\uDDF9 globalFlush: removing directory ${O}`),y1.rmSync(O,{recursive:!0})}for(let[w,O]of z.entries()){let M=d8.join(T,w);if(!y1.existsSync(M)){console.warn(`\uD83D\uDCA5 List folder ${M}, identified as being used during tracking, no longer exists.`);continue}let I=y1.readdirSync(M);for(let j of I){let R=j.replace(".input.json","").replace(".output.json","").replace(".stream.txt","");if(!O.has(R)){let Z=d8.join(M,j);console.log(`\uD83E\uDDF9 globalFlush: removing file ${Z}`),y1.rmSync(Z)}}}}}y1.rmSync(P0.storage.rootDir,{recursive:!0})}};function RX(W,$){return $.startsWith(W)}import*as i0 from"fs";import*as LW from"path";import{inspect as d3}from"util";var l3=class{filenameCache=new Map;filesTouched=new Map;mode;baseDir;rootName;constructor(W="off",$=LW.join(process.cwd(),".varmint")){if(this.mode=W,this.baseDir=$,this.rootName=A$(this.baseDir),P0.storage.initialized&&!P0.storage.getItem(`root${X1}${this.rootName}`))P0.storage.setItem(`root${X1}${this.rootName}`,this.baseDir)}read(W,$,X){let Y=LW.join(this.baseDir,W),G=`${$}.input.json`,J=LW.join(Y,G);if(!i0.existsSync(J)){if(!i0.existsSync(Y)){if(P0.storage.initialized&&this.mode==="read")P0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${W}" with "${$}" was not found. Directory "${Y}" does not exist.`)}let _=i0.readdirSync(Y).map((M)=>[M,i0.readFileSync(LW.join(Y,M),"utf-8")]).filter(([M])=>M.endsWith(".input.json")),w=[];for(let[M,A]of _){let I=` ${M}`,j=` ${d3(JSON.parse(A),{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
19
19
  `).join(`
20
- `)}`;_.push(I,C)}let V=` ${J}
21
- ${u3(X,{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
20
+ `)}`;w.push(I,j)}let O=` ${G}
21
+ ${d3(X,{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
22
22
  `).join(`
23
- `)}`;if(f0.storage.initialized&&this.mode==="read")f0.storage.setItem(`unmatched${X1}${J}`,JSON.stringify(X,null,"\t")),f0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${W}" with subKey "${$}" (${G}) was not found. Directory "${Y}" exists, but the file does not. Below is a list of CACHED INPUT FILES from that directory and their contents, followed by YOUR INPUT DATA.
23
+ `)}`;if(P0.storage.initialized&&this.mode==="read")P0.storage.setItem(`unmatched${X1}${G}`,JSON.stringify(X,null,"\t")),P0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${W}" with subKey "${$}" (${J}) was not found. Directory "${Y}" exists, but the file does not. Below is a list of CACHED INPUT FILES from that directory and their contents, followed by YOUR INPUT DATA.
24
24
 
25
25
  CACHED INPUT FILES:
26
- ${_.join(`
26
+ ${w.join(`
27
27
  `)}
28
28
 
29
29
  YOUR INPUT DATA:
30
- ${V}
31
- `)}let H=i0.readFileSync(G,"utf-8"),Q=JSON.stringify(X,null,"\t");if(Q!==H){if(f0.storage.initialized&&this.mode==="read")f0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: the content of the cached input file ${G} does not match the input provided.
30
+ ${O}
31
+ `)}let H=i0.readFileSync(J,"utf-8"),Q=JSON.stringify(X,null,"\t");if(Q!==H){if(P0.storage.initialized&&this.mode==="read")P0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: the content of the cached input file ${J} does not match the input provided.
32
32
 
33
33
  Provided:
34
34
  ${Q}
35
35
 
36
36
  Cached:
37
- ${H}`)}let z=EW.join(this.baseDir,`${W}/${$}.output.json`);return JSON.parse(i0.readFileSync(z,"utf-8"))}async write(W,$,X,Y){let J=EW.join(this.baseDir,W),G=EW.join(J,`${$}.input.json`),H=EW.join(J,`${$}.output.json`),Q=JSON.stringify(X,null,"\t");if(!i0.existsSync(this.baseDir))i0.mkdirSync(this.baseDir,{recursive:!0});if(!i0.existsSync(J))i0.mkdirSync(J);if(i0.writeFileSync(G,Q),i0.existsSync(H))i0.unlinkSync(H);let z=await Y(...X),F=JSON.stringify(z,null,"\t");return i0.writeFileSync(H,F),z}add(W,$){let X=`${this.rootName}${X1}${O4(W)}`;return{flush:()=>{this.flush(W)},for:(Y)=>{if(this.mode!=="off"){if(this.filesTouched.set(W,new Set),f0.storage.initialized&&!f0.storage.getItem(`list${X1}${X}`))f0.storage.setItem(`list${X1}${X}`,"true")}return{get:async(...J)=>{let G=Y;if(this.mode!=="off"){let H=this.filenameCache.get(Y);if(!H)H=O4(Y),this.filenameCache.set(Y,H);G=H,this.filesTouched.get(W)?.add(G);let Q=`${X}${X1}${G}`,z=`file${X1}${Q}`;if(f0.storage.initialized&&!f0.storage.getItem(z))f0.storage.setItem(z,"true")}switch(this.mode){case"off":return $(...J);case"read":return this.read(W,G,J);case"write":return this.write(W,G,J,$);case"read-write":try{return this.read(W,G,J)}catch(H){if(H instanceof Error)return this.write(W,G,J,$);throw H}}}}}}}flush(...W){console.log(this.filesTouched);for(let[$,X]of this.filesTouched.entries())if(W.length===0||W.includes($)){let Y=EW.join(this.baseDir,$),J=i0.readdirSync(Y);for(let G of J){let H=G.replace(".input.json","").replace(".output.json","");if(!X.has(H))console.info(`\uD83E\uDDF9 Flushing ${H}`),i0.unlinkSync(EW.join(Y,G))}}}};var NX="RFC3986",ZX={RFC1738:(W)=>String(W).replace(/%20/g,"+"),RFC3986:(W)=>String(W)},d3="RFC1738";var qM=Array.isArray,bW=(()=>{let W=[];for(let $=0;$<256;++$)W.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return W})();var r9=1024,l3=(W,$,X,Y,J)=>{if(W.length===0)return W;let G=W;if(typeof W==="symbol")G=Symbol.prototype.toString.call(W);else if(typeof W!=="string")G=String(W);if(X==="iso-8859-1")return escape(G).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let H="";for(let Q=0;Q<G.length;Q+=r9){let z=G.length>=r9?G.slice(Q,Q+r9):G,F=[];for(let T=0;T<z.length;++T){let U=z.charCodeAt(T);if(U===45||U===46||U===95||U===126||U>=48&&U<=57||U>=65&&U<=90||U>=97&&U<=122||J===d3&&(U===40||U===41)){F[F.length]=z.charAt(T);continue}if(U<128){F[F.length]=bW[U];continue}if(U<2048){F[F.length]=bW[192|U>>6]+bW[128|U&63];continue}if(U<55296||U>=57344){F[F.length]=bW[224|U>>12]+bW[128|U>>6&63]+bW[128|U&63];continue}T+=1,U=65536+((U&1023)<<10|z.charCodeAt(T)&1023),F[F.length]=bW[240|U>>18]+bW[128|U>>12&63]+bW[128|U>>6&63]+bW[128|U&63]}H+=F.join("")}return H};function o3(W){if(!W||typeof W!=="object")return!1;return!!(W.constructor&&W.constructor.isBuffer&&W.constructor.isBuffer(W))}function t9(W,$){if(qM(W)){let X=[];for(let Y=0;Y<W.length;Y+=1)X.push($(W[Y]));return X}return $(W)}var CM=Object.prototype.hasOwnProperty,i3={brackets(W){return String(W)+"[]"},comma:"comma",indices(W,$){return String(W)+"["+$+"]"},repeat(W){return String(W)}},yW=Array.isArray,kM=Array.prototype.push,n3=function(W,$){kM.apply(W,yW($)?$:[$])},jM=Date.prototype.toISOString,Y1={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:l3,encodeValuesOnly:!1,format:NX,formatter:ZX[NX],indices:!1,serializeDate(W){return jM.call(W)},skipNulls:!1,strictNullHandling:!1};function IM(W){return typeof W==="string"||typeof W==="number"||typeof W==="boolean"||typeof W==="symbol"||typeof W==="bigint"}var a9={};function r3(W,$,X,Y,J,G,H,Q,z,F,T,U,_,V,K,B,I,C){let R=W,q=C,m=0,c=!1;while((q=q.get(a9))!==void 0&&!c){let L=q.get(W);if(m+=1,typeof L!=="undefined")if(L===m)throw new RangeError("Cyclic object value");else c=!0;if(typeof q.get(a9)==="undefined")m=0}if(typeof F==="function")R=F($,R);else if(R instanceof Date)R=_?.(R);else if(X==="comma"&&yW(R))R=t9(R,function(L){if(L instanceof Date)return _?.(L);return L});if(R===null){if(G)return z&&!B?z($,Y1.encoder,I,"key",V):$;R=""}if(IM(R)||o3(R)){if(z){let L=B?$:z($,Y1.encoder,I,"key",V);return[K?.(L)+"="+K?.(z(R,Y1.encoder,I,"value",V))]}return[K?.($)+"="+K?.(String(R))]}let v=[];if(typeof R==="undefined")return v;let h;if(X==="comma"&&yW(R)){if(B&&z)R=t9(R,z);h=[{value:R.length>0?R.join(",")||null:void 0}]}else if(yW(F))h=F;else{let L=Object.keys(R);h=T?L.sort(T):L}let w0=Q?String($).replace(/\./g,"%2E"):String($),p0=Y&&yW(R)&&R.length===1?w0+"[]":w0;if(J&&yW(R)&&R.length===0)return p0+"[]";for(let L=0;L<h.length;++L){let M0=h[L],W0=typeof M0==="object"&&typeof M0.value!=="undefined"?M0.value:R[M0];if(H&&W0===null)continue;let _0=U&&Q?M0.replace(/\./g,"%2E"):M0,e0=yW(R)?typeof X==="function"?X(p0,_0):p0:p0+(U?"."+_0:"["+_0+"]");C.set(W,m);let V1=new WeakMap;V1.set(a9,C),n3(v,r3(W0,e0,X,Y,J,G,H,Q,X==="comma"&&B&&yW(R)?null:z,F,T,U,_,V,K,B,I,V1))}return v}function fM(W=Y1){if(typeof W.allowEmptyArrays!=="undefined"&&typeof W.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof W.encodeDotInKeys!=="undefined"&&typeof W.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(W.encoder!==null&&typeof W.encoder!=="undefined"&&typeof W.encoder!=="function")throw new TypeError("Encoder has to be a function.");let $=W.charset||Y1.charset;if(typeof W.charset!=="undefined"&&W.charset!=="utf-8"&&W.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let X=NX;if(typeof W.format!=="undefined"){if(!CM.call(ZX,W.format))throw new TypeError("Unknown format option provided.");X=W.format}let Y=ZX[X],J=Y1.filter;if(typeof W.filter==="function"||yW(W.filter))J=W.filter;let G;if(W.arrayFormat&&W.arrayFormat in i3)G=W.arrayFormat;else if("indices"in W)G=W.indices?"indices":"repeat";else G=Y1.arrayFormat;if("commaRoundTrip"in W&&typeof W.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let H=typeof W.allowDots==="undefined"?!!W.encodeDotInKeys===!0?!0:Y1.allowDots:!!W.allowDots;return{addQueryPrefix:typeof W.addQueryPrefix==="boolean"?W.addQueryPrefix:Y1.addQueryPrefix,allowDots:H,allowEmptyArrays:typeof W.allowEmptyArrays==="boolean"?!!W.allowEmptyArrays:Y1.allowEmptyArrays,arrayFormat:G,charset:$,charsetSentinel:typeof W.charsetSentinel==="boolean"?W.charsetSentinel:Y1.charsetSentinel,commaRoundTrip:!!W.commaRoundTrip,delimiter:typeof W.delimiter==="undefined"?Y1.delimiter:W.delimiter,encode:typeof W.encode==="boolean"?W.encode:Y1.encode,encodeDotInKeys:typeof W.encodeDotInKeys==="boolean"?W.encodeDotInKeys:Y1.encodeDotInKeys,encoder:typeof W.encoder==="function"?W.encoder:Y1.encoder,encodeValuesOnly:typeof W.encodeValuesOnly==="boolean"?W.encodeValuesOnly:Y1.encodeValuesOnly,filter:J,format:X,formatter:Y,serializeDate:typeof W.serializeDate==="function"?W.serializeDate:Y1.serializeDate,skipNulls:typeof W.skipNulls==="boolean"?W.skipNulls:Y1.skipNulls,sort:typeof W.sort==="function"?W.sort:null,strictNullHandling:typeof W.strictNullHandling==="boolean"?W.strictNullHandling:Y1.strictNullHandling}}function s9(W,$={}){let X=W,Y=fM($),J,G;if(typeof Y.filter==="function")G=Y.filter,X=G("",X);else if(yW(Y.filter))G=Y.filter,J=G;let H=[];if(typeof X!=="object"||X===null)return"";let Q=i3[Y.arrayFormat],z=Q==="comma"&&Y.commaRoundTrip;if(!J)J=Object.keys(X);if(Y.sort)J.sort(Y.sort);let F=new WeakMap;for(let _=0;_<J.length;++_){let V=J[_];if(Y.skipNulls&&X[V]===null)continue;n3(H,r3(X[V],V,Q,z,Y.allowEmptyArrays,Y.strictNullHandling,Y.skipNulls,Y.encodeDotInKeys,Y.encode?Y.encoder:null,Y.filter,Y.sort,Y.allowDots,Y.serializeDate,Y.format,Y.formatter,Y.encodeValuesOnly,Y.charset,F))}let T=H.join(Y.delimiter),U=Y.addQueryPrefix===!0?"?":"";if(Y.charsetSentinel)if(Y.charset==="iso-8859-1")U+="utf8=%26%2310003%3B&";else U+="utf8=%E2%9C%93&";return T.length>0?U+T:""}var i2="4.100.0";var t3=!1,n2=void 0,e9=void 0,xM=void 0,vM=void 0,bM=void 0,WJ=void 0,yM=void 0,SX=void 0,$J=void 0,XJ=void 0,YJ=void 0,qX=void 0,JJ=void 0;function a3(W,$={auto:!1}){if(t3)throw new Error(`you must \`import 'openai/shims/${W.kind}'\` before importing anything else from openai`);if(n2)throw new Error(`can't \`import 'openai/shims/${W.kind}'\` after \`import 'openai/shims/${n2}'\``);t3=$.auto,n2=W.kind,e9=W.fetch,xM=W.Request,vM=W.Response,bM=W.Headers,WJ=W.FormData,yM=W.Blob,SX=W.File,$J=W.ReadableStream,XJ=W.getMultipartRequestOptions,YJ=W.getDefaultAgent,qX=W.fileFromPath,JJ=W.isFsReadStream}class GJ{constructor(W){this.body=W}get[Symbol.toStringTag](){return"MultipartBody"}}function s3({manuallyImported:W}={}){let $=W?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",X,Y,J,G;try{X=fetch,Y=Request,J=Response,G=Headers}catch(H){throw new Error(`this environment is missing the following Web Fetch API type: ${H.message}. ${$}`)}return{kind:"web",fetch:X,Request:Y,Response:J,Headers:G,FormData:typeof FormData!=="undefined"?FormData:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${$}`)}},Blob:typeof Blob!=="undefined"?Blob:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${$}`)}},File:typeof File!=="undefined"?File:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${$}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class H{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${$}`)}},getMultipartRequestOptions:async(H,Q)=>({...Q,body:new GJ(H)}),getDefaultAgent:(H)=>{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:(H)=>!1}}import{ReadStream as gM}from"fs";function e3(){let W=s3();function $(X){return X instanceof gM}return{...W,isFsReadStream:$}}var HJ=()=>{if(!n2)a3(e3(),{auto:!0})};HJ();class o extends Error{}class t0 extends o{constructor(W,$,X,Y){super(`${t0.makeMessage(W,$,X)}`);this.status=W,this.headers=Y,this.request_id=Y?.["x-request-id"],this.error=$;let J=$;this.code=J?.code,this.param=J?.param,this.type=J?.type}static makeMessage(W,$,X){let Y=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):X;if(W&&Y)return`${W} ${Y}`;if(W)return`${W} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate(W,$,X,Y){if(!W||!Y)return new r2({message:X,cause:bX($)});let J=$?.error;if(W===400)return new CX(W,J,X,Y);if(W===401)return new kX(W,J,X,Y);if(W===403)return new jX(W,J,X,Y);if(W===404)return new IX(W,J,X,Y);if(W===409)return new fX(W,J,X,Y);if(W===422)return new PX(W,J,X,Y);if(W===429)return new xX(W,J,X,Y);if(W>=500)return new vX(W,J,X,Y);return new t0(W,J,X,Y)}}class J1 extends t0{constructor({message:W}={}){super(void 0,void 0,W||"Request was aborted.",void 0)}}class r2 extends t0{constructor({message:W,cause:$}){super(void 0,void 0,W||"Connection error.",void 0);if($)this.cause=$}}class t2 extends r2{constructor({message:W}={}){super({message:W??"Request timed out."})}}class CX extends t0{}class kX extends t0{}class jX extends t0{}class IX extends t0{}class fX extends t0{}class PX extends t0{}class xX extends t0{}class vX extends t0{}class K4 extends o{constructor(){super("Could not parse response content as the length limit was reached")}}class A4 extends o{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var yX=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},a2=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},i1;class c8{constructor(){i1.set(this,void 0),this.buffer=new Uint8Array,yX(this,i1,null,"f")}decode(W){if(W==null)return[];let $=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?new TextEncoder().encode(W):W,X=new Uint8Array(this.buffer.length+$.length);X.set(this.buffer),X.set($,this.buffer.length),this.buffer=X;let Y=[],J;while((J=pM(this.buffer,a2(this,i1,"f")))!=null){if(J.carriage&&a2(this,i1,"f")==null){yX(this,i1,J.index,"f");continue}if(a2(this,i1,"f")!=null&&(J.index!==a2(this,i1,"f")+1||J.carriage)){Y.push(this.decodeText(this.buffer.slice(0,a2(this,i1,"f")-1))),this.buffer=this.buffer.slice(a2(this,i1,"f")),yX(this,i1,null,"f");continue}let G=a2(this,i1,"f")!==null?J.preceding-1:J.preceding,H=this.decodeText(this.buffer.slice(0,G));Y.push(H),this.buffer=this.buffer.slice(J.index),yX(this,i1,null,"f")}return Y}decodeText(W){if(W==null)return"";if(typeof W==="string")return W;if(typeof Buffer!=="undefined"){if(W instanceof Buffer)return W.toString();if(W instanceof Uint8Array)return Buffer.from(W).toString();throw new o(`Unexpected: received non-Uint8Array (${W.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(W instanceof Uint8Array||W instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(W);throw new o(`Unexpected: received non-Uint8Array/ArrayBuffer (${W.constructor.name}) in a web platform. Please report this error.`)}throw new o("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
38
- `)}}i1=new WeakMap;c8.NEWLINE_CHARS=new Set([`
39
- `,"\r"]);c8.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function pM(W,$){for(let J=$??0;J<W.length;J++){if(W[J]===10)return{preceding:J,index:J+1,carriage:!1};if(W[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function WH(W){for(let Y=0;Y<W.length-1;Y++){if(W[Y]===10&&W[Y+1]===10)return Y+2;if(W[Y]===13&&W[Y+1]===13)return Y+2;if(W[Y]===13&&W[Y+1]===10&&Y+3<W.length&&W[Y+2]===13&&W[Y+3]===10)return Y+4}return-1}function QJ(W){if(W[Symbol.asyncIterator])return W;let $=W.getReader();return{async next(){try{let X=await $.read();if(X?.done)$.releaseLock();return X}catch(X){throw $.releaseLock(),X}},async return(){let X=$.cancel();return $.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class n1{constructor(W,$){this.iterator=W,this.controller=$}static fromSSEResponse(W,$){let X=!1;async function*Y(){if(X)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let J=!1;try{for await(let G of uM(W,$)){if(J)continue;if(G.data.startsWith("[DONE]")){J=!0;continue}if(G.event===null||G.event.startsWith("response.")||G.event.startsWith("transcript.")){let H;try{H=JSON.parse(G.data)}catch(Q){throw console.error("Could not parse message into JSON:",G.data),console.error("From chunk:",G.raw),Q}if(H&&H.error)throw new t0(void 0,H.error,void 0,zJ(W.headers));yield H}else{let H;try{H=JSON.parse(G.data)}catch(Q){throw console.error("Could not parse message into JSON:",G.data),console.error("From chunk:",G.raw),Q}if(G.event=="error")throw new t0(void 0,H.error,H.message,void 0);yield{event:G.event,data:H}}}J=!0}catch(G){if(G instanceof Error&&G.name==="AbortError")return;throw G}finally{if(!J)$.abort()}}return new n1(Y,$)}static fromReadableStream(W,$){let X=!1;async function*Y(){let G=new c8,H=QJ(W);for await(let Q of H)for(let z of G.decode(Q))yield z;for(let Q of G.flush())yield Q}async function*J(){if(X)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let G=!1;try{for await(let H of Y()){if(G)continue;if(H)yield JSON.parse(H)}G=!0}catch(H){if(H instanceof Error&&H.name==="AbortError")return;throw H}finally{if(!G)$.abort()}}return new n1(J,$)}[Symbol.asyncIterator](){return this.iterator()}tee(){let W=[],$=[],X=this.iterator(),Y=(J)=>{return{next:()=>{if(J.length===0){let G=X.next();W.push(G),$.push(G)}return J.shift()}}};return[new n1(()=>Y(W),this.controller),new n1(()=>Y($),this.controller)]}toReadableStream(){let W=this,$,X=new TextEncoder;return new $J({async start(){$=W[Symbol.asyncIterator]()},async pull(Y){try{let{value:J,done:G}=await $.next();if(G)return Y.close();let H=X.encode(JSON.stringify(J)+`
40
- `);Y.enqueue(H)}catch(J){Y.error(J)}},async cancel(){await $.return?.()}})}}async function*uM(W,$){if(!W.body)throw $.abort(),new o("Attempted to iterate over a response with no body");let X=new $H,Y=new c8,J=QJ(W.body);for await(let G of cM(J))for(let H of Y.decode(G)){let Q=X.decode(H);if(Q)yield Q}for(let G of Y.flush()){let H=X.decode(G);if(H)yield H}}async function*cM(W){let $=new Uint8Array;for await(let X of W){if(X==null)continue;let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?new TextEncoder().encode(X):X,J=new Uint8Array($.length+Y.length);J.set($),J.set(Y,$.length),$=J;let G;while((G=WH($))!==-1)yield $.slice(0,G),$=$.slice(G)}if($.length>0)yield $}class $H{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(W){if(W.endsWith("\r"))W=W.substring(0,W.length-1);if(!W){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
41
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push(W),W.startsWith(":"))return null;let[$,X,Y]=dM(W,":");if(Y.startsWith(" "))Y=Y.substring(1);if($==="event")this.event=Y;else if($==="data")this.data.push(Y);return null}}function dM(W,$){let X=W.indexOf($);if(X!==-1)return[W.substring(0,X),$,W.substring(X+$.length)];return[W,"",""]}var XH=(W)=>W!=null&&typeof W==="object"&&typeof W.url==="string"&&typeof W.blob==="function",YH=(W)=>W!=null&&typeof W==="object"&&typeof W.name==="string"&&typeof W.lastModified==="number"&&E4(W),E4=(W)=>W!=null&&typeof W==="object"&&typeof W.size==="number"&&typeof W.type==="string"&&typeof W.text==="function"&&typeof W.slice==="function"&&typeof W.arrayBuffer==="function",lM=(W)=>{return YH(W)||XH(W)||JJ(W)};async function UJ(W,$,X){if(W=await W,YH(W))return W;if(XH(W)){let J=await W.blob();$||($=new URL(W.url).pathname.split(/[\\/]/).pop()??"unknown_file");let G=E4(J)?[await J.arrayBuffer()]:[J];return new SX(G,$,X)}let Y=await oM(W);if($||($=nM(W)??"unknown_file"),!X?.type){let J=Y[0]?.type;if(typeof J==="string")X={...X,type:J}}return new SX(Y,$,X)}async function oM(W){let $=[];if(typeof W==="string"||ArrayBuffer.isView(W)||W instanceof ArrayBuffer)$.push(W);else if(E4(W))$.push(await W.arrayBuffer());else if(rM(W))for await(let X of W)$.push(X);else throw new Error(`Unexpected data type: ${typeof W}; constructor: ${W?.constructor?.name}; props: ${iM(W)}`);return $}function iM(W){return`[${Object.getOwnPropertyNames(W).map((X)=>`"${X}"`).join(", ")}]`}function nM(W){return FJ(W.name)||FJ(W.filename)||FJ(W.path)?.split(/[\\/]/).pop()}var FJ=(W)=>{if(typeof W==="string")return W;if(typeof Buffer!=="undefined"&&W instanceof Buffer)return String(W);return},rM=(W)=>W!=null&&typeof W==="object"&&typeof W[Symbol.asyncIterator]==="function",wJ=(W)=>W&&typeof W==="object"&&W.body&&W[Symbol.toStringTag]==="MultipartBody";var JW=async(W)=>{let $=await JH(W.body);return XJ($,W)},JH=async(W)=>{let $=new WJ;return await Promise.all(Object.entries(W||{}).map(([X,Y])=>TJ($,X,Y))),$};var TJ=async(W,$,X)=>{if(X===void 0)return;if(X==null)throw new TypeError(`Received null for "${$}"; to pass null in FormData, you must use the string 'null'`);if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")W.append($,String(X));else if(lM(X)){let Y=await UJ(X);W.append($,Y)}else if(Array.isArray(X))await Promise.all(X.map((Y)=>TJ(W,$+"[]",Y)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Y,J])=>TJ(W,`${$}[${Y}]`,J)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${X} instead`)};var aM=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},sM=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},hX;HJ();async function TH(W){let{response:$}=W;if(W.options.stream){if(rW("response",$.status,$.url,$.headers,$.body),W.options.__streamClass)return W.options.__streamClass.fromSSEResponse($,W.controller);return n1.fromSSEResponse($,W.controller)}if($.status===204)return null;if(W.options.__binaryResponse)return $;let Y=$.headers.get("content-type")?.split(";")[0]?.trim();if(Y?.includes("application/json")||Y?.endsWith("+json")){let H=await $.json();return rW("response",$.status,$.url,$.headers,H),UH(H,$)}let G=await $.text();return rW("response",$.status,$.url,$.headers,G),G}function UH(W,$){if(!W||typeof W!=="object"||Array.isArray(W))return W;return Object.defineProperty(W,"_request_id",{value:$.headers.get("x-request-id"),enumerable:!1})}class mX extends Promise{constructor(W,$=TH){super((X)=>{X(null)});this.responsePromise=W,this.parseResponse=$}_thenUnwrap(W){return new mX(this.responsePromise,async($)=>UH(W(await this.parseResponse($),$),$.response))}asResponse(){return this.responsePromise.then((W)=>W.response)}async withResponse(){let[W,$]=await Promise.all([this.parse(),this.asResponse()]);return{data:W,response:$,request_id:$.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(W,$){return this.parse().then(W,$)}catch(W){return this.parse().catch(W)}finally(W){return this.parse().finally(W)}}class DJ{constructor({baseURL:W,maxRetries:$=2,timeout:X=600000,httpAgent:Y,fetch:J}){this.baseURL=W,this.maxRetries=_J("maxRetries",$),this.timeout=_J("timeout",X),this.httpAgent=Y,this.fetch=J??e9}authHeaders(W){return{}}defaultHeaders(W){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...XV(),...this.authHeaders(W)}}validateHeaders(W,$){}defaultIdempotencyKey(){return`stainless-node-retry-${HV()}`}get(W,$){return this.methodRequest("get",W,$)}post(W,$){return this.methodRequest("post",W,$)}patch(W,$){return this.methodRequest("patch",W,$)}put(W,$){return this.methodRequest("put",W,$)}delete(W,$){return this.methodRequest("delete",W,$)}methodRequest(W,$,X){return this.request(Promise.resolve(X).then(async(Y)=>{let J=Y&&E4(Y?.body)?new DataView(await Y.body.arrayBuffer()):Y?.body instanceof DataView?Y.body:Y?.body instanceof ArrayBuffer?new DataView(Y.body):Y&&ArrayBuffer.isView(Y?.body)?new DataView(Y.body.buffer):Y?.body;return{method:W,path:$,...Y,body:J}}))}getAPIList(W,$,X){return this.requestAPIList($,{method:"get",path:W,...X})}calculateContentLength(W){if(typeof W==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(W,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(W).length.toString()}else if(ArrayBuffer.isView(W))return W.byteLength.toString();return null}buildRequest(W,{retryCount:$=0}={}){let X={...W},{method:Y,path:J,query:G,headers:H={}}=X,Q=ArrayBuffer.isView(X.body)||X.__binaryRequest&&typeof X.body==="string"?X.body:wJ(X.body)?X.body.body:X.body?JSON.stringify(X.body,null,2):null,z=this.calculateContentLength(Q),F=this.buildURL(J,G);if("timeout"in X)_J("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let T=X.httpAgent??this.httpAgent??YJ(F),U=X.timeout+1000;if(typeof T?.options?.timeout==="number"&&U>(T.options.timeout??0))T.options.timeout=U;if(this.idempotencyHeader&&Y!=="get"){if(!W.idempotencyKey)W.idempotencyKey=this.defaultIdempotencyKey();H[this.idempotencyHeader]=W.idempotencyKey}let _=this.buildHeaders({options:X,headers:H,contentLength:z,retryCount:$});return{req:{method:Y,...Q&&{body:Q},headers:_,...T&&{agent:T},signal:X.signal??null},url:F,timeout:X.timeout}}buildHeaders({options:W,headers:$,contentLength:X,retryCount:Y}){let J={};if(X)J["content-length"]=X;let G=this.defaultHeaders(W);if(zH(J,G),zH(J,$),wJ(W.body)&&n2!=="node")delete J["content-type"];if(gX(G,"x-stainless-retry-count")===void 0&&gX($,"x-stainless-retry-count")===void 0)J["x-stainless-retry-count"]=String(Y);if(gX(G,"x-stainless-timeout")===void 0&&gX($,"x-stainless-timeout")===void 0&&W.timeout)J["x-stainless-timeout"]=String(Math.trunc(W.timeout/1000));return this.validateHeaders(J,$),J}async prepareOptions(W){}async prepareRequest(W,{url:$,options:X}){}parseHeaders(W){return!W?{}:(Symbol.iterator in W)?Object.fromEntries(Array.from(W).map(($)=>[...$])):{...W}}makeStatusError(W,$,X,Y){return t0.generate(W,$,X,Y)}request(W,$=null){return new mX(this.makeRequest(W,$))}async makeRequest(W,$){let X=await W,Y=X.maxRetries??this.maxRetries;if($==null)$=Y;await this.prepareOptions(X);let{req:J,url:G,timeout:H}=this.buildRequest(X,{retryCount:Y-$});if(await this.prepareRequest(J,{url:G,options:X}),rW("request",G,X,J.headers),X.signal?.aborted)throw new J1;let Q=new AbortController,z=await this.fetchWithTimeout(G,J,H,Q).catch(bX);if(z instanceof Error){if(X.signal?.aborted)throw new J1;if($)return this.retryRequest(X,$);if(z.name==="AbortError")throw new t2;throw new r2({cause:z})}let F=zJ(z.headers);if(!z.ok){if($&&this.shouldRetry(z)){let B=`retrying, ${$} attempts remaining`;return rW(`response (error; ${B})`,z.status,G,F),this.retryRequest(X,$,F)}let T=await z.text().catch((B)=>bX(B).message),U=YV(T),_=U?void 0:T;throw rW(`response (error; ${$?"(error; no more retries left)":"(error; not retryable)"})`,z.status,G,F,_),this.makeStatusError(z.status,U,_,F)}return{response:z,options:X,controller:Q}}requestAPIList(W,$){let X=this.makeRequest($,null);return new wH(this,X,W)}buildURL(W,$){let X=GV(W)?new URL(W):new URL(this.baseURL+(this.baseURL.endsWith("/")&&W.startsWith("/")?W.slice(1):W)),Y=this.defaultQuery();if(!_H(Y))$={...Y,...$};if(typeof $==="object"&&$&&!Array.isArray($))X.search=this.stringifyQuery($);return X.toString()}stringifyQuery(W){return Object.entries(W).filter(([$,X])=>typeof X!=="undefined").map(([$,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent($)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent($)}=`;throw new o(`Cannot stringify type ${typeof X}; 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(W,$,X,Y){let{signal:J,...G}=$||{};if(J)J.addEventListener("abort",()=>Y.abort());let H=setTimeout(()=>Y.abort(),X),Q={signal:Y.signal,...G};if(Q.method)Q.method=Q.method.toUpperCase();return this.fetch.call(void 0,W,Q).finally(()=>{clearTimeout(H)})}shouldRetry(W){let $=W.headers.get("x-should-retry");if($==="true")return!0;if($==="false")return!1;if(W.status===408)return!0;if(W.status===409)return!0;if(W.status===429)return!0;if(W.status>=500)return!0;return!1}async retryRequest(W,$,X){let Y,J=X?.["retry-after-ms"];if(J){let H=parseFloat(J);if(!Number.isNaN(H))Y=H}let G=X?.["retry-after"];if(G&&!Y){let H=parseFloat(G);if(!Number.isNaN(H))Y=H*1000;else Y=Date.parse(G)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let H=W.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis($,H)}return await tW(Y),this.makeRequest(W,$-1)}calculateDefaultRetryTimeoutMillis(W,$){let J=$-W,G=Math.min(0.5*Math.pow(2,J),8),H=1-Math.random()*0.25;return G*H*1000}getUserAgent(){return`${this.constructor.name}/JS ${i2}`}}class pX{constructor(W,$,X,Y){hX.set(this,void 0),aM(this,hX,W,"f"),this.options=Y,this.response=$,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let W=this.nextPageInfo();if(!W)throw new o("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let $={...this.options};if("params"in W&&typeof $.query==="object")$.query={...$.query,...W.params};else if("url"in W){let X=[...Object.entries($.query||{}),...W.url.searchParams.entries()];for(let[Y,J]of X)W.url.searchParams.set(Y,J);$.query=void 0,$.path=W.url.toString()}return await sM(this,hX,"f").requestAPIList(this.constructor,$)}async*iterPages(){let W=this;yield W;while(W.hasNextPage())W=await W.getNextPage(),yield W}async*[(hX=new WeakMap,Symbol.asyncIterator)](){for await(let W of this.iterPages())for(let $ of W.getPaginatedItems())yield $}}class wH extends mX{constructor(W,$,X){super($,async(Y)=>new X(W,Y.response,await TH(Y),Y.options))}async*[Symbol.asyncIterator](){let W=await this;for await(let $ of W)yield $}}var zJ=(W)=>{return new Proxy(Object.fromEntries(W.entries()),{get($,X){let Y=X.toString();return $[Y.toLowerCase()]||$[Y]}})},eM={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},z0=(W)=>{return typeof W==="object"&&W!==null&&!_H(W)&&Object.keys(W).every(($)=>DH(eM,$))},WV=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i2,"X-Stainless-OS":HH(Deno.build.os),"X-Stainless-Arch":GH(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":i2,"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":i2,"X-Stainless-OS":HH(process.platform),"X-Stainless-Arch":GH(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let W=$V();if(W)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${W.browser}`,"X-Stainless-Runtime-Version":W.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function $V(){if(typeof navigator==="undefined"||!navigator)return null;let W=[{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:$,pattern:X}of W){let Y=X.exec(navigator.userAgent);if(Y){let J=Y[1]||0,G=Y[2]||0,H=Y[3]||0;return{browser:$,version:`${J}.${G}.${H}`}}}return null}var GH=(W)=>{if(W==="x32")return"x32";if(W==="x86_64"||W==="x64")return"x64";if(W==="arm")return"arm";if(W==="aarch64"||W==="arm64")return"arm64";if(W)return`other:${W}`;return"unknown"},HH=(W)=>{if(W=W.toLowerCase(),W.includes("ios"))return"iOS";if(W==="android")return"Android";if(W==="darwin")return"MacOS";if(W==="win32")return"Windows";if(W==="freebsd")return"FreeBSD";if(W==="openbsd")return"OpenBSD";if(W==="linux")return"Linux";if(W)return`Other:${W}`;return"Unknown"},QH,XV=()=>{return QH??(QH=WV())},YV=(W)=>{try{return JSON.parse(W)}catch($){return}},JV=/^[a-z][a-z0-9+.-]*:/i,GV=(W)=>{return JV.test(W)},tW=(W)=>new Promise(($)=>setTimeout($,W)),_J=(W,$)=>{if(typeof $!=="number"||!Number.isInteger($))throw new o(`${W} must be an integer`);if($<0)throw new o(`${W} must be a positive integer`);return $},bX=(W)=>{if(W instanceof Error)return W;if(typeof W==="object"&&W!==null)try{return new Error(JSON.stringify(W))}catch{}return new Error(W)};var L4=(W)=>{if(typeof process!=="undefined")return process.env?.[W]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(W)?.trim();return};function _H(W){if(!W)return!0;for(let $ in W)return!1;return!0}function DH(W,$){return Object.prototype.hasOwnProperty.call(W,$)}function zH(W,$){for(let X in $){if(!DH($,X))continue;let Y=X.toLowerCase();if(!Y)continue;let J=$[X];if(J===null)delete W[Y];else if(J!==void 0)W[Y]=J}}var FH=new Set(["authorization","api-key"]);function rW(W,...$){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true"){let X=$.map((Y)=>{if(!Y)return Y;if(Y.headers){let G={...Y,headers:{...Y.headers}};for(let H in Y.headers)if(FH.has(H.toLowerCase()))G.headers[H]="REDACTED";return G}let J=null;for(let G in Y)if(FH.has(G.toLowerCase()))J??(J={...Y}),J[G]="REDACTED";return J??Y});console.log(`OpenAI:DEBUG:${W}`,...X)}}var HV=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(W)=>{let $=Math.random()*16|0;return(W==="x"?$:$&3|8).toString(16)})},MH=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},QV=(W)=>{return typeof W?.get==="function"};var gX=(W,$)=>{let X=$.toLowerCase();if(QV(W)){let Y=$[0]?.toUpperCase()+$.substring(1).replace(/([^\w])(\w)/g,(J,G,H)=>G+H.toUpperCase());for(let J of[$,X,$.toUpperCase(),Y]){let G=W.get(J);if(G)return G}}for(let[Y,J]of Object.entries(W))if(Y.toLowerCase()===X){if(Array.isArray(J)){if(J.length<=1)return J[0];return console.warn(`Received ${J.length} entries for the ${$} header, using the first entry.`),J[0]}return J}return};var VH=(W)=>{if(typeof Buffer!=="undefined"){let $=Buffer.from(W,"base64");return Array.from(new Float32Array($.buffer,$.byteOffset,$.length/Float32Array.BYTES_PER_ELEMENT))}else{let $=atob(W),X=$.length,Y=new Uint8Array(X);for(let J=0;J<X;J++)Y[J]=$.charCodeAt(J);return Array.from(new Float32Array(Y.buffer))}};function B4(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}class aW extends pX{constructor(W,$,X,Y){super(W,$,X,Y);this.data=X.data||[],this.object=X.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class E0 extends pX{constructor(W,$,X,Y){super(W,$,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let W=this.nextPageInfo();if(!W)return null;if("params"in W)return W.params;let $=Object.fromEntries(W.url.searchParams);if(!Object.keys($).length)return null;return $}nextPageInfo(){let W=this.getPaginatedItems();if(!W.length)return null;let $=W[W.length-1]?.id;if(!$)return null;return{params:{after:$}}}}class k{constructor(W){this._client=W}}class R4 extends k{list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/chat/completions/${W}/messages`,MJ,{query:$,...X})}}class s2 extends k{constructor(){super(...arguments);this.messages=new R4(this._client)}create(W,$){return this._client.post("/chat/completions",{body:W,...$,stream:W.stream??!1})}retrieve(W,$){return this._client.get(`/chat/completions/${W}`,$)}update(W,$,X){return this._client.post(`/chat/completions/${W}`,{body:$,...X})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/chat/completions",e2,{query:W,...$})}del(W,$){return this._client.delete(`/chat/completions/${W}`,$)}}class e2 extends E0{}class MJ extends E0{}s2.ChatCompletionsPage=e2;s2.Messages=R4;class N2 extends k{constructor(){super(...arguments);this.completions=new s2(this._client)}}N2.Completions=s2;N2.ChatCompletionsPage=e2;class N4 extends k{create(W,$){return this._client.post("/audio/speech",{body:W,...$,headers:{Accept:"application/octet-stream",...$?.headers},__binaryResponse:!0})}}class Z4 extends k{create(W,$){return this._client.post("/audio/transcriptions",JW({body:W,...$,stream:W.stream??!1,__metadata:{model:W.model}}))}}class S4 extends k{create(W,$){return this._client.post("/audio/translations",JW({body:W,...$,__metadata:{model:W.model}}))}}class sW extends k{constructor(){super(...arguments);this.transcriptions=new Z4(this._client),this.translations=new S4(this._client),this.speech=new N4(this._client)}}sW.Transcriptions=Z4;sW.Translations=S4;sW.Speech=N4;class W8 extends k{create(W,$){return this._client.post("/batches",{body:W,...$})}retrieve(W,$){return this._client.get(`/batches/${W}`,$)}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/batches",d8,{query:W,...$})}cancel(W,$){return this._client.post(`/batches/${W}/cancel`,$)}}class d8 extends E0{}W8.BatchesPage=d8;var LW=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},c0=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},VJ,uX,cX,q4,C4,dX,k4,eW,j4,lX,oX,l8,OH;class $8{constructor(){VJ.add(this),this.controller=new AbortController,uX.set(this,void 0),cX.set(this,()=>{}),q4.set(this,()=>{}),C4.set(this,void 0),dX.set(this,()=>{}),k4.set(this,()=>{}),eW.set(this,{}),j4.set(this,!1),lX.set(this,!1),oX.set(this,!1),l8.set(this,!1),LW(this,uX,new Promise((W,$)=>{LW(this,cX,W,"f"),LW(this,q4,$,"f")}),"f"),LW(this,C4,new Promise((W,$)=>{LW(this,dX,W,"f"),LW(this,k4,$,"f")}),"f"),c0(this,uX,"f").catch(()=>{}),c0(this,C4,"f").catch(()=>{})}_run(W){setTimeout(()=>{W().then(()=>{this._emitFinal(),this._emit("end")},c0(this,VJ,"m",OH).bind(this))},0)}_connected(){if(this.ended)return;c0(this,cX,"f").call(this),this._emit("connect")}get ended(){return c0(this,j4,"f")}get errored(){return c0(this,lX,"f")}get aborted(){return c0(this,oX,"f")}abort(){this.controller.abort()}on(W,$){return(c0(this,eW,"f")[W]||(c0(this,eW,"f")[W]=[])).push({listener:$}),this}off(W,$){let X=c0(this,eW,"f")[W];if(!X)return this;let Y=X.findIndex((J)=>J.listener===$);if(Y>=0)X.splice(Y,1);return this}once(W,$){return(c0(this,eW,"f")[W]||(c0(this,eW,"f")[W]=[])).push({listener:$,once:!0}),this}emitted(W){return new Promise(($,X)=>{if(LW(this,l8,!0,"f"),W!=="error")this.once("error",X);this.once(W,$)})}async done(){LW(this,l8,!0,"f"),await c0(this,C4,"f")}_emit(W,...$){if(c0(this,j4,"f"))return;if(W==="end")LW(this,j4,!0,"f"),c0(this,dX,"f").call(this);let X=c0(this,eW,"f")[W];if(X)c0(this,eW,"f")[W]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...$));if(W==="abort"){let Y=$[0];if(!c0(this,l8,"f")&&!X?.length)Promise.reject(Y);c0(this,q4,"f").call(this,Y),c0(this,k4,"f").call(this,Y),this._emit("end");return}if(W==="error"){let Y=$[0];if(!c0(this,l8,"f")&&!X?.length)Promise.reject(Y);c0(this,q4,"f").call(this,Y),c0(this,k4,"f").call(this,Y),this._emit("end")}}_emitFinal(){}}uX=new WeakMap,cX=new WeakMap,q4=new WeakMap,C4=new WeakMap,dX=new WeakMap,k4=new WeakMap,eW=new WeakMap,j4=new WeakMap,lX=new WeakMap,oX=new WeakMap,l8=new WeakMap,VJ=new WeakSet,OH=function W($){if(LW(this,lX,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new J1;if($ instanceof J1)return LW(this,oX,!0,"f"),this._emit("abort",$);if($ instanceof o)return this._emit("error",$);if($ instanceof Error){let X=new o($.message);return X.cause=$,this._emit("error",X)}return this._emit("error",new o(String($)))};var i=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},r1=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},D1,OJ,hW,iX,BW,Y8,o8,X8,tX,t1,nX,rX,P4,I4,f4,KH,AH,EH,LH,BH,RH,NH;class a1 extends $8{constructor(){super(...arguments);D1.add(this),OJ.set(this,[]),hW.set(this,{}),iX.set(this,{}),BW.set(this,void 0),Y8.set(this,void 0),o8.set(this,void 0),X8.set(this,void 0),tX.set(this,void 0),t1.set(this,void 0),nX.set(this,void 0),rX.set(this,void 0),P4.set(this,void 0)}[(OJ=new WeakMap,hW=new WeakMap,iX=new WeakMap,BW=new WeakMap,Y8=new WeakMap,o8=new WeakMap,X8=new WeakMap,tX=new WeakMap,t1=new WeakMap,nX=new WeakMap,rX=new WeakMap,P4=new WeakMap,D1=new WeakSet,Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("event",(Y)=>{let J=$.shift();if(J)J.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((J,G)=>$.push({resolve:J,reject:G})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(W){let $=new a1;return $._run(()=>$._fromReadableStream(W)),$}async _fromReadableStream(W,$){let X=$?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}this._connected();let Y=n1.fromReadableStream(W,this.controller);for await(let J of Y)i(this,D1,"m",I4).call(this,J);if(Y.controller.signal?.aborted)throw new J1;return this._addRun(i(this,D1,"m",f4).call(this))}toReadableStream(){return new n1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(W,$,X,Y,J){let G=new a1;return G._run(()=>G._runToolAssistantStream(W,$,X,Y,{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),G}async _createToolAssistantStream(W,$,X,Y,J){let G=J?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let H={...Y,stream:!0},Q=await W.submitToolOutputs($,X,H,{...J,signal:this.controller.signal});this._connected();for await(let z of Q)i(this,D1,"m",I4).call(this,z);if(Q.controller.signal?.aborted)throw new J1;return this._addRun(i(this,D1,"m",f4).call(this))}static createThreadAssistantStream(W,$,X){let Y=new a1;return Y._run(()=>Y._threadAssistantStream(W,$,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}static createAssistantStream(W,$,X,Y){let J=new a1;return J._run(()=>J._runAssistantStream(W,$,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),J}currentEvent(){return i(this,nX,"f")}currentRun(){return i(this,rX,"f")}currentMessageSnapshot(){return i(this,BW,"f")}currentRunStepSnapshot(){return i(this,P4,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,hW,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,iX,"f"))}async finalRun(){if(await this.done(),!i(this,Y8,"f"))throw Error("Final run was not received.");return i(this,Y8,"f")}async _createThreadAssistantStream(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let J={...$,stream:!0},G=await W.createAndRun(J,{...X,signal:this.controller.signal});this._connected();for await(let H of G)i(this,D1,"m",I4).call(this,H);if(G.controller.signal?.aborted)throw new J1;return this._addRun(i(this,D1,"m",f4).call(this))}async _createAssistantStream(W,$,X,Y){let J=Y?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let G={...X,stream:!0},H=await W.create($,G,{...Y,signal:this.controller.signal});this._connected();for await(let Q of H)i(this,D1,"m",I4).call(this,Q);if(H.controller.signal?.aborted)throw new J1;return this._addRun(i(this,D1,"m",f4).call(this))}static accumulateDelta(W,$){for(let[X,Y]of Object.entries($)){if(!W.hasOwnProperty(X)){W[X]=Y;continue}let J=W[X];if(J===null||J===void 0){W[X]=Y;continue}if(X==="index"||X==="type"){W[X]=Y;continue}if(typeof J==="string"&&typeof Y==="string")J+=Y;else if(typeof J==="number"&&typeof Y==="number")J+=Y;else if(B4(J)&&B4(Y))J=this.accumulateDelta(J,Y);else if(Array.isArray(J)&&Array.isArray(Y)){if(J.every((G)=>typeof G==="string"||typeof G==="number")){J.push(...Y);continue}for(let G of Y){if(!B4(G))throw new Error(`Expected array delta entry to be an object but got: ${G}`);let H=G.index;if(H==null)throw console.error(G),new Error("Expected array delta entry to have an `index` property");if(typeof H!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${H}`);let Q=J[H];if(Q==null)J.push(G);else J[H]=this.accumulateDelta(Q,G)}continue}else throw Error(`Unhandled record type: ${X}, deltaValue: ${Y}, accValue: ${J}`);W[X]=J}return W}_addRun(W){return W}async _threadAssistantStream(W,$,X){return await this._createThreadAssistantStream($,W,X)}async _runAssistantStream(W,$,X,Y){return await this._createAssistantStream($,W,X,Y)}async _runToolAssistantStream(W,$,X,Y,J){return await this._createToolAssistantStream(X,W,$,Y,J)}}I4=function W($){if(this.ended)return;switch(r1(this,nX,$,"f"),i(this,D1,"m",EH).call(this,$),$.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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":i(this,D1,"m",NH).call(this,$);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":i(this,D1,"m",AH).call(this,$);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,D1,"m",KH).call(this,$);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:_V($)}},f4=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");if(!i(this,Y8,"f"))throw Error("Final run has not been received");return i(this,Y8,"f")},KH=function W($){let[X,Y]=i(this,D1,"m",BH).call(this,$,i(this,BW,"f"));r1(this,BW,X,"f"),i(this,iX,"f")[X.id]=X;for(let J of Y){let G=X.content[J.index];if(G?.type=="text")this._emit("textCreated",G.text)}switch($.event){case"thread.message.created":this._emit("messageCreated",$.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",$.data.delta,X),$.data.delta.content)for(let J of $.data.delta.content){if(J.type=="text"&&J.text){let G=J.text,H=X.content[J.index];if(H&&H.type=="text")this._emit("textDelta",G,H.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(J.index!=i(this,o8,"f")){if(i(this,X8,"f"))switch(i(this,X8,"f").type){case"text":this._emit("textDone",i(this,X8,"f").text,i(this,BW,"f"));break;case"image_file":this._emit("imageFileDone",i(this,X8,"f").image_file,i(this,BW,"f"));break}r1(this,o8,J.index,"f")}r1(this,X8,X.content[J.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,o8,"f")!==void 0){let J=$.data.content[i(this,o8,"f")];if(J)switch(J.type){case"image_file":this._emit("imageFileDone",J.image_file,i(this,BW,"f"));break;case"text":this._emit("textDone",J.text,i(this,BW,"f"));break}}if(i(this,BW,"f"))this._emit("messageDone",$.data);r1(this,BW,void 0,"f")}},AH=function W($){let X=i(this,D1,"m",LH).call(this,$);switch(r1(this,P4,X,"f"),$.event){case"thread.run.step.created":this._emit("runStepCreated",$.data);break;case"thread.run.step.delta":let Y=$.data.delta;if(Y.step_details&&Y.step_details.type=="tool_calls"&&Y.step_details.tool_calls&&X.step_details.type=="tool_calls")for(let G of Y.step_details.tool_calls)if(G.index==i(this,tX,"f"))this._emit("toolCallDelta",G,X.step_details.tool_calls[G.index]);else{if(i(this,t1,"f"))this._emit("toolCallDone",i(this,t1,"f"));if(r1(this,tX,G.index,"f"),r1(this,t1,X.step_details.tool_calls[G.index],"f"),i(this,t1,"f"))this._emit("toolCallCreated",i(this,t1,"f"))}this._emit("runStepDelta",$.data.delta,X);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(r1(this,P4,void 0,"f"),$.data.step_details.type=="tool_calls"){if(i(this,t1,"f"))this._emit("toolCallDone",i(this,t1,"f")),r1(this,t1,void 0,"f")}this._emit("runStepDone",$.data,X);break;case"thread.run.step.in_progress":break}},EH=function W($){i(this,OJ,"f").push($),this._emit("event",$)},LH=function W($){switch($.event){case"thread.run.step.created":return i(this,hW,"f")[$.data.id]=$.data,$.data;case"thread.run.step.delta":let X=i(this,hW,"f")[$.data.id];if(!X)throw Error("Received a RunStepDelta before creation of a snapshot");let Y=$.data;if(Y.delta){let J=a1.accumulateDelta(X,Y.delta);i(this,hW,"f")[$.data.id]=J}return i(this,hW,"f")[$.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":i(this,hW,"f")[$.data.id]=$.data;break}if(i(this,hW,"f")[$.data.id])return i(this,hW,"f")[$.data.id];throw new Error("No snapshot available")},BH=function W($,X){let Y=[];switch($.event){case"thread.message.created":return[$.data,Y];case"thread.message.delta":if(!X)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let J=$.data;if(J.delta.content)for(let G of J.delta.content)if(G.index in X.content){let H=X.content[G.index];X.content[G.index]=i(this,D1,"m",RH).call(this,G,H)}else X.content[G.index]=G,Y.push(G);return[X,Y];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(X)return[X,Y];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},RH=function W($,X){return a1.accumulateDelta(X,$)},NH=function W($){switch(r1(this,rX,$.data,"f"),$.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(r1(this,Y8,$.data,"f"),i(this,t1,"f"))this._emit("toolCallDone",i(this,t1,"f")),r1(this,t1,void 0,"f");break;case"thread.run.cancelling":break}};function _V(W){}class i8 extends k{create(W,$){return this._client.post("/assistants",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/assistants/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/assistants",x4,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class x4 extends E0{}i8.AssistantsPage=x4;function KJ(W){return typeof W.parse==="function"}var Z2=(W)=>{return W?.role==="assistant"},AJ=(W)=>{return W?.role==="function"},EJ=(W)=>{return W?.role==="tool"};function v4(W){return W?.$brand==="auto-parseable-response-format"}function J8(W){return W?.$brand==="auto-parseable-tool"}function ZH(W,$){if(!$||!LJ($))return{...W,choices:W.choices.map((X)=>({...X,message:{...X.message,parsed:null,...X.message.tool_calls?{tool_calls:X.message.tool_calls}:void 0}}))};return b4(W,$)}function b4(W,$){let X=W.choices.map((Y)=>{if(Y.finish_reason==="length")throw new K4;if(Y.finish_reason==="content_filter")throw new A4;return{...Y,message:{...Y.message,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls?.map((J)=>VV($,J))??void 0}:void 0,parsed:Y.message.content&&!Y.message.refusal?MV($,Y.message.content):null}}});return{...W,choices:X}}function MV(W,$){if(W.response_format?.type!=="json_schema")return null;if(W.response_format?.type==="json_schema"){if("$parseRaw"in W.response_format)return W.response_format.$parseRaw($);return JSON.parse($)}return null}function VV(W,$){let X=W.tools?.find((Y)=>Y.function?.name===$.function.name);return{...$,function:{...$.function,parsed_arguments:J8(X)?X.$parseRaw($.function.arguments):X?.function.strict?JSON.parse($.function.arguments):null}}}function SH(W,$){if(!W)return!1;let X=W.tools?.find((Y)=>Y.function?.name===$.function.name);return J8(X)||X?.function.strict||!1}function LJ(W){if(v4(W.response_format))return!0;return W.tools?.some(($)=>J8($)||$.type==="function"&&$.function.strict===!0)??!1}function qH(W){for(let $ of W??[]){if($.type!=="function")throw new o(`Currently only \`function\` tool types support auto-parsing; Received \`${$.type}\``);if($.function.strict!==!0)throw new o(`The \`${$.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var y1=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},L1,BJ,aX,RJ,NJ,ZJ,kH,SJ,CH=10;class y4 extends $8{constructor(){super(...arguments);L1.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(W){this._chatCompletions.push(W),this._emit("chatCompletion",W);let $=W.choices[0]?.message;if($)this._addMessage($);return W}_addMessage(W,$=!0){if(!("content"in W))W.content=null;if(this.messages.push(W),$){if(this._emit("message",W),(AJ(W)||EJ(W))&&W.content)this._emit("functionCallResult",W.content);else if(Z2(W)&&W.function_call)this._emit("functionCall",W.function_call);else if(Z2(W)&&W.tool_calls){for(let X of W.tool_calls)if(X.type==="function")this._emit("functionCall",X.function)}}}async finalChatCompletion(){await this.done();let W=this._chatCompletions[this._chatCompletions.length-1];if(!W)throw new o("stream ended without producing a ChatCompletion");return W}async finalContent(){return await this.done(),y1(this,L1,"m",BJ).call(this)}async finalMessage(){return await this.done(),y1(this,L1,"m",aX).call(this)}async finalFunctionCall(){return await this.done(),y1(this,L1,"m",RJ).call(this)}async finalFunctionCallResult(){return await this.done(),y1(this,L1,"m",NJ).call(this)}async totalUsage(){return await this.done(),y1(this,L1,"m",ZJ).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let W=this._chatCompletions[this._chatCompletions.length-1];if(W)this._emit("finalChatCompletion",W);let $=y1(this,L1,"m",aX).call(this);if($)this._emit("finalMessage",$);let X=y1(this,L1,"m",BJ).call(this);if(X)this._emit("finalContent",X);let Y=y1(this,L1,"m",RJ).call(this);if(Y)this._emit("finalFunctionCall",Y);let J=y1(this,L1,"m",NJ).call(this);if(J!=null)this._emit("finalFunctionCallResult",J);if(this._chatCompletions.some((G)=>G.usage))this._emit("totalUsage",y1(this,L1,"m",ZJ).call(this))}async _createChatCompletion(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}y1(this,L1,"m",kH).call(this,$);let J=await W.chat.completions.create({...$,stream:!1},{...X,signal:this.controller.signal});return this._connected(),this._addChatCompletion(b4(J,$))}async _runChatCompletion(W,$,X){for(let Y of $.messages)this._addMessage(Y,!1);return await this._createChatCompletion(W,$,X)}async _runFunctions(W,$,X){let{function_call:J="auto",stream:G,...H}=$,Q=typeof J!=="string"&&J?.name,{maxChatCompletions:z=CH}=X||{},F={};for(let U of $.functions)F[U.name||U.function.name]=U;let T=$.functions.map((U)=>({name:U.name||U.function.name,parameters:U.parameters,description:U.description}));for(let U of $.messages)this._addMessage(U,!1);for(let U=0;U<z;++U){let V=(await this._createChatCompletion(W,{...H,function_call:J,functions:T,messages:[...this.messages]},X)).choices[0]?.message;if(!V)throw new o("missing message in ChatCompletion response");if(!V.function_call)return;let{name:K,arguments:B}=V.function_call,I=F[K];if(!I){let m=`Invalid function_call: ${JSON.stringify(K)}. Available options are: ${T.map((c)=>JSON.stringify(c.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:K,content:m});continue}else if(Q&&Q!==K){let m=`Invalid function_call: ${JSON.stringify(K)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"function",name:K,content:m});continue}let C;try{C=KJ(I)?await I.parse(B):B}catch(m){this._addMessage({role:"function",name:K,content:m instanceof Error?m.message:String(m)});continue}let R=await I.function(C,this),q=y1(this,L1,"m",SJ).call(this,R);if(this._addMessage({role:"function",name:K,content:q}),Q)return}}async _runTools(W,$,X){let{tool_choice:J="auto",stream:G,...H}=$,Q=typeof J!=="string"&&J?.function?.name,{maxChatCompletions:z=CH}=X||{},F=$.tools.map((_)=>{if(J8(_)){if(!_.$callback)throw new o("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),T={};for(let _ of F)if(_.type==="function")T[_.function.name||_.function.function.name]=_.function;let U="tools"in $?F.map((_)=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(let _ of $.messages)this._addMessage(_,!1);for(let _=0;_<z;++_){let K=(await this._createChatCompletion(W,{...H,tool_choice:J,tools:U,messages:[...this.messages]},X)).choices[0]?.message;if(!K)throw new o("missing message in ChatCompletion response");if(!K.tool_calls?.length)return;for(let B of K.tool_calls){if(B.type!=="function")continue;let I=B.id,{name:C,arguments:R}=B.function,q=T[C];if(!q){let h=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(T).map((w0)=>JSON.stringify(w0)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:h});continue}else if(Q&&Q!==C){let h=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:h});continue}let m;try{m=KJ(q)?await q.parse(R):R}catch(h){let w0=h instanceof Error?h.message:String(h);this._addMessage({role:"tool",tool_call_id:I,content:w0});continue}let c=await q.function(m,this),v=y1(this,L1,"m",SJ).call(this,c);if(this._addMessage({role:"tool",tool_call_id:I,content:v}),Q)return}}return}}L1=new WeakSet,BJ=function W(){return y1(this,L1,"m",aX).call(this).content??null},aX=function W(){let $=this.messages.length;while($-- >0){let X=this.messages[$];if(Z2(X)){let{function_call:Y,...J}=X,G={...J,content:X.content??null,refusal:X.refusal??null};if(Y)G.function_call=Y;return G}}throw new o("stream ended without producing a ChatCompletionMessage with role=assistant")},RJ=function W(){for(let $=this.messages.length-1;$>=0;$--){let X=this.messages[$];if(Z2(X)&&X?.function_call)return X.function_call;if(Z2(X)&&X?.tool_calls?.length)return X.tool_calls.at(-1)?.function}return},NJ=function W(){for(let $=this.messages.length-1;$>=0;$--){let X=this.messages[$];if(AJ(X)&&X.content!=null)return X.content;if(EJ(X)&&X.content!=null&&typeof X.content==="string"&&this.messages.some((Y)=>Y.role==="assistant"&&Y.tool_calls?.some((J)=>J.type==="function"&&J.id===X.tool_call_id)))return X.content}return},ZJ=function W(){let $={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:X}of this._chatCompletions)if(X)$.completion_tokens+=X.completion_tokens,$.prompt_tokens+=X.prompt_tokens,$.total_tokens+=X.total_tokens;return $},kH=function W($){if($.n!=null&&$.n>1)throw new o("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},SJ=function W($){return typeof $==="string"?$:$===void 0?"undefined":JSON.stringify($)};class n8 extends y4{static runFunctions(W,$,X){let Y=new n8,J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return Y._run(()=>Y._runFunctions(W,$,J)),Y}static runTools(W,$,X){let Y=new n8,J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools(W,$,J)),Y}_addMessage(W,$=!0){if(super._addMessage(W,$),Z2(W)&&W.content)this._emit("content",W.content)}}var U1={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 jH extends Error{}class IH extends Error{}function OV(W,$=U1.ALL){if(typeof W!=="string")throw new TypeError(`expecting str, got ${typeof W}`);if(!W.trim())throw new Error(`${W} is empty`);return KV(W.trim(),$)}var KV=(W,$)=>{let X=W.length,Y=0,J=(_)=>{throw new jH(`${_} at position ${Y}`)},G=(_)=>{throw new IH(`${_} at position ${Y}`)},H=()=>{if(U(),Y>=X)J("Unexpected end of input");if(W[Y]==='"')return Q();if(W[Y]==="{")return z();if(W[Y]==="[")return F();if(W.substring(Y,Y+4)==="null"||U1.NULL&$&&X-Y<4&&"null".startsWith(W.substring(Y)))return Y+=4,null;if(W.substring(Y,Y+4)==="true"||U1.BOOL&$&&X-Y<4&&"true".startsWith(W.substring(Y)))return Y+=4,!0;if(W.substring(Y,Y+5)==="false"||U1.BOOL&$&&X-Y<5&&"false".startsWith(W.substring(Y)))return Y+=5,!1;if(W.substring(Y,Y+8)==="Infinity"||U1.INFINITY&$&&X-Y<8&&"Infinity".startsWith(W.substring(Y)))return Y+=8,1/0;if(W.substring(Y,Y+9)==="-Infinity"||U1.MINUS_INFINITY&$&&1<X-Y&&X-Y<9&&"-Infinity".startsWith(W.substring(Y)))return Y+=9,-1/0;if(W.substring(Y,Y+3)==="NaN"||U1.NAN&$&&X-Y<3&&"NaN".startsWith(W.substring(Y)))return Y+=3,NaN;return T()},Q=()=>{let _=Y,V=!1;Y++;while(Y<X&&(W[Y]!=='"'||V&&W[Y-1]==="\\"))V=W[Y]==="\\"?!V:!1,Y++;if(W.charAt(Y)=='"')try{return JSON.parse(W.substring(_,++Y-Number(V)))}catch(K){G(String(K))}else if(U1.STR&$)try{return JSON.parse(W.substring(_,Y-Number(V))+'"')}catch(K){return JSON.parse(W.substring(_,W.lastIndexOf("\\"))+'"')}J("Unterminated string literal")},z=()=>{Y++,U();let _={};try{while(W[Y]!=="}"){if(U(),Y>=X&&U1.OBJ&$)return _;let V=Q();U(),Y++;try{let K=H();Object.defineProperty(_,V,{value:K,writable:!0,enumerable:!0,configurable:!0})}catch(K){if(U1.OBJ&$)return _;else throw K}if(U(),W[Y]===",")Y++}}catch(V){if(U1.OBJ&$)return _;else J("Expected '}' at end of object")}return Y++,_},F=()=>{Y++;let _=[];try{while(W[Y]!=="]")if(_.push(H()),U(),W[Y]===",")Y++}catch(V){if(U1.ARR&$)return _;J("Expected ']' at end of array")}return Y++,_},T=()=>{if(Y===0){if(W==="-"&&U1.NUM&$)J("Not sure what '-' is");try{return JSON.parse(W)}catch(V){if(U1.NUM&$)try{if(W[W.length-1]===".")return JSON.parse(W.substring(0,W.lastIndexOf(".")));return JSON.parse(W.substring(0,W.lastIndexOf("e")))}catch(K){}G(String(V))}}let _=Y;if(W[Y]==="-")Y++;while(W[Y]&&!",]}".includes(W[Y]))Y++;if(Y==X&&!(U1.NUM&$))J("Unterminated number literal");try{return JSON.parse(W.substring(_,Y))}catch(V){if(W.substring(_,Y)==="-"&&U1.NUM&$)J("Not sure what '-' is");try{return JSON.parse(W.substring(_,W.lastIndexOf("e")))}catch(K){G(String(K))}}},U=()=>{while(Y<X&&`
42
- \r `.includes(W[Y]))Y++};return H()},qJ=(W)=>OV(W,U1.ALL^U1.NUM);var r8=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},N0=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},G1,W2,t8,S2,CJ,sX,kJ,jJ,IJ,eX,fJ,fH;class G8 extends y4{constructor(W){super();G1.add(this),W2.set(this,void 0),t8.set(this,void 0),S2.set(this,void 0),r8(this,W2,W,"f"),r8(this,t8,[],"f")}get currentChatCompletionSnapshot(){return N0(this,S2,"f")}static fromReadableStream(W){let $=new G8(null);return $._run(()=>$._fromReadableStream(W)),$}static createChatCompletion(W,$,X){let Y=new G8($);return Y._run(()=>Y._runChatCompletion(W,{...$,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createChatCompletion(W,$,X){super._createChatCompletion;let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}N0(this,G1,"m",CJ).call(this);let J=await W.chat.completions.create({...$,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let G of J)N0(this,G1,"m",kJ).call(this,G);if(J.controller.signal?.aborted)throw new J1;return this._addChatCompletion(N0(this,G1,"m",eX).call(this))}async _fromReadableStream(W,$){let X=$?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}N0(this,G1,"m",CJ).call(this),this._connected();let Y=n1.fromReadableStream(W,this.controller),J;for await(let G of Y){if(J&&J!==G.id)this._addChatCompletion(N0(this,G1,"m",eX).call(this));N0(this,G1,"m",kJ).call(this,G),J=G.id}if(Y.controller.signal?.aborted)throw new J1;return this._addChatCompletion(N0(this,G1,"m",eX).call(this))}[(W2=new WeakMap,t8=new WeakMap,S2=new WeakMap,G1=new WeakSet,CJ=function W(){if(this.ended)return;r8(this,S2,void 0,"f")},sX=function W($){let X=N0(this,t8,"f")[$.index];if(X)return X;return X={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},N0(this,t8,"f")[$.index]=X,X},kJ=function W($){if(this.ended)return;let X=N0(this,G1,"m",fH).call(this,$);this._emit("chunk",$,X);for(let Y of $.choices){let J=X.choices[Y.index];if(Y.delta.content!=null&&J.message?.role==="assistant"&&J.message?.content)this._emit("content",Y.delta.content,J.message.content),this._emit("content.delta",{delta:Y.delta.content,snapshot:J.message.content,parsed:J.message.parsed});if(Y.delta.refusal!=null&&J.message?.role==="assistant"&&J.message?.refusal)this._emit("refusal.delta",{delta:Y.delta.refusal,snapshot:J.message.refusal});if(Y.logprobs?.content!=null&&J.message?.role==="assistant")this._emit("logprobs.content.delta",{content:Y.logprobs?.content,snapshot:J.logprobs?.content??[]});if(Y.logprobs?.refusal!=null&&J.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:Y.logprobs?.refusal,snapshot:J.logprobs?.refusal??[]});let G=N0(this,G1,"m",sX).call(this,J);if(J.finish_reason){if(N0(this,G1,"m",IJ).call(this,J),G.current_tool_call_index!=null)N0(this,G1,"m",jJ).call(this,J,G.current_tool_call_index)}for(let H of Y.delta.tool_calls??[]){if(G.current_tool_call_index!==H.index){if(N0(this,G1,"m",IJ).call(this,J),G.current_tool_call_index!=null)N0(this,G1,"m",jJ).call(this,J,G.current_tool_call_index)}G.current_tool_call_index=H.index}for(let H of Y.delta.tool_calls??[]){let Q=J.message.tool_calls?.[H.index];if(!Q?.type)continue;if(Q?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:Q.function?.name,index:H.index,arguments:Q.function.arguments,parsed_arguments:Q.function.parsed_arguments,arguments_delta:H.function?.arguments??""});else xH(Q?.type)}}},jJ=function W($,X){if(N0(this,G1,"m",sX).call(this,$).done_tool_calls.has(X))return;let J=$.message.tool_calls?.[X];if(!J)throw new Error("no tool call snapshot");if(!J.type)throw new Error("tool call snapshot missing `type`");if(J.type==="function"){let G=N0(this,W2,"f")?.tools?.find((H)=>H.type==="function"&&H.function.name===J.function.name);this._emit("tool_calls.function.arguments.done",{name:J.function.name,index:X,arguments:J.function.arguments,parsed_arguments:J8(G)?G.$parseRaw(J.function.arguments):G?.function.strict?JSON.parse(J.function.arguments):null})}else xH(J.type)},IJ=function W($){let X=N0(this,G1,"m",sX).call(this,$);if($.message.content&&!X.content_done){X.content_done=!0;let Y=N0(this,G1,"m",fJ).call(this);this._emit("content.done",{content:$.message.content,parsed:Y?Y.$parseRaw($.message.content):null})}if($.message.refusal&&!X.refusal_done)X.refusal_done=!0,this._emit("refusal.done",{refusal:$.message.refusal});if($.logprobs?.content&&!X.logprobs_content_done)X.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:$.logprobs.content});if($.logprobs?.refusal&&!X.logprobs_refusal_done)X.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:$.logprobs.refusal})},eX=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=N0(this,S2,"f");if(!$)throw new o("request ended without sending any chunks");return r8(this,S2,void 0,"f"),r8(this,t8,[],"f"),AV($,N0(this,W2,"f"))},fJ=function W(){let $=N0(this,W2,"f")?.response_format;if(v4($))return $;return null},fH=function W($){var X,Y,J,G;let H=N0(this,S2,"f"),{choices:Q,...z}=$;if(!H)H=r8(this,S2,{...z,choices:[]},"f");else Object.assign(H,z);for(let{delta:F,finish_reason:T,index:U,logprobs:_=null,...V}of $.choices){let K=H.choices[U];if(!K)K=H.choices[U]={finish_reason:T,index:U,message:{},logprobs:_,...V};if(_)if(!K.logprobs)K.logprobs=Object.assign({},_);else{let{content:c,refusal:v,...h}=_;if(PH(h),Object.assign(K.logprobs,h),c)(X=K.logprobs).content??(X.content=[]),K.logprobs.content.push(...c);if(v)(Y=K.logprobs).refusal??(Y.refusal=[]),K.logprobs.refusal.push(...v)}if(T){if(K.finish_reason=T,N0(this,W2,"f")&&LJ(N0(this,W2,"f"))){if(T==="length")throw new K4;if(T==="content_filter")throw new A4}}if(Object.assign(K,V),!F)continue;let{content:B,refusal:I,function_call:C,role:R,tool_calls:q,...m}=F;if(PH(m),Object.assign(K.message,m),I)K.message.refusal=(K.message.refusal||"")+I;if(R)K.message.role=R;if(C)if(!K.message.function_call)K.message.function_call=C;else{if(C.name)K.message.function_call.name=C.name;if(C.arguments)(J=K.message.function_call).arguments??(J.arguments=""),K.message.function_call.arguments+=C.arguments}if(B){if(K.message.content=(K.message.content||"")+B,!K.message.refusal&&N0(this,G1,"m",fJ).call(this))K.message.parsed=qJ(K.message.content)}if(q){if(!K.message.tool_calls)K.message.tool_calls=[];for(let{index:c,id:v,type:h,function:w0,...p0}of q){let L=(G=K.message.tool_calls)[c]??(G[c]={});if(Object.assign(L,p0),v)L.id=v;if(h)L.type=h;if(w0)L.function??(L.function={name:w0.name??"",arguments:""});if(w0?.name)L.function.name=w0.name;if(w0?.arguments){if(L.function.arguments+=w0.arguments,SH(N0(this,W2,"f"),L))L.function.parsed_arguments=qJ(L.function.arguments)}}}}return H},Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("chunk",(Y)=>{let J=$.shift();if(J)J.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((J,G)=>$.push({resolve:J,reject:G})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new n1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function AV(W,$){let{id:X,choices:Y,created:J,model:G,system_fingerprint:H,...Q}=W,z={...Q,id:X,choices:Y.map(({message:F,finish_reason:T,index:U,logprobs:_,...V})=>{if(!T)throw new o(`missing finish_reason for choice ${U}`);let{content:K=null,function_call:B,tool_calls:I,...C}=F,R=F.role;if(!R)throw new o(`missing role for choice ${U}`);if(B){let{arguments:q,name:m}=B;if(q==null)throw new o(`missing function_call.arguments for choice ${U}`);if(!m)throw new o(`missing function_call.name for choice ${U}`);return{...V,message:{content:K,function_call:{arguments:q,name:m},role:R,refusal:F.refusal??null},finish_reason:T,index:U,logprobs:_}}if(I)return{...V,index:U,finish_reason:T,logprobs:_,message:{...C,role:R,content:K,refusal:F.refusal??null,tool_calls:I.map((q,m)=>{let{function:c,type:v,id:h,...w0}=q,{arguments:p0,name:L,...M0}=c||{};if(h==null)throw new o(`missing choices[${U}].tool_calls[${m}].id
43
- ${WY(W)}`);if(v==null)throw new o(`missing choices[${U}].tool_calls[${m}].type
44
- ${WY(W)}`);if(L==null)throw new o(`missing choices[${U}].tool_calls[${m}].function.name
45
- ${WY(W)}`);if(p0==null)throw new o(`missing choices[${U}].tool_calls[${m}].function.arguments
46
- ${WY(W)}`);return{...w0,id:h,type:v,function:{...M0,name:L,arguments:p0}}})}};return{...V,message:{...C,content:K,role:R,refusal:F.refusal??null},finish_reason:T,index:U,logprobs:_}}),created:J,model:G,object:"chat.completion",...H?{system_fingerprint:H}:{}};return ZH(z,$)}function WY(W){return JSON.stringify(W)}function PH(W){return}function xH(W){}class H8 extends G8{static fromReadableStream(W){let $=new H8(null);return $._run(()=>$._fromReadableStream(W)),$}static runFunctions(W,$,X){let Y=new H8(null),J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return Y._run(()=>Y._runFunctions(W,$,J)),Y}static runTools(W,$,X){let Y=new H8($),J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools(W,$,J)),Y}}class $Y extends k{parse(W,$){return qH(W.tools),this._client.chat.completions.create(W,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((X)=>b4(X,W))}runFunctions(W,$){if(W.stream)return H8.runFunctions(this._client,W,$);return n8.runFunctions(this._client,W,$)}runTools(W,$){if(W.stream)return H8.runTools(this._client,W,$);return n8.runTools(this._client,W,$)}stream(W,$){return G8.createChatCompletion(this._client,W,$)}}class h4 extends k{constructor(){super(...arguments);this.completions=new $Y(this._client)}}(function(W){W.Completions=$Y})(h4||(h4={}));class g4 extends k{create(W,$){return this._client.post("/realtime/sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class m4 extends k{create(W,$){return this._client.post("/realtime/transcription_sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class Q8 extends k{constructor(){super(...arguments);this.sessions=new g4(this._client),this.transcriptionSessions=new m4(this._client)}}Q8.Sessions=g4;Q8.TranscriptionSessions=m4;class a8 extends k{create(W,$,X){return this._client.post(`/threads/${W}/messages`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/threads/${W}/messages/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/threads/${W}/messages/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/messages`,p4,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$,X){return this._client.delete(`/threads/${W}/messages/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class p4 extends E0{}a8.MessagesPage=p4;class s8 extends k{retrieve(W,$,X,Y={},J){if(z0(Y))return this.retrieve(W,$,X,{},Y);return this._client.get(`/threads/${W}/runs/${$}/steps/${X}`,{query:Y,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}list(W,$,X={},Y){if(z0(X))return this.list(W,$,{},X);return this._client.getAPIList(`/threads/${W}/runs/${$}/steps`,u4,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}class u4 extends E0{}s8.RunStepsPage=u4;class q2 extends k{constructor(){super(...arguments);this.steps=new s8(this._client)}create(W,$,X){let{include:Y,...J}=$;return this._client.post(`/threads/${W}/runs`,{query:{include:Y},body:J,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers},stream:$.stream??!1})}retrieve(W,$,X){return this._client.get(`/threads/${W}/runs/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/threads/${W}/runs/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/runs`,c4,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}cancel(W,$,X){return this._client.post(`/threads/${W}/runs/${$}/cancel`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$,X);return await this.poll(W,Y.id,X)}createAndStream(W,$,X){return a1.createAssistantStream(W,this._client.beta.threads.runs,$,X)}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let{data:J,response:G}=await this.retrieve(W,$,{...X,headers:{...X?.headers,...Y}}).withResponse();switch(J.status){case"queued":case"in_progress":case"cancelling":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=G.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await tW(H);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return J}}}stream(W,$,X){return a1.createAssistantStream(W,this._client.beta.threads.runs,$,X)}submitToolOutputs(W,$,X,Y){return this._client.post(`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers},stream:X.stream??!1})}async submitToolOutputsAndPoll(W,$,X,Y){let J=await this.submitToolOutputs(W,$,X,Y);return await this.poll(W,J.id,Y)}submitToolOutputsStream(W,$,X,Y){return a1.createToolAssistantStream(W,$,this._client.beta.threads.runs,X,Y)}}class c4 extends E0{}q2.RunsPage=c4;q2.Steps=s8;q2.RunStepsPage=u4;class $2 extends k{constructor(){super(...arguments);this.runs=new q2(this._client),this.messages=new a8(this._client)}create(W={},$){if(z0(W))return this.create({},W);return this._client.post("/threads",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/threads/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/threads/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$){return this._client.delete(`/threads/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}createAndRun(W,$){return this._client.post("/threads/runs",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:W.stream??!1})}async createAndRunPoll(W,$){let X=await this.createAndRun(W,$);return await this.runs.poll(X.thread_id,X.id,$)}createAndRunStream(W,$){return a1.createThreadAssistantStream(W,this._client.beta.threads,$)}}$2.Runs=q2;$2.RunsPage=c4;$2.Messages=a8;$2.MessagesPage=p4;class gW extends k{constructor(){super(...arguments);this.realtime=new Q8(this._client),this.chat=new h4(this._client),this.assistants=new i8(this._client),this.threads=new $2(this._client)}}gW.Realtime=Q8;gW.Assistants=i8;gW.AssistantsPage=x4;gW.Threads=$2;class e8 extends k{create(W,$){return this._client.post("/completions",{body:W,...$,stream:W.stream??!1})}}class W$ extends k{create(W,$){let X=!!W.encoding_format,Y=X?W.encoding_format:"base64";if(X)rW("Request","User defined encoding_format:",W.encoding_format);let J=this._client.post("/embeddings",{body:{...W,encoding_format:Y},...$});if(X)return J;return rW("response","Decoding base64 embeddings to float32 array"),J._thenUnwrap((G)=>{if(G&&G.data)G.data.forEach((H)=>{let Q=H.embedding;H.embedding=VH(Q)});return G})}}class $$ extends k{retrieve(W,$,X,Y){return this._client.get(`/evals/${W}/runs/${$}/output_items/${X}`,Y)}list(W,$,X={},Y){if(z0(X))return this.list(W,$,{},X);return this._client.getAPIList(`/evals/${W}/runs/${$}/output_items`,d4,{query:X,...Y})}}class d4 extends E0{}$$.OutputItemListResponsesPage=d4;class C2 extends k{constructor(){super(...arguments);this.outputItems=new $$(this._client)}create(W,$,X){return this._client.post(`/evals/${W}/runs`,{body:$,...X})}retrieve(W,$,X){return this._client.get(`/evals/${W}/runs/${$}`,X)}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/evals/${W}/runs`,l4,{query:$,...X})}del(W,$,X){return this._client.delete(`/evals/${W}/runs/${$}`,X)}cancel(W,$,X){return this._client.post(`/evals/${W}/runs/${$}`,X)}}class l4 extends E0{}C2.RunListResponsesPage=l4;C2.OutputItems=$$;C2.OutputItemListResponsesPage=d4;class X2 extends k{constructor(){super(...arguments);this.runs=new C2(this._client)}create(W,$){return this._client.post("/evals",{body:W,...$})}retrieve(W,$){return this._client.get(`/evals/${W}`,$)}update(W,$,X){return this._client.post(`/evals/${W}`,{body:$,...X})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/evals",X$,{query:W,...$})}del(W,$){return this._client.delete(`/evals/${W}`,$)}}class X$ extends E0{}X2.EvalListResponsesPage=X$;X2.Runs=C2;X2.RunListResponsesPage=l4;class z8 extends k{create(W,$){return this._client.post("/files",JW({body:W,...$}))}retrieve(W,$){return this._client.get(`/files/${W}`,$)}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/files",Y$,{query:W,...$})}del(W,$){return this._client.delete(`/files/${W}`,$)}content(W,$){return this._client.get(`/files/${W}/content`,{...$,headers:{Accept:"application/binary",...$?.headers},__binaryResponse:!0})}retrieveContent(W,$){return this._client.get(`/files/${W}/content`,$)}async waitForProcessing(W,{pollInterval:$=5000,maxWait:X=1800000}={}){let Y=new Set(["processed","error","deleted"]),J=Date.now(),G=await this.retrieve(W);while(!G.status||!Y.has(G.status))if(await tW($),G=await this.retrieve(W),Date.now()-J>X)throw new t2({message:`Giving up on waiting for file ${W} to finish processing after ${X} milliseconds.`});return G}}class Y$ extends E0{}z8.FileObjectsPage=Y$;class o4 extends k{}class i4 extends k{run(W,$){return this._client.post("/fine_tuning/alpha/graders/run",{body:W,...$})}validate(W,$){return this._client.post("/fine_tuning/alpha/graders/validate",{body:W,...$})}}class J$ extends k{constructor(){super(...arguments);this.graders=new i4(this._client)}}J$.Graders=i4;class G$ extends k{create(W,$,X){return this._client.getAPIList(`/fine_tuning/checkpoints/${W}/permissions`,n4,{body:$,method:"post",...X})}retrieve(W,$={},X){if(z0($))return this.retrieve(W,{},$);return this._client.get(`/fine_tuning/checkpoints/${W}/permissions`,{query:$,...X})}del(W,$,X){return this._client.delete(`/fine_tuning/checkpoints/${W}/permissions/${$}`,X)}}class n4 extends aW{}G$.PermissionCreateResponsesPage=n4;class F8 extends k{constructor(){super(...arguments);this.permissions=new G$(this._client)}}F8.Permissions=G$;F8.PermissionCreateResponsesPage=n4;class H$ extends k{list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/checkpoints`,r4,{query:$,...X})}}class r4 extends E0{}H$.FineTuningJobCheckpointsPage=r4;class Y2 extends k{constructor(){super(...arguments);this.checkpoints=new H$(this._client)}create(W,$){return this._client.post("/fine_tuning/jobs",{body:W,...$})}retrieve(W,$){return this._client.get(`/fine_tuning/jobs/${W}`,$)}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/fine_tuning/jobs",t4,{query:W,...$})}cancel(W,$){return this._client.post(`/fine_tuning/jobs/${W}/cancel`,$)}listEvents(W,$={},X){if(z0($))return this.listEvents(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/events`,a4,{query:$,...X})}pause(W,$){return this._client.post(`/fine_tuning/jobs/${W}/pause`,$)}resume(W,$){return this._client.post(`/fine_tuning/jobs/${W}/resume`,$)}}class t4 extends E0{}class a4 extends E0{}Y2.FineTuningJobsPage=t4;Y2.FineTuningJobEventsPage=a4;Y2.Checkpoints=H$;Y2.FineTuningJobCheckpointsPage=r4;class GW extends k{constructor(){super(...arguments);this.methods=new o4(this._client),this.jobs=new Y2(this._client),this.checkpoints=new F8(this._client),this.alpha=new J$(this._client)}}GW.Methods=o4;GW.Jobs=Y2;GW.FineTuningJobsPage=t4;GW.FineTuningJobEventsPage=a4;GW.Checkpoints=F8;GW.Alpha=J$;class s4 extends k{}class T8 extends k{constructor(){super(...arguments);this.graderModels=new s4(this._client)}}T8.GraderModels=s4;class Q$ extends k{createVariation(W,$){return this._client.post("/images/variations",JW({body:W,...$}))}edit(W,$){return this._client.post("/images/edits",JW({body:W,...$}))}generate(W,$){return this._client.post("/images/generations",{body:W,...$})}}class U8 extends k{retrieve(W,$){return this._client.get(`/models/${W}`,$)}list(W){return this._client.getAPIList("/models",z$,W)}del(W,$){return this._client.delete(`/models/${W}`,$)}}class z$ extends aW{}U8.ModelsPage=z$;class F$ extends k{create(W,$){return this._client.post("/moderations",{body:W,...$})}}function vH(W,$){if(!$||!mV($))return{...W,output_parsed:null,output:W.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:null};if(X.type==="message")return{...X,content:X.content.map((Y)=>({...Y,parsed:null}))};else return X})};return PJ(W,$)}function PJ(W,$){let X=W.output.map((J)=>{if(J.type==="function_call")return{...J,parsed_arguments:cV($,J)};if(J.type==="message"){let G=J.content.map((H)=>{if(H.type==="output_text")return{...H,parsed:gV($,H.text)};return H});return{...J,content:G}}return J}),Y=Object.assign({},W,{output:X});if(!Object.getOwnPropertyDescriptor(W,"output_text"))xJ(Y);return Object.defineProperty(Y,"output_parsed",{enumerable:!0,get(){for(let J of Y.output){if(J.type!=="message")continue;for(let G of J.content)if(G.type==="output_text"&&G.parsed!==null)return G.parsed}return null}}),Y}function gV(W,$){if(W.text?.format?.type!=="json_schema")return null;if("$parseRaw"in W.text?.format)return(W.text?.format).$parseRaw($);return JSON.parse($)}function mV(W){if(v4(W.text?.format))return!0;return!1}function pV(W){return W?.$brand==="auto-parseable-tool"}function uV(W,$){return W.find((X)=>X.type==="function"&&X.name===$)}function cV(W,$){let X=uV(W.tools??[],$.name);return{...$,...$,parsed_arguments:pV(X)?X.$parseRaw($.arguments):X?.strict?JSON.parse($.arguments):null}}function xJ(W){let $=[];for(let X of W.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text")$.push(Y.text)}W.output_text=$.join("")}class e4 extends k{list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/responses/${W}/input_items`,vJ,{query:$,...X})}}var T$=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},k2=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},U$,XY,j2,YY,bH,yH,hH,gH;class JY extends $8{constructor(W){super();U$.add(this),XY.set(this,void 0),j2.set(this,void 0),YY.set(this,void 0),T$(this,XY,W,"f")}static createResponse(W,$,X){let Y=new JY($);return Y._run(()=>Y._createResponse(W,$,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createResponse(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}k2(this,U$,"m",bH).call(this);let J=await W.responses.create({...$,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let G of J)k2(this,U$,"m",yH).call(this,G);if(J.controller.signal?.aborted)throw new J1;return k2(this,U$,"m",hH).call(this)}[(XY=new WeakMap,j2=new WeakMap,YY=new WeakMap,U$=new WeakSet,bH=function W(){if(this.ended)return;T$(this,j2,void 0,"f")},yH=function W($){if(this.ended)return;let X=k2(this,U$,"m",gH).call(this,$);switch(this._emit("event",$),$.type){case"response.output_text.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message"){let J=Y.content[$.content_index];if(!J)throw new o(`missing content at index ${$.content_index}`);if(J.type!=="output_text")throw new o(`expected content to be 'output_text', got ${J.type}`);this._emit("response.output_text.delta",{...$,snapshot:J.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="function_call")this._emit("response.function_call_arguments.delta",{...$,snapshot:Y.arguments});break}default:this._emit($.type,$);break}},hH=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=k2(this,j2,"f");if(!$)throw new o("request ended without sending any events");T$(this,j2,void 0,"f");let X=lV($,k2(this,XY,"f"));return T$(this,YY,X,"f"),X},gH=function W($){let X=k2(this,j2,"f");if(!X){if($.type!=="response.created")throw new o(`When snapshot hasn't been set yet, expected 'response.created' event, got ${$.type}`);return X=T$(this,j2,$.response,"f"),X}switch($.type){case"response.output_item.added":{X.output.push($.item);break}case"response.content_part.added":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message")Y.content.push($.part);break}case"response.output_text.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message"){let J=Y.content[$.content_index];if(!J)throw new o(`missing content at index ${$.content_index}`);if(J.type!=="output_text")throw new o(`expected content to be 'output_text', got ${J.type}`);J.text+=$.delta}break}case"response.function_call_arguments.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="function_call")Y.arguments+=$.delta;break}case"response.completed":{T$(this,j2,$.response,"f");break}}return X},Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("event",(Y)=>{let J=$.shift();if(J)J.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((J,G)=>$.push({resolve:J,reject:G})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let W=k2(this,YY,"f");if(!W)throw new o("stream ended without producing a ChatCompletion");return W}}function lV(W,$){return vH(W,$)}class w8 extends k{constructor(){super(...arguments);this.inputItems=new e4(this._client)}create(W,$){return this._client.post("/responses",{body:W,...$,stream:W.stream??!1})._thenUnwrap((X)=>{if("object"in X&&X.object==="response")xJ(X);return X})}retrieve(W,$={},X){if(z0($))return this.retrieve(W,{},$);return this._client.get(`/responses/${W}`,{query:$,...X})}del(W,$){return this._client.delete(`/responses/${W}`,{...$,headers:{Accept:"*/*",...$?.headers}})}parse(W,$){return this._client.responses.create(W,$)._thenUnwrap((X)=>PJ(X,W))}stream(W,$){return JY.createResponse(this._client,W,$)}}class vJ extends E0{}w8.InputItems=e4;class W6 extends k{create(W,$,X){return this._client.post(`/uploads/${W}/parts`,JW({body:$,...X}))}}class _8 extends k{constructor(){super(...arguments);this.parts=new W6(this._client)}create(W,$){return this._client.post("/uploads",{body:W,...$})}cancel(W,$){return this._client.post(`/uploads/${W}/cancel`,$)}complete(W,$,X){return this._client.post(`/uploads/${W}/complete`,{body:$,...X})}}_8.Parts=W6;var mH=async(W)=>{let $=await Promise.allSettled(W),X=$.filter((J)=>J.status==="rejected");if(X.length){for(let J of X)console.error(J.reason);throw new Error(`${X.length} promise(s) failed - see the above errors`)}let Y=[];for(let J of $)if(J.status==="fulfilled")Y.push(J.value);return Y};class D8 extends k{create(W,$,X){return this._client.post(`/vector_stores/${W}/files`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/vector_stores/${W}/files/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/vector_stores/${W}/files/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/vector_stores/${W}/files`,M8,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$,X){return this._client.delete(`/vector_stores/${W}/files/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$,X);return await this.poll(W,Y.id,X)}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let J=await this.retrieve(W,$,{...X,headers:Y}).withResponse(),G=J.data;switch(G.status){case"in_progress":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=J.response.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await tW(H);break;case"failed":case"completed":return G}}}async upload(W,$,X){let Y=await this._client.files.create({file:$,purpose:"assistants"},X);return this.create(W,{file_id:Y.id},X)}async uploadAndPoll(W,$,X){let Y=await this.upload(W,$,X);return await this.poll(W,Y.id,X)}content(W,$,X){return this._client.getAPIList(`/vector_stores/${W}/files/${$}/content`,$6,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class M8 extends E0{}class $6 extends aW{}D8.VectorStoreFilesPage=M8;D8.FileContentResponsesPage=$6;class X6 extends k{create(W,$,X){return this._client.post(`/vector_stores/${W}/file_batches`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/vector_stores/${W}/file_batches/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}cancel(W,$,X){return this._client.post(`/vector_stores/${W}/file_batches/${$}/cancel`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$);return await this.poll(W,Y.id,X)}listFiles(W,$,X={},Y){if(z0(X))return this.listFiles(W,$,{},X);return this._client.getAPIList(`/vector_stores/${W}/file_batches/${$}/files`,M8,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let{data:J,response:G}=await this.retrieve(W,$,{...X,headers:Y}).withResponse();switch(J.status){case"in_progress":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=G.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await tW(H);break;case"failed":case"cancelled":case"completed":return J}}}async uploadAndPoll(W,{files:$,fileIds:X=[]},Y){if($==null||$.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let J=Y?.maxConcurrency??5,G=Math.min(J,$.length),H=this._client,Q=$.values(),z=[...X];async function F(U){for(let _ of U){let V=await H.files.create({file:_,purpose:"assistants"},Y);z.push(V.id)}}let T=Array(G).fill(Q).map(F);return await mH(T),await this.createAndPoll(W,{file_ids:z})}}class HW extends k{constructor(){super(...arguments);this.files=new D8(this._client),this.fileBatches=new X6(this._client)}create(W,$){return this._client.post("/vector_stores",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/vector_stores/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/vector_stores/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/vector_stores",w$,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/vector_stores/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}search(W,$,X){return this._client.getAPIList(`/vector_stores/${W}/search`,_$,{body:$,method:"post",...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class w$ extends E0{}class _$ extends aW{}HW.VectorStoresPage=w$;HW.VectorStoreSearchResponsesPage=_$;HW.Files=D8;HW.VectorStoreFilesPage=M8;HW.FileContentResponsesPage=$6;HW.FileBatches=X6;var pH;class H0 extends DJ{constructor({baseURL:W=L4("OPENAI_BASE_URL"),apiKey:$=L4("OPENAI_API_KEY"),organization:X=L4("OPENAI_ORG_ID")??null,project:Y=L4("OPENAI_PROJECT_ID")??null,...J}={}){if($===void 0)throw new o("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 G={apiKey:$,organization:X,project:Y,...J,baseURL:W||"https://api.openai.com/v1"};if(!G.dangerouslyAllowBrowser&&MH())throw new o(`It looks like you're running in a browser-like environment.
37
+ ${H}`)}let z=LW.join(this.baseDir,`${W}/${$}.output.json`);return JSON.parse(i0.readFileSync(z,"utf-8"))}async write(W,$,X,Y){let G=LW.join(this.baseDir,W),J=LW.join(G,`${$}.input.json`),H=LW.join(G,`${$}.output.json`),Q=JSON.stringify(X,null,"\t");if(!i0.existsSync(this.baseDir))i0.mkdirSync(this.baseDir,{recursive:!0});if(!i0.existsSync(G))i0.mkdirSync(G);if(i0.writeFileSync(J,Q),i0.existsSync(H))i0.unlinkSync(H);let z=await Y(...X),T=JSON.stringify(z,null,"\t");return i0.writeFileSync(H,T),z}add(W,$){let X=`${this.rootName}${X1}${A$(W)}`;return{flush:()=>{this.flush(W)},for:(Y)=>{if(this.mode!=="off"){if(this.filesTouched.set(W,new Set),P0.storage.initialized&&!P0.storage.getItem(`list${X1}${X}`))P0.storage.setItem(`list${X1}${X}`,"true")}return{get:async(...G)=>{let J=Y;if(this.mode!=="off"){let H=this.filenameCache.get(Y);if(!H)H=A$(Y),this.filenameCache.set(Y,H);J=H,this.filesTouched.get(W)?.add(J);let Q=`${X}${X1}${J}`,z=`file${X1}${Q}`;if(P0.storage.initialized&&!P0.storage.getItem(z))P0.storage.setItem(z,"true")}switch(this.mode){case"off":return $(...G);case"read":return this.read(W,J,G);case"write":return this.write(W,J,G,$);case"read-write":try{return this.read(W,J,G)}catch(H){if(H instanceof Error)return this.write(W,J,G,$);throw H}}}}}}}flush(...W){console.log(this.filesTouched);for(let[$,X]of this.filesTouched.entries())if(W.length===0||W.includes($)){let Y=LW.join(this.baseDir,$),G=i0.readdirSync(Y);for(let J of G){let H=J.replace(".input.json","").replace(".output.json","");if(!X.has(H))console.info(`\uD83E\uDDF9 Flushing ${H}`),i0.unlinkSync(LW.join(Y,J))}}}};var NX="RFC3986",ZX={RFC1738:(W)=>String(W).replace(/%20/g,"+"),RFC3986:(W)=>String(W)},o3="RFC1738";var kV=Array.isArray,vW=(()=>{let W=[];for(let $=0;$<256;++$)W.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return W})();var a9=1024,i3=(W,$,X,Y,G)=>{if(W.length===0)return W;let J=W;if(typeof W==="symbol")J=Symbol.prototype.toString.call(W);else if(typeof W!=="string")J=String(W);if(X==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let H="";for(let Q=0;Q<J.length;Q+=a9){let z=J.length>=a9?J.slice(Q,Q+a9):J,T=[];for(let F=0;F<z.length;++F){let _=z.charCodeAt(F);if(_===45||_===46||_===95||_===126||_>=48&&_<=57||_>=65&&_<=90||_>=97&&_<=122||G===o3&&(_===40||_===41)){T[T.length]=z.charAt(F);continue}if(_<128){T[T.length]=vW[_];continue}if(_<2048){T[T.length]=vW[192|_>>6]+vW[128|_&63];continue}if(_<55296||_>=57344){T[T.length]=vW[224|_>>12]+vW[128|_>>6&63]+vW[128|_&63];continue}F+=1,_=65536+((_&1023)<<10|z.charCodeAt(F)&1023),T[T.length]=vW[240|_>>18]+vW[128|_>>12&63]+vW[128|_>>6&63]+vW[128|_&63]}H+=T.join("")}return H};function n3(W){if(!W||typeof W!=="object")return!1;return!!(W.constructor&&W.constructor.isBuffer&&W.constructor.isBuffer(W))}function s9(W,$){if(kV(W)){let X=[];for(let Y=0;Y<W.length;Y+=1)X.push($(W[Y]));return X}return $(W)}var jV=Object.prototype.hasOwnProperty,r3={brackets(W){return String(W)+"[]"},comma:"comma",indices(W,$){return String(W)+"["+$+"]"},repeat(W){return String(W)}},yW=Array.isArray,IV=Array.prototype.push,t3=function(W,$){IV.apply(W,yW($)?$:[$])},PV=Date.prototype.toISOString,Y1={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:i3,encodeValuesOnly:!1,format:NX,formatter:ZX[NX],indices:!1,serializeDate(W){return PV.call(W)},skipNulls:!1,strictNullHandling:!1};function fV(W){return typeof W==="string"||typeof W==="number"||typeof W==="boolean"||typeof W==="symbol"||typeof W==="bigint"}var e9={};function a3(W,$,X,Y,G,J,H,Q,z,T,F,_,w,O,M,A,I,j){let R=W,Z=j,P=0,h=!1;while((Z=Z.get(e9))!==void 0&&!h){let B=Z.get(W);if(P+=1,typeof B!=="undefined")if(B===P)throw new RangeError("Cyclic object value");else h=!0;if(typeof Z.get(e9)==="undefined")P=0}if(typeof T==="function")R=T($,R);else if(R instanceof Date)R=w?.(R);else if(X==="comma"&&yW(R))R=s9(R,function(B){if(B instanceof Date)return w?.(B);return B});if(R===null){if(J)return z&&!A?z($,Y1.encoder,I,"key",O):$;R=""}if(fV(R)||n3(R)){if(z){let B=A?$:z($,Y1.encoder,I,"key",O);return[M?.(B)+"="+M?.(z(R,Y1.encoder,I,"value",O))]}return[M?.($)+"="+M?.(String(R))]}let x=[];if(typeof R==="undefined")return x;let m;if(X==="comma"&&yW(R)){if(A&&z)R=s9(R,z);m=[{value:R.length>0?R.join(",")||null:void 0}]}else if(yW(T))m=T;else{let B=Object.keys(R);m=F?B.sort(F):B}let w0=Q?String($).replace(/\./g,"%2E"):String($),p0=Y&&yW(R)&&R.length===1?w0+"[]":w0;if(G&&yW(R)&&R.length===0)return p0+"[]";for(let B=0;B<m.length;++B){let V0=m[B],$0=typeof V0==="object"&&typeof V0.value!=="undefined"?V0.value:R[V0];if(H&&$0===null)continue;let U0=_&&Q?V0.replace(/\./g,"%2E"):V0,e0=yW(R)?typeof X==="function"?X(p0,U0):p0:p0+(_?"."+U0:"["+U0+"]");j.set(W,P);let M1=new WeakMap;M1.set(e9,j),t3(x,a3($0,e0,X,Y,G,J,H,Q,X==="comma"&&A&&yW(R)?null:z,T,F,_,w,O,M,A,I,M1))}return x}function xV(W=Y1){if(typeof W.allowEmptyArrays!=="undefined"&&typeof W.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof W.encodeDotInKeys!=="undefined"&&typeof W.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(W.encoder!==null&&typeof W.encoder!=="undefined"&&typeof W.encoder!=="function")throw new TypeError("Encoder has to be a function.");let $=W.charset||Y1.charset;if(typeof W.charset!=="undefined"&&W.charset!=="utf-8"&&W.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let X=NX;if(typeof W.format!=="undefined"){if(!jV.call(ZX,W.format))throw new TypeError("Unknown format option provided.");X=W.format}let Y=ZX[X],G=Y1.filter;if(typeof W.filter==="function"||yW(W.filter))G=W.filter;let J;if(W.arrayFormat&&W.arrayFormat in r3)J=W.arrayFormat;else if("indices"in W)J=W.indices?"indices":"repeat";else J=Y1.arrayFormat;if("commaRoundTrip"in W&&typeof W.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let H=typeof W.allowDots==="undefined"?!!W.encodeDotInKeys===!0?!0:Y1.allowDots:!!W.allowDots;return{addQueryPrefix:typeof W.addQueryPrefix==="boolean"?W.addQueryPrefix:Y1.addQueryPrefix,allowDots:H,allowEmptyArrays:typeof W.allowEmptyArrays==="boolean"?!!W.allowEmptyArrays:Y1.allowEmptyArrays,arrayFormat:J,charset:$,charsetSentinel:typeof W.charsetSentinel==="boolean"?W.charsetSentinel:Y1.charsetSentinel,commaRoundTrip:!!W.commaRoundTrip,delimiter:typeof W.delimiter==="undefined"?Y1.delimiter:W.delimiter,encode:typeof W.encode==="boolean"?W.encode:Y1.encode,encodeDotInKeys:typeof W.encodeDotInKeys==="boolean"?W.encodeDotInKeys:Y1.encodeDotInKeys,encoder:typeof W.encoder==="function"?W.encoder:Y1.encoder,encodeValuesOnly:typeof W.encodeValuesOnly==="boolean"?W.encodeValuesOnly:Y1.encodeValuesOnly,filter:G,format:X,formatter:Y,serializeDate:typeof W.serializeDate==="function"?W.serializeDate:Y1.serializeDate,skipNulls:typeof W.skipNulls==="boolean"?W.skipNulls:Y1.skipNulls,sort:typeof W.sort==="function"?W.sort:null,strictNullHandling:typeof W.strictNullHandling==="boolean"?W.strictNullHandling:Y1.strictNullHandling}}function W5(W,$={}){let X=W,Y=xV($),G,J;if(typeof Y.filter==="function")J=Y.filter,X=J("",X);else if(yW(Y.filter))J=Y.filter,G=J;let H=[];if(typeof X!=="object"||X===null)return"";let Q=r3[Y.arrayFormat],z=Q==="comma"&&Y.commaRoundTrip;if(!G)G=Object.keys(X);if(Y.sort)G.sort(Y.sort);let T=new WeakMap;for(let w=0;w<G.length;++w){let O=G[w];if(Y.skipNulls&&X[O]===null)continue;t3(H,a3(X[O],O,Q,z,Y.allowEmptyArrays,Y.strictNullHandling,Y.skipNulls,Y.encodeDotInKeys,Y.encode?Y.encoder:null,Y.filter,Y.sort,Y.allowDots,Y.serializeDate,Y.format,Y.formatter,Y.encodeValuesOnly,Y.charset,T))}let F=H.join(Y.delimiter),_=Y.addQueryPrefix===!0?"?":"";if(Y.charsetSentinel)if(Y.charset==="iso-8859-1")_+="utf8=%26%2310003%3B&";else _+="utf8=%E2%9C%93&";return F.length>0?_+F:""}var t2="4.100.0";var s3=!1,a2=void 0,$5=void 0,vV=void 0,yV=void 0,hV=void 0,X5=void 0,gV=void 0,SX=void 0,Y5=void 0,G5=void 0,J5=void 0,qX=void 0,H5=void 0;function e3(W,$={auto:!1}){if(s3)throw new Error(`you must \`import 'openai/shims/${W.kind}'\` before importing anything else from openai`);if(a2)throw new Error(`can't \`import 'openai/shims/${W.kind}'\` after \`import 'openai/shims/${a2}'\``);s3=$.auto,a2=W.kind,$5=W.fetch,vV=W.Request,yV=W.Response,hV=W.Headers,X5=W.FormData,gV=W.Blob,SX=W.File,Y5=W.ReadableStream,G5=W.getMultipartRequestOptions,J5=W.getDefaultAgent,qX=W.fileFromPath,H5=W.isFsReadStream}class Q5{constructor(W){this.body=W}get[Symbol.toStringTag](){return"MultipartBody"}}function WH({manuallyImported:W}={}){let $=W?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",X,Y,G,J;try{X=fetch,Y=Request,G=Response,J=Headers}catch(H){throw new Error(`this environment is missing the following Web Fetch API type: ${H.message}. ${$}`)}return{kind:"web",fetch:X,Request:Y,Response:G,Headers:J,FormData:typeof FormData!=="undefined"?FormData:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${$}`)}},Blob:typeof Blob!=="undefined"?Blob:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${$}`)}},File:typeof File!=="undefined"?File:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${$}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class H{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${$}`)}},getMultipartRequestOptions:async(H,Q)=>({...Q,body:new Q5(H)}),getDefaultAgent:(H)=>{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:(H)=>!1}}import{ReadStream as pV}from"fs";function $H(){let W=WH();function $(X){return X instanceof pV}return{...W,isFsReadStream:$}}var z5=()=>{if(!a2)e3($H(),{auto:!0})};z5();class o extends Error{}class t0 extends o{constructor(W,$,X,Y){super(`${t0.makeMessage(W,$,X)}`);this.status=W,this.headers=Y,this.request_id=Y?.["x-request-id"],this.error=$;let G=$;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage(W,$,X){let Y=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):X;if(W&&Y)return`${W} ${Y}`;if(W)return`${W} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate(W,$,X,Y){if(!W||!Y)return new s2({message:X,cause:vX($)});let G=$?.error;if(W===400)return new CX(W,G,X,Y);if(W===401)return new kX(W,G,X,Y);if(W===403)return new jX(W,G,X,Y);if(W===404)return new IX(W,G,X,Y);if(W===409)return new PX(W,G,X,Y);if(W===422)return new fX(W,G,X,Y);if(W===429)return new xX(W,G,X,Y);if(W>=500)return new bX(W,G,X,Y);return new t0(W,G,X,Y)}}class G1 extends t0{constructor({message:W}={}){super(void 0,void 0,W||"Request was aborted.",void 0)}}class s2 extends t0{constructor({message:W,cause:$}){super(void 0,void 0,W||"Connection error.",void 0);if($)this.cause=$}}class e2 extends s2{constructor({message:W}={}){super({message:W??"Request timed out."})}}class CX extends t0{}class kX extends t0{}class jX extends t0{}class IX extends t0{}class PX extends t0{}class fX extends t0{}class xX extends t0{}class bX extends t0{}class E$ extends o{constructor(){super("Could not parse response content as the length limit was reached")}}class L$ extends o{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var yX=function(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X},W8=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},n1;class l8{constructor(){n1.set(this,void 0),this.buffer=new Uint8Array,yX(this,n1,null,"f")}decode(W){if(W==null)return[];let $=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?new TextEncoder().encode(W):W,X=new Uint8Array(this.buffer.length+$.length);X.set(this.buffer),X.set($,this.buffer.length),this.buffer=X;let Y=[],G;while((G=cV(this.buffer,W8(this,n1,"f")))!=null){if(G.carriage&&W8(this,n1,"f")==null){yX(this,n1,G.index,"f");continue}if(W8(this,n1,"f")!=null&&(G.index!==W8(this,n1,"f")+1||G.carriage)){Y.push(this.decodeText(this.buffer.slice(0,W8(this,n1,"f")-1))),this.buffer=this.buffer.slice(W8(this,n1,"f")),yX(this,n1,null,"f");continue}let J=W8(this,n1,"f")!==null?G.preceding-1:G.preceding,H=this.decodeText(this.buffer.slice(0,J));Y.push(H),this.buffer=this.buffer.slice(G.index),yX(this,n1,null,"f")}return Y}decodeText(W){if(W==null)return"";if(typeof W==="string")return W;if(typeof Buffer!=="undefined"){if(W instanceof Buffer)return W.toString();if(W instanceof Uint8Array)return Buffer.from(W).toString();throw new o(`Unexpected: received non-Uint8Array (${W.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(W instanceof Uint8Array||W instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(W);throw new o(`Unexpected: received non-Uint8Array/ArrayBuffer (${W.constructor.name}) in a web platform. Please report this error.`)}throw new o("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
38
+ `)}}n1=new WeakMap;l8.NEWLINE_CHARS=new Set([`
39
+ `,"\r"]);l8.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function cV(W,$){for(let G=$??0;G<W.length;G++){if(W[G]===10)return{preceding:G,index:G+1,carriage:!1};if(W[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function XH(W){for(let Y=0;Y<W.length-1;Y++){if(W[Y]===10&&W[Y+1]===10)return Y+2;if(W[Y]===13&&W[Y+1]===13)return Y+2;if(W[Y]===13&&W[Y+1]===10&&Y+3<W.length&&W[Y+2]===13&&W[Y+3]===10)return Y+4}return-1}function T5(W){if(W[Symbol.asyncIterator])return W;let $=W.getReader();return{async next(){try{let X=await $.read();if(X?.done)$.releaseLock();return X}catch(X){throw $.releaseLock(),X}},async return(){let X=$.cancel();return $.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class r1{constructor(W,$){this.iterator=W,this.controller=$}static fromSSEResponse(W,$){let X=!1;async function*Y(){if(X)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let G=!1;try{for await(let J of dV(W,$)){if(G)continue;if(J.data.startsWith("[DONE]")){G=!0;continue}if(J.event===null||J.event.startsWith("response.")||J.event.startsWith("transcript.")){let H;try{H=JSON.parse(J.data)}catch(Q){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),Q}if(H&&H.error)throw new t0(void 0,H.error,void 0,F5(W.headers));yield H}else{let H;try{H=JSON.parse(J.data)}catch(Q){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),Q}if(J.event=="error")throw new t0(void 0,H.error,H.message,void 0);yield{event:J.event,data:H}}}G=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!G)$.abort()}}return new r1(Y,$)}static fromReadableStream(W,$){let X=!1;async function*Y(){let J=new l8,H=T5(W);for await(let Q of H)for(let z of J.decode(Q))yield z;for(let Q of J.flush())yield Q}async function*G(){if(X)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let J=!1;try{for await(let H of Y()){if(J)continue;if(H)yield JSON.parse(H)}J=!0}catch(H){if(H instanceof Error&&H.name==="AbortError")return;throw H}finally{if(!J)$.abort()}}return new r1(G,$)}[Symbol.asyncIterator](){return this.iterator()}tee(){let W=[],$=[],X=this.iterator(),Y=(G)=>{return{next:()=>{if(G.length===0){let J=X.next();W.push(J),$.push(J)}return G.shift()}}};return[new r1(()=>Y(W),this.controller),new r1(()=>Y($),this.controller)]}toReadableStream(){let W=this,$,X=new TextEncoder;return new Y5({async start(){$=W[Symbol.asyncIterator]()},async pull(Y){try{let{value:G,done:J}=await $.next();if(J)return Y.close();let H=X.encode(JSON.stringify(G)+`
40
+ `);Y.enqueue(H)}catch(G){Y.error(G)}},async cancel(){await $.return?.()}})}}async function*dV(W,$){if(!W.body)throw $.abort(),new o("Attempted to iterate over a response with no body");let X=new YH,Y=new l8,G=T5(W.body);for await(let J of lV(G))for(let H of Y.decode(J)){let Q=X.decode(H);if(Q)yield Q}for(let J of Y.flush()){let H=X.decode(J);if(H)yield H}}async function*lV(W){let $=new Uint8Array;for await(let X of W){if(X==null)continue;let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?new TextEncoder().encode(X):X,G=new Uint8Array($.length+Y.length);G.set($),G.set(Y,$.length),$=G;let J;while((J=XH($))!==-1)yield $.slice(0,J),$=$.slice(J)}if($.length>0)yield $}class YH{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(W){if(W.endsWith("\r"))W=W.substring(0,W.length-1);if(!W){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
41
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push(W),W.startsWith(":"))return null;let[$,X,Y]=oV(W,":");if(Y.startsWith(" "))Y=Y.substring(1);if($==="event")this.event=Y;else if($==="data")this.data.push(Y);return null}}function oV(W,$){let X=W.indexOf($);if(X!==-1)return[W.substring(0,X),$,W.substring(X+$.length)];return[W,"",""]}var GH=(W)=>W!=null&&typeof W==="object"&&typeof W.url==="string"&&typeof W.blob==="function",JH=(W)=>W!=null&&typeof W==="object"&&typeof W.name==="string"&&typeof W.lastModified==="number"&&B$(W),B$=(W)=>W!=null&&typeof W==="object"&&typeof W.size==="number"&&typeof W.type==="string"&&typeof W.text==="function"&&typeof W.slice==="function"&&typeof W.arrayBuffer==="function",iV=(W)=>{return JH(W)||GH(W)||H5(W)};async function U5(W,$,X){if(W=await W,JH(W))return W;if(GH(W)){let G=await W.blob();$||($=new URL(W.url).pathname.split(/[\\/]/).pop()??"unknown_file");let J=B$(G)?[await G.arrayBuffer()]:[G];return new SX(J,$,X)}let Y=await nV(W);if($||($=tV(W)??"unknown_file"),!X?.type){let G=Y[0]?.type;if(typeof G==="string")X={...X,type:G}}return new SX(Y,$,X)}async function nV(W){let $=[];if(typeof W==="string"||ArrayBuffer.isView(W)||W instanceof ArrayBuffer)$.push(W);else if(B$(W))$.push(await W.arrayBuffer());else if(aV(W))for await(let X of W)$.push(X);else throw new Error(`Unexpected data type: ${typeof W}; constructor: ${W?.constructor?.name}; props: ${rV(W)}`);return $}function rV(W){return`[${Object.getOwnPropertyNames(W).map((X)=>`"${X}"`).join(", ")}]`}function tV(W){return _5(W.name)||_5(W.filename)||_5(W.path)?.split(/[\\/]/).pop()}var _5=(W)=>{if(typeof W==="string")return W;if(typeof Buffer!=="undefined"&&W instanceof Buffer)return String(W);return},aV=(W)=>W!=null&&typeof W==="object"&&typeof W[Symbol.asyncIterator]==="function",D5=(W)=>W&&typeof W==="object"&&W.body&&W[Symbol.toStringTag]==="MultipartBody";var JW=async(W)=>{let $=await HH(W.body);return G5($,W)},HH=async(W)=>{let $=new X5;return await Promise.all(Object.entries(W||{}).map(([X,Y])=>w5($,X,Y))),$};var w5=async(W,$,X)=>{if(X===void 0)return;if(X==null)throw new TypeError(`Received null for "${$}"; to pass null in FormData, you must use the string 'null'`);if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")W.append($,String(X));else if(iV(X)){let Y=await U5(X);W.append($,Y)}else if(Array.isArray(X))await Promise.all(X.map((Y)=>w5(W,$+"[]",Y)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Y,G])=>w5(W,`${$}[${Y}]`,G)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${X} instead`)};var eV=function(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X},WM=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},hX;z5();async function wH(W){let{response:$}=W;if(W.options.stream){if(rW("response",$.status,$.url,$.headers,$.body),W.options.__streamClass)return W.options.__streamClass.fromSSEResponse($,W.controller);return r1.fromSSEResponse($,W.controller)}if($.status===204)return null;if(W.options.__binaryResponse)return $;let Y=$.headers.get("content-type")?.split(";")[0]?.trim();if(Y?.includes("application/json")||Y?.endsWith("+json")){let H=await $.json();return rW("response",$.status,$.url,$.headers,H),UH(H,$)}let J=await $.text();return rW("response",$.status,$.url,$.headers,J),J}function UH(W,$){if(!W||typeof W!=="object"||Array.isArray(W))return W;return Object.defineProperty(W,"_request_id",{value:$.headers.get("x-request-id"),enumerable:!1})}class mX extends Promise{constructor(W,$=wH){super((X)=>{X(null)});this.responsePromise=W,this.parseResponse=$}_thenUnwrap(W){return new mX(this.responsePromise,async($)=>UH(W(await this.parseResponse($),$),$.response))}asResponse(){return this.responsePromise.then((W)=>W.response)}async withResponse(){let[W,$]=await Promise.all([this.parse(),this.asResponse()]);return{data:W,response:$,request_id:$.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(W,$){return this.parse().then(W,$)}catch(W){return this.parse().catch(W)}finally(W){return this.parse().finally(W)}}class M5{constructor({baseURL:W,maxRetries:$=2,timeout:X=600000,httpAgent:Y,fetch:G}){this.baseURL=W,this.maxRetries=V5("maxRetries",$),this.timeout=V5("timeout",X),this.httpAgent=Y,this.fetch=G??$5}authHeaders(W){return{}}defaultHeaders(W){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...GM(),...this.authHeaders(W)}}validateHeaders(W,$){}defaultIdempotencyKey(){return`stainless-node-retry-${zM()}`}get(W,$){return this.methodRequest("get",W,$)}post(W,$){return this.methodRequest("post",W,$)}patch(W,$){return this.methodRequest("patch",W,$)}put(W,$){return this.methodRequest("put",W,$)}delete(W,$){return this.methodRequest("delete",W,$)}methodRequest(W,$,X){return this.request(Promise.resolve(X).then(async(Y)=>{let G=Y&&B$(Y?.body)?new DataView(await Y.body.arrayBuffer()):Y?.body instanceof DataView?Y.body:Y?.body instanceof ArrayBuffer?new DataView(Y.body):Y&&ArrayBuffer.isView(Y?.body)?new DataView(Y.body.buffer):Y?.body;return{method:W,path:$,...Y,body:G}}))}getAPIList(W,$,X){return this.requestAPIList($,{method:"get",path:W,...X})}calculateContentLength(W){if(typeof W==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(W,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(W).length.toString()}else if(ArrayBuffer.isView(W))return W.byteLength.toString();return null}buildRequest(W,{retryCount:$=0}={}){let X={...W},{method:Y,path:G,query:J,headers:H={}}=X,Q=ArrayBuffer.isView(X.body)||X.__binaryRequest&&typeof X.body==="string"?X.body:D5(X.body)?X.body.body:X.body?JSON.stringify(X.body,null,2):null,z=this.calculateContentLength(Q),T=this.buildURL(G,J);if("timeout"in X)V5("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let F=X.httpAgent??this.httpAgent??J5(T),_=X.timeout+1000;if(typeof F?.options?.timeout==="number"&&_>(F.options.timeout??0))F.options.timeout=_;if(this.idempotencyHeader&&Y!=="get"){if(!W.idempotencyKey)W.idempotencyKey=this.defaultIdempotencyKey();H[this.idempotencyHeader]=W.idempotencyKey}let w=this.buildHeaders({options:X,headers:H,contentLength:z,retryCount:$});return{req:{method:Y,...Q&&{body:Q},headers:w,...F&&{agent:F},signal:X.signal??null},url:T,timeout:X.timeout}}buildHeaders({options:W,headers:$,contentLength:X,retryCount:Y}){let G={};if(X)G["content-length"]=X;let J=this.defaultHeaders(W);if(FH(G,J),FH(G,$),D5(W.body)&&a2!=="node")delete G["content-type"];if(gX(J,"x-stainless-retry-count")===void 0&&gX($,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(Y);if(gX(J,"x-stainless-timeout")===void 0&&gX($,"x-stainless-timeout")===void 0&&W.timeout)G["x-stainless-timeout"]=String(Math.trunc(W.timeout/1000));return this.validateHeaders(G,$),G}async prepareOptions(W){}async prepareRequest(W,{url:$,options:X}){}parseHeaders(W){return!W?{}:(Symbol.iterator in W)?Object.fromEntries(Array.from(W).map(($)=>[...$])):{...W}}makeStatusError(W,$,X,Y){return t0.generate(W,$,X,Y)}request(W,$=null){return new mX(this.makeRequest(W,$))}async makeRequest(W,$){let X=await W,Y=X.maxRetries??this.maxRetries;if($==null)$=Y;await this.prepareOptions(X);let{req:G,url:J,timeout:H}=this.buildRequest(X,{retryCount:Y-$});if(await this.prepareRequest(G,{url:J,options:X}),rW("request",J,X,G.headers),X.signal?.aborted)throw new G1;let Q=new AbortController,z=await this.fetchWithTimeout(J,G,H,Q).catch(vX);if(z instanceof Error){if(X.signal?.aborted)throw new G1;if($)return this.retryRequest(X,$);if(z.name==="AbortError")throw new e2;throw new s2({cause:z})}let T=F5(z.headers);if(!z.ok){if($&&this.shouldRetry(z)){let A=`retrying, ${$} attempts remaining`;return rW(`response (error; ${A})`,z.status,J,T),this.retryRequest(X,$,T)}let F=await z.text().catch((A)=>vX(A).message),_=JM(F),w=_?void 0:F;throw rW(`response (error; ${$?"(error; no more retries left)":"(error; not retryable)"})`,z.status,J,T,w),this.makeStatusError(z.status,_,w,T)}return{response:z,options:X,controller:Q}}requestAPIList(W,$){let X=this.makeRequest($,null);return new DH(this,X,W)}buildURL(W,$){let X=QM(W)?new URL(W):new URL(this.baseURL+(this.baseURL.endsWith("/")&&W.startsWith("/")?W.slice(1):W)),Y=this.defaultQuery();if(!VH(Y))$={...Y,...$};if(typeof $==="object"&&$&&!Array.isArray($))X.search=this.stringifyQuery($);return X.toString()}stringifyQuery(W){return Object.entries(W).filter(([$,X])=>typeof X!=="undefined").map(([$,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent($)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent($)}=`;throw new o(`Cannot stringify type ${typeof X}; 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(W,$,X,Y){let{signal:G,...J}=$||{};if(G)G.addEventListener("abort",()=>Y.abort());let H=setTimeout(()=>Y.abort(),X),Q={signal:Y.signal,...J};if(Q.method)Q.method=Q.method.toUpperCase();return this.fetch.call(void 0,W,Q).finally(()=>{clearTimeout(H)})}shouldRetry(W){let $=W.headers.get("x-should-retry");if($==="true")return!0;if($==="false")return!1;if(W.status===408)return!0;if(W.status===409)return!0;if(W.status===429)return!0;if(W.status>=500)return!0;return!1}async retryRequest(W,$,X){let Y,G=X?.["retry-after-ms"];if(G){let H=parseFloat(G);if(!Number.isNaN(H))Y=H}let J=X?.["retry-after"];if(J&&!Y){let H=parseFloat(J);if(!Number.isNaN(H))Y=H*1000;else Y=Date.parse(J)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let H=W.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis($,H)}return await tW(Y),this.makeRequest(W,$-1)}calculateDefaultRetryTimeoutMillis(W,$){let G=$-W,J=Math.min(0.5*Math.pow(2,G),8),H=1-Math.random()*0.25;return J*H*1000}getUserAgent(){return`${this.constructor.name}/JS ${t2}`}}class pX{constructor(W,$,X,Y){hX.set(this,void 0),eV(this,hX,W,"f"),this.options=Y,this.response=$,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let W=this.nextPageInfo();if(!W)throw new o("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let $={...this.options};if("params"in W&&typeof $.query==="object")$.query={...$.query,...W.params};else if("url"in W){let X=[...Object.entries($.query||{}),...W.url.searchParams.entries()];for(let[Y,G]of X)W.url.searchParams.set(Y,G);$.query=void 0,$.path=W.url.toString()}return await WM(this,hX,"f").requestAPIList(this.constructor,$)}async*iterPages(){let W=this;yield W;while(W.hasNextPage())W=await W.getNextPage(),yield W}async*[(hX=new WeakMap,Symbol.asyncIterator)](){for await(let W of this.iterPages())for(let $ of W.getPaginatedItems())yield $}}class DH extends mX{constructor(W,$,X){super($,async(Y)=>new X(W,Y.response,await wH(Y),Y.options))}async*[Symbol.asyncIterator](){let W=await this;for await(let $ of W)yield $}}var F5=(W)=>{return new Proxy(Object.fromEntries(W.entries()),{get($,X){let Y=X.toString();return $[Y.toLowerCase()]||$[Y]}})},$M={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},z0=(W)=>{return typeof W==="object"&&W!==null&&!VH(W)&&Object.keys(W).every(($)=>MH($M,$))},XM=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":t2,"X-Stainless-OS":zH(Deno.build.os),"X-Stainless-Arch":QH(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":t2,"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":t2,"X-Stainless-OS":zH(process.platform),"X-Stainless-Arch":QH(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let W=YM();if(W)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":t2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${W.browser}`,"X-Stainless-Runtime-Version":W.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":t2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function YM(){if(typeof navigator==="undefined"||!navigator)return null;let W=[{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:$,pattern:X}of W){let Y=X.exec(navigator.userAgent);if(Y){let G=Y[1]||0,J=Y[2]||0,H=Y[3]||0;return{browser:$,version:`${G}.${J}.${H}`}}}return null}var QH=(W)=>{if(W==="x32")return"x32";if(W==="x86_64"||W==="x64")return"x64";if(W==="arm")return"arm";if(W==="aarch64"||W==="arm64")return"arm64";if(W)return`other:${W}`;return"unknown"},zH=(W)=>{if(W=W.toLowerCase(),W.includes("ios"))return"iOS";if(W==="android")return"Android";if(W==="darwin")return"MacOS";if(W==="win32")return"Windows";if(W==="freebsd")return"FreeBSD";if(W==="openbsd")return"OpenBSD";if(W==="linux")return"Linux";if(W)return`Other:${W}`;return"Unknown"},TH,GM=()=>{return TH??(TH=XM())},JM=(W)=>{try{return JSON.parse(W)}catch($){return}},HM=/^[a-z][a-z0-9+.-]*:/i,QM=(W)=>{return HM.test(W)},tW=(W)=>new Promise(($)=>setTimeout($,W)),V5=(W,$)=>{if(typeof $!=="number"||!Number.isInteger($))throw new o(`${W} must be an integer`);if($<0)throw new o(`${W} must be a positive integer`);return $},vX=(W)=>{if(W instanceof Error)return W;if(typeof W==="object"&&W!==null)try{return new Error(JSON.stringify(W))}catch{}return new Error(W)};var R$=(W)=>{if(typeof process!=="undefined")return process.env?.[W]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(W)?.trim();return};function VH(W){if(!W)return!0;for(let $ in W)return!1;return!0}function MH(W,$){return Object.prototype.hasOwnProperty.call(W,$)}function FH(W,$){for(let X in $){if(!MH($,X))continue;let Y=X.toLowerCase();if(!Y)continue;let G=$[X];if(G===null)delete W[Y];else if(G!==void 0)W[Y]=G}}var _H=new Set(["authorization","api-key"]);function rW(W,...$){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true"){let X=$.map((Y)=>{if(!Y)return Y;if(Y.headers){let J={...Y,headers:{...Y.headers}};for(let H in Y.headers)if(_H.has(H.toLowerCase()))J.headers[H]="REDACTED";return J}let G=null;for(let J in Y)if(_H.has(J.toLowerCase()))G??(G={...Y}),G[J]="REDACTED";return G??Y});console.log(`OpenAI:DEBUG:${W}`,...X)}}var zM=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(W)=>{let $=Math.random()*16|0;return(W==="x"?$:$&3|8).toString(16)})},OH=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},TM=(W)=>{return typeof W?.get==="function"};var gX=(W,$)=>{let X=$.toLowerCase();if(TM(W)){let Y=$[0]?.toUpperCase()+$.substring(1).replace(/([^\w])(\w)/g,(G,J,H)=>J+H.toUpperCase());for(let G of[$,X,$.toUpperCase(),Y]){let J=W.get(G);if(J)return J}}for(let[Y,G]of Object.entries(W))if(Y.toLowerCase()===X){if(Array.isArray(G)){if(G.length<=1)return G[0];return console.warn(`Received ${G.length} entries for the ${$} header, using the first entry.`),G[0]}return G}return};var KH=(W)=>{if(typeof Buffer!=="undefined"){let $=Buffer.from(W,"base64");return Array.from(new Float32Array($.buffer,$.byteOffset,$.length/Float32Array.BYTES_PER_ELEMENT))}else{let $=atob(W),X=$.length,Y=new Uint8Array(X);for(let G=0;G<X;G++)Y[G]=$.charCodeAt(G);return Array.from(new Float32Array(Y.buffer))}};function N$(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}class aW extends pX{constructor(W,$,X,Y){super(W,$,X,Y);this.data=X.data||[],this.object=X.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class E0 extends pX{constructor(W,$,X,Y){super(W,$,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let W=this.nextPageInfo();if(!W)return null;if("params"in W)return W.params;let $=Object.fromEntries(W.url.searchParams);if(!Object.keys($).length)return null;return $}nextPageInfo(){let W=this.getPaginatedItems();if(!W.length)return null;let $=W[W.length-1]?.id;if(!$)return null;return{params:{after:$}}}}class C{constructor(W){this._client=W}}class Z$ extends C{list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/chat/completions/${W}/messages`,O5,{query:$,...X})}}class $8 extends C{constructor(){super(...arguments);this.messages=new Z$(this._client)}create(W,$){return this._client.post("/chat/completions",{body:W,...$,stream:W.stream??!1})}retrieve(W,$){return this._client.get(`/chat/completions/${W}`,$)}update(W,$,X){return this._client.post(`/chat/completions/${W}`,{body:$,...X})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/chat/completions",X8,{query:W,...$})}del(W,$){return this._client.delete(`/chat/completions/${W}`,$)}}class X8 extends E0{}class O5 extends E0{}$8.ChatCompletionsPage=X8;$8.Messages=Z$;class q2 extends C{constructor(){super(...arguments);this.completions=new $8(this._client)}}q2.Completions=$8;q2.ChatCompletionsPage=X8;class S$ extends C{create(W,$){return this._client.post("/audio/speech",{body:W,...$,headers:{Accept:"application/octet-stream",...$?.headers},__binaryResponse:!0})}}class q$ extends C{create(W,$){return this._client.post("/audio/transcriptions",JW({body:W,...$,stream:W.stream??!1,__metadata:{model:W.model}}))}}class C$ extends C{create(W,$){return this._client.post("/audio/translations",JW({body:W,...$,__metadata:{model:W.model}}))}}class sW extends C{constructor(){super(...arguments);this.transcriptions=new q$(this._client),this.translations=new C$(this._client),this.speech=new S$(this._client)}}sW.Transcriptions=q$;sW.Translations=C$;sW.Speech=S$;class Y8 extends C{create(W,$){return this._client.post("/batches",{body:W,...$})}retrieve(W,$){return this._client.get(`/batches/${W}`,$)}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/batches",o8,{query:W,...$})}cancel(W,$){return this._client.post(`/batches/${W}/cancel`,$)}}class o8 extends E0{}Y8.BatchesPage=o8;var BW=function(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X},c0=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},K5,uX,cX,k$,j$,dX,I$,eW,P$,lX,oX,i8,AH;class G8{constructor(){K5.add(this),this.controller=new AbortController,uX.set(this,void 0),cX.set(this,()=>{}),k$.set(this,()=>{}),j$.set(this,void 0),dX.set(this,()=>{}),I$.set(this,()=>{}),eW.set(this,{}),P$.set(this,!1),lX.set(this,!1),oX.set(this,!1),i8.set(this,!1),BW(this,uX,new Promise((W,$)=>{BW(this,cX,W,"f"),BW(this,k$,$,"f")}),"f"),BW(this,j$,new Promise((W,$)=>{BW(this,dX,W,"f"),BW(this,I$,$,"f")}),"f"),c0(this,uX,"f").catch(()=>{}),c0(this,j$,"f").catch(()=>{})}_run(W){setTimeout(()=>{W().then(()=>{this._emitFinal(),this._emit("end")},c0(this,K5,"m",AH).bind(this))},0)}_connected(){if(this.ended)return;c0(this,cX,"f").call(this),this._emit("connect")}get ended(){return c0(this,P$,"f")}get errored(){return c0(this,lX,"f")}get aborted(){return c0(this,oX,"f")}abort(){this.controller.abort()}on(W,$){return(c0(this,eW,"f")[W]||(c0(this,eW,"f")[W]=[])).push({listener:$}),this}off(W,$){let X=c0(this,eW,"f")[W];if(!X)return this;let Y=X.findIndex((G)=>G.listener===$);if(Y>=0)X.splice(Y,1);return this}once(W,$){return(c0(this,eW,"f")[W]||(c0(this,eW,"f")[W]=[])).push({listener:$,once:!0}),this}emitted(W){return new Promise(($,X)=>{if(BW(this,i8,!0,"f"),W!=="error")this.once("error",X);this.once(W,$)})}async done(){BW(this,i8,!0,"f"),await c0(this,j$,"f")}_emit(W,...$){if(c0(this,P$,"f"))return;if(W==="end")BW(this,P$,!0,"f"),c0(this,dX,"f").call(this);let X=c0(this,eW,"f")[W];if(X)c0(this,eW,"f")[W]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...$));if(W==="abort"){let Y=$[0];if(!c0(this,i8,"f")&&!X?.length)Promise.reject(Y);c0(this,k$,"f").call(this,Y),c0(this,I$,"f").call(this,Y),this._emit("end");return}if(W==="error"){let Y=$[0];if(!c0(this,i8,"f")&&!X?.length)Promise.reject(Y);c0(this,k$,"f").call(this,Y),c0(this,I$,"f").call(this,Y),this._emit("end")}}_emitFinal(){}}uX=new WeakMap,cX=new WeakMap,k$=new WeakMap,j$=new WeakMap,dX=new WeakMap,I$=new WeakMap,eW=new WeakMap,P$=new WeakMap,lX=new WeakMap,oX=new WeakMap,i8=new WeakMap,K5=new WeakSet,AH=function W($){if(BW(this,lX,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new G1;if($ instanceof G1)return BW(this,oX,!0,"f"),this._emit("abort",$);if($ instanceof o)return this._emit("error",$);if($ instanceof Error){let X=new o($.message);return X.cause=$,this._emit("error",X)}return this._emit("error",new o(String($)))};var i=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},t1=function(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X},D1,A5,hW,iX,RW,H8,n8,J8,tX,a1,nX,rX,b$,f$,x$,EH,LH,BH,RH,NH,ZH,SH;class s1 extends G8{constructor(){super(...arguments);D1.add(this),A5.set(this,[]),hW.set(this,{}),iX.set(this,{}),RW.set(this,void 0),H8.set(this,void 0),n8.set(this,void 0),J8.set(this,void 0),tX.set(this,void 0),a1.set(this,void 0),nX.set(this,void 0),rX.set(this,void 0),b$.set(this,void 0)}[(A5=new WeakMap,hW=new WeakMap,iX=new WeakMap,RW=new WeakMap,H8=new WeakMap,n8=new WeakMap,J8=new WeakMap,tX=new WeakMap,a1=new WeakMap,nX=new WeakMap,rX=new WeakMap,b$=new WeakMap,D1=new WeakSet,Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("event",(Y)=>{let G=$.shift();if(G)G.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of $)G.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let G of $)G.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((G,J)=>$.push({resolve:G,reject:J})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(W){let $=new s1;return $._run(()=>$._fromReadableStream(W)),$}async _fromReadableStream(W,$){let X=$?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}this._connected();let Y=r1.fromReadableStream(W,this.controller);for await(let G of Y)i(this,D1,"m",f$).call(this,G);if(Y.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",x$).call(this))}toReadableStream(){return new r1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(W,$,X,Y,G){let J=new s1;return J._run(()=>J._runToolAssistantStream(W,$,X,Y,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(W,$,X,Y,G){let J=G?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let H={...Y,stream:!0},Q=await W.submitToolOutputs($,X,H,{...G,signal:this.controller.signal});this._connected();for await(let z of Q)i(this,D1,"m",f$).call(this,z);if(Q.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",x$).call(this))}static createThreadAssistantStream(W,$,X){let Y=new s1;return Y._run(()=>Y._threadAssistantStream(W,$,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}static createAssistantStream(W,$,X,Y){let G=new s1;return G._run(()=>G._runAssistantStream(W,$,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),G}currentEvent(){return i(this,nX,"f")}currentRun(){return i(this,rX,"f")}currentMessageSnapshot(){return i(this,RW,"f")}currentRunStepSnapshot(){return i(this,b$,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,hW,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,iX,"f"))}async finalRun(){if(await this.done(),!i(this,H8,"f"))throw Error("Final run was not received.");return i(this,H8,"f")}async _createThreadAssistantStream(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let G={...$,stream:!0},J=await W.createAndRun(G,{...X,signal:this.controller.signal});this._connected();for await(let H of J)i(this,D1,"m",f$).call(this,H);if(J.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",x$).call(this))}async _createAssistantStream(W,$,X,Y){let G=Y?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let J={...X,stream:!0},H=await W.create($,J,{...Y,signal:this.controller.signal});this._connected();for await(let Q of H)i(this,D1,"m",f$).call(this,Q);if(H.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",x$).call(this))}static accumulateDelta(W,$){for(let[X,Y]of Object.entries($)){if(!W.hasOwnProperty(X)){W[X]=Y;continue}let G=W[X];if(G===null||G===void 0){W[X]=Y;continue}if(X==="index"||X==="type"){W[X]=Y;continue}if(typeof G==="string"&&typeof Y==="string")G+=Y;else if(typeof G==="number"&&typeof Y==="number")G+=Y;else if(N$(G)&&N$(Y))G=this.accumulateDelta(G,Y);else if(Array.isArray(G)&&Array.isArray(Y)){if(G.every((J)=>typeof J==="string"||typeof J==="number")){G.push(...Y);continue}for(let J of Y){if(!N$(J))throw new Error(`Expected array delta entry to be an object but got: ${J}`);let H=J.index;if(H==null)throw console.error(J),new Error("Expected array delta entry to have an `index` property");if(typeof H!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${H}`);let Q=G[H];if(Q==null)G.push(J);else G[H]=this.accumulateDelta(Q,J)}continue}else throw Error(`Unhandled record type: ${X}, deltaValue: ${Y}, accValue: ${G}`);W[X]=G}return W}_addRun(W){return W}async _threadAssistantStream(W,$,X){return await this._createThreadAssistantStream($,W,X)}async _runAssistantStream(W,$,X,Y){return await this._createAssistantStream($,W,X,Y)}async _runToolAssistantStream(W,$,X,Y,G){return await this._createToolAssistantStream(X,W,$,Y,G)}}f$=function W($){if(this.ended)return;switch(t1(this,nX,$,"f"),i(this,D1,"m",BH).call(this,$),$.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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":i(this,D1,"m",SH).call(this,$);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":i(this,D1,"m",LH).call(this,$);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,D1,"m",EH).call(this,$);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:VM($)}},x$=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");if(!i(this,H8,"f"))throw Error("Final run has not been received");return i(this,H8,"f")},EH=function W($){let[X,Y]=i(this,D1,"m",NH).call(this,$,i(this,RW,"f"));t1(this,RW,X,"f"),i(this,iX,"f")[X.id]=X;for(let G of Y){let J=X.content[G.index];if(J?.type=="text")this._emit("textCreated",J.text)}switch($.event){case"thread.message.created":this._emit("messageCreated",$.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",$.data.delta,X),$.data.delta.content)for(let G of $.data.delta.content){if(G.type=="text"&&G.text){let J=G.text,H=X.content[G.index];if(H&&H.type=="text")this._emit("textDelta",J,H.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(G.index!=i(this,n8,"f")){if(i(this,J8,"f"))switch(i(this,J8,"f").type){case"text":this._emit("textDone",i(this,J8,"f").text,i(this,RW,"f"));break;case"image_file":this._emit("imageFileDone",i(this,J8,"f").image_file,i(this,RW,"f"));break}t1(this,n8,G.index,"f")}t1(this,J8,X.content[G.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,n8,"f")!==void 0){let G=$.data.content[i(this,n8,"f")];if(G)switch(G.type){case"image_file":this._emit("imageFileDone",G.image_file,i(this,RW,"f"));break;case"text":this._emit("textDone",G.text,i(this,RW,"f"));break}}if(i(this,RW,"f"))this._emit("messageDone",$.data);t1(this,RW,void 0,"f")}},LH=function W($){let X=i(this,D1,"m",RH).call(this,$);switch(t1(this,b$,X,"f"),$.event){case"thread.run.step.created":this._emit("runStepCreated",$.data);break;case"thread.run.step.delta":let Y=$.data.delta;if(Y.step_details&&Y.step_details.type=="tool_calls"&&Y.step_details.tool_calls&&X.step_details.type=="tool_calls")for(let J of Y.step_details.tool_calls)if(J.index==i(this,tX,"f"))this._emit("toolCallDelta",J,X.step_details.tool_calls[J.index]);else{if(i(this,a1,"f"))this._emit("toolCallDone",i(this,a1,"f"));if(t1(this,tX,J.index,"f"),t1(this,a1,X.step_details.tool_calls[J.index],"f"),i(this,a1,"f"))this._emit("toolCallCreated",i(this,a1,"f"))}this._emit("runStepDelta",$.data.delta,X);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(t1(this,b$,void 0,"f"),$.data.step_details.type=="tool_calls"){if(i(this,a1,"f"))this._emit("toolCallDone",i(this,a1,"f")),t1(this,a1,void 0,"f")}this._emit("runStepDone",$.data,X);break;case"thread.run.step.in_progress":break}},BH=function W($){i(this,A5,"f").push($),this._emit("event",$)},RH=function W($){switch($.event){case"thread.run.step.created":return i(this,hW,"f")[$.data.id]=$.data,$.data;case"thread.run.step.delta":let X=i(this,hW,"f")[$.data.id];if(!X)throw Error("Received a RunStepDelta before creation of a snapshot");let Y=$.data;if(Y.delta){let G=s1.accumulateDelta(X,Y.delta);i(this,hW,"f")[$.data.id]=G}return i(this,hW,"f")[$.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":i(this,hW,"f")[$.data.id]=$.data;break}if(i(this,hW,"f")[$.data.id])return i(this,hW,"f")[$.data.id];throw new Error("No snapshot available")},NH=function W($,X){let Y=[];switch($.event){case"thread.message.created":return[$.data,Y];case"thread.message.delta":if(!X)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let G=$.data;if(G.delta.content)for(let J of G.delta.content)if(J.index in X.content){let H=X.content[J.index];X.content[J.index]=i(this,D1,"m",ZH).call(this,J,H)}else X.content[J.index]=J,Y.push(J);return[X,Y];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(X)return[X,Y];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ZH=function W($,X){return s1.accumulateDelta(X,$)},SH=function W($){switch(t1(this,rX,$.data,"f"),$.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(t1(this,H8,$.data,"f"),i(this,a1,"f"))this._emit("toolCallDone",i(this,a1,"f")),t1(this,a1,void 0,"f");break;case"thread.run.cancelling":break}};function VM(W){}class r8 extends C{create(W,$){return this._client.post("/assistants",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/assistants/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/assistants",v$,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class v$ extends E0{}r8.AssistantsPage=v$;function E5(W){return typeof W.parse==="function"}var C2=(W)=>{return W?.role==="assistant"},L5=(W)=>{return W?.role==="function"},B5=(W)=>{return W?.role==="tool"};function y$(W){return W?.$brand==="auto-parseable-response-format"}function Q8(W){return W?.$brand==="auto-parseable-tool"}function qH(W,$){if(!$||!R5($))return{...W,choices:W.choices.map((X)=>({...X,message:{...X.message,parsed:null,...X.message.tool_calls?{tool_calls:X.message.tool_calls}:void 0}}))};return h$(W,$)}function h$(W,$){let X=W.choices.map((Y)=>{if(Y.finish_reason==="length")throw new E$;if(Y.finish_reason==="content_filter")throw new L$;return{...Y,message:{...Y.message,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls?.map((G)=>KM($,G))??void 0}:void 0,parsed:Y.message.content&&!Y.message.refusal?OM($,Y.message.content):null}}});return{...W,choices:X}}function OM(W,$){if(W.response_format?.type!=="json_schema")return null;if(W.response_format?.type==="json_schema"){if("$parseRaw"in W.response_format)return W.response_format.$parseRaw($);return JSON.parse($)}return null}function KM(W,$){let X=W.tools?.find((Y)=>Y.function?.name===$.function.name);return{...$,function:{...$.function,parsed_arguments:Q8(X)?X.$parseRaw($.function.arguments):X?.function.strict?JSON.parse($.function.arguments):null}}}function CH(W,$){if(!W)return!1;let X=W.tools?.find((Y)=>Y.function?.name===$.function.name);return Q8(X)||X?.function.strict||!1}function R5(W){if(y$(W.response_format))return!0;return W.tools?.some(($)=>Q8($)||$.type==="function"&&$.function.strict===!0)??!1}function kH(W){for(let $ of W??[]){if($.type!=="function")throw new o(`Currently only \`function\` tool types support auto-parsing; Received \`${$.type}\``);if($.function.strict!==!0)throw new o(`The \`${$.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var h1=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},L1,N5,aX,Z5,S5,q5,IH,C5,jH=10;class g$ extends G8{constructor(){super(...arguments);L1.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(W){this._chatCompletions.push(W),this._emit("chatCompletion",W);let $=W.choices[0]?.message;if($)this._addMessage($);return W}_addMessage(W,$=!0){if(!("content"in W))W.content=null;if(this.messages.push(W),$){if(this._emit("message",W),(L5(W)||B5(W))&&W.content)this._emit("functionCallResult",W.content);else if(C2(W)&&W.function_call)this._emit("functionCall",W.function_call);else if(C2(W)&&W.tool_calls){for(let X of W.tool_calls)if(X.type==="function")this._emit("functionCall",X.function)}}}async finalChatCompletion(){await this.done();let W=this._chatCompletions[this._chatCompletions.length-1];if(!W)throw new o("stream ended without producing a ChatCompletion");return W}async finalContent(){return await this.done(),h1(this,L1,"m",N5).call(this)}async finalMessage(){return await this.done(),h1(this,L1,"m",aX).call(this)}async finalFunctionCall(){return await this.done(),h1(this,L1,"m",Z5).call(this)}async finalFunctionCallResult(){return await this.done(),h1(this,L1,"m",S5).call(this)}async totalUsage(){return await this.done(),h1(this,L1,"m",q5).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let W=this._chatCompletions[this._chatCompletions.length-1];if(W)this._emit("finalChatCompletion",W);let $=h1(this,L1,"m",aX).call(this);if($)this._emit("finalMessage",$);let X=h1(this,L1,"m",N5).call(this);if(X)this._emit("finalContent",X);let Y=h1(this,L1,"m",Z5).call(this);if(Y)this._emit("finalFunctionCall",Y);let G=h1(this,L1,"m",S5).call(this);if(G!=null)this._emit("finalFunctionCallResult",G);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",h1(this,L1,"m",q5).call(this))}async _createChatCompletion(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}h1(this,L1,"m",IH).call(this,$);let G=await W.chat.completions.create({...$,stream:!1},{...X,signal:this.controller.signal});return this._connected(),this._addChatCompletion(h$(G,$))}async _runChatCompletion(W,$,X){for(let Y of $.messages)this._addMessage(Y,!1);return await this._createChatCompletion(W,$,X)}async _runFunctions(W,$,X){let{function_call:G="auto",stream:J,...H}=$,Q=typeof G!=="string"&&G?.name,{maxChatCompletions:z=jH}=X||{},T={};for(let _ of $.functions)T[_.name||_.function.name]=_;let F=$.functions.map((_)=>({name:_.name||_.function.name,parameters:_.parameters,description:_.description}));for(let _ of $.messages)this._addMessage(_,!1);for(let _=0;_<z;++_){let O=(await this._createChatCompletion(W,{...H,function_call:G,functions:F,messages:[...this.messages]},X)).choices[0]?.message;if(!O)throw new o("missing message in ChatCompletion response");if(!O.function_call)return;let{name:M,arguments:A}=O.function_call,I=T[M];if(!I){let P=`Invalid function_call: ${JSON.stringify(M)}. Available options are: ${F.map((h)=>JSON.stringify(h.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:M,content:P});continue}else if(Q&&Q!==M){let P=`Invalid function_call: ${JSON.stringify(M)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"function",name:M,content:P});continue}let j;try{j=E5(I)?await I.parse(A):A}catch(P){this._addMessage({role:"function",name:M,content:P instanceof Error?P.message:String(P)});continue}let R=await I.function(j,this),Z=h1(this,L1,"m",C5).call(this,R);if(this._addMessage({role:"function",name:M,content:Z}),Q)return}}async _runTools(W,$,X){let{tool_choice:G="auto",stream:J,...H}=$,Q=typeof G!=="string"&&G?.function?.name,{maxChatCompletions:z=jH}=X||{},T=$.tools.map((w)=>{if(Q8(w)){if(!w.$callback)throw new o("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}),F={};for(let w of T)if(w.type==="function")F[w.function.name||w.function.function.name]=w.function;let _="tools"in $?T.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 $.messages)this._addMessage(w,!1);for(let w=0;w<z;++w){let M=(await this._createChatCompletion(W,{...H,tool_choice:G,tools:_,messages:[...this.messages]},X)).choices[0]?.message;if(!M)throw new o("missing message in ChatCompletion response");if(!M.tool_calls?.length)return;for(let A of M.tool_calls){if(A.type!=="function")continue;let I=A.id,{name:j,arguments:R}=A.function,Z=F[j];if(!Z){let m=`Invalid tool_call: ${JSON.stringify(j)}. Available options are: ${Object.keys(F).map((w0)=>JSON.stringify(w0)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:m});continue}else if(Q&&Q!==j){let m=`Invalid tool_call: ${JSON.stringify(j)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:m});continue}let P;try{P=E5(Z)?await Z.parse(R):R}catch(m){let w0=m instanceof Error?m.message:String(m);this._addMessage({role:"tool",tool_call_id:I,content:w0});continue}let h=await Z.function(P,this),x=h1(this,L1,"m",C5).call(this,h);if(this._addMessage({role:"tool",tool_call_id:I,content:x}),Q)return}}return}}L1=new WeakSet,N5=function W(){return h1(this,L1,"m",aX).call(this).content??null},aX=function W(){let $=this.messages.length;while($-- >0){let X=this.messages[$];if(C2(X)){let{function_call:Y,...G}=X,J={...G,content:X.content??null,refusal:X.refusal??null};if(Y)J.function_call=Y;return J}}throw new o("stream ended without producing a ChatCompletionMessage with role=assistant")},Z5=function W(){for(let $=this.messages.length-1;$>=0;$--){let X=this.messages[$];if(C2(X)&&X?.function_call)return X.function_call;if(C2(X)&&X?.tool_calls?.length)return X.tool_calls.at(-1)?.function}return},S5=function W(){for(let $=this.messages.length-1;$>=0;$--){let X=this.messages[$];if(L5(X)&&X.content!=null)return X.content;if(B5(X)&&X.content!=null&&typeof X.content==="string"&&this.messages.some((Y)=>Y.role==="assistant"&&Y.tool_calls?.some((G)=>G.type==="function"&&G.id===X.tool_call_id)))return X.content}return},q5=function W(){let $={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:X}of this._chatCompletions)if(X)$.completion_tokens+=X.completion_tokens,$.prompt_tokens+=X.prompt_tokens,$.total_tokens+=X.total_tokens;return $},IH=function W($){if($.n!=null&&$.n>1)throw new o("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},C5=function W($){return typeof $==="string"?$:$===void 0?"undefined":JSON.stringify($)};class t8 extends g${static runFunctions(W,$,X){let Y=new t8,G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return Y._run(()=>Y._runFunctions(W,$,G)),Y}static runTools(W,$,X){let Y=new t8,G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools(W,$,G)),Y}_addMessage(W,$=!0){if(super._addMessage(W,$),C2(W)&&W.content)this._emit("content",W.content)}}var _1={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 PH extends Error{}class fH extends Error{}function AM(W,$=_1.ALL){if(typeof W!=="string")throw new TypeError(`expecting str, got ${typeof W}`);if(!W.trim())throw new Error(`${W} is empty`);return EM(W.trim(),$)}var EM=(W,$)=>{let X=W.length,Y=0,G=(w)=>{throw new PH(`${w} at position ${Y}`)},J=(w)=>{throw new fH(`${w} at position ${Y}`)},H=()=>{if(_(),Y>=X)G("Unexpected end of input");if(W[Y]==='"')return Q();if(W[Y]==="{")return z();if(W[Y]==="[")return T();if(W.substring(Y,Y+4)==="null"||_1.NULL&$&&X-Y<4&&"null".startsWith(W.substring(Y)))return Y+=4,null;if(W.substring(Y,Y+4)==="true"||_1.BOOL&$&&X-Y<4&&"true".startsWith(W.substring(Y)))return Y+=4,!0;if(W.substring(Y,Y+5)==="false"||_1.BOOL&$&&X-Y<5&&"false".startsWith(W.substring(Y)))return Y+=5,!1;if(W.substring(Y,Y+8)==="Infinity"||_1.INFINITY&$&&X-Y<8&&"Infinity".startsWith(W.substring(Y)))return Y+=8,1/0;if(W.substring(Y,Y+9)==="-Infinity"||_1.MINUS_INFINITY&$&&1<X-Y&&X-Y<9&&"-Infinity".startsWith(W.substring(Y)))return Y+=9,-1/0;if(W.substring(Y,Y+3)==="NaN"||_1.NAN&$&&X-Y<3&&"NaN".startsWith(W.substring(Y)))return Y+=3,NaN;return F()},Q=()=>{let w=Y,O=!1;Y++;while(Y<X&&(W[Y]!=='"'||O&&W[Y-1]==="\\"))O=W[Y]==="\\"?!O:!1,Y++;if(W.charAt(Y)=='"')try{return JSON.parse(W.substring(w,++Y-Number(O)))}catch(M){J(String(M))}else if(_1.STR&$)try{return JSON.parse(W.substring(w,Y-Number(O))+'"')}catch(M){return JSON.parse(W.substring(w,W.lastIndexOf("\\"))+'"')}G("Unterminated string literal")},z=()=>{Y++,_();let w={};try{while(W[Y]!=="}"){if(_(),Y>=X&&_1.OBJ&$)return w;let O=Q();_(),Y++;try{let M=H();Object.defineProperty(w,O,{value:M,writable:!0,enumerable:!0,configurable:!0})}catch(M){if(_1.OBJ&$)return w;else throw M}if(_(),W[Y]===",")Y++}}catch(O){if(_1.OBJ&$)return w;else G("Expected '}' at end of object")}return Y++,w},T=()=>{Y++;let w=[];try{while(W[Y]!=="]")if(w.push(H()),_(),W[Y]===",")Y++}catch(O){if(_1.ARR&$)return w;G("Expected ']' at end of array")}return Y++,w},F=()=>{if(Y===0){if(W==="-"&&_1.NUM&$)G("Not sure what '-' is");try{return JSON.parse(W)}catch(O){if(_1.NUM&$)try{if(W[W.length-1]===".")return JSON.parse(W.substring(0,W.lastIndexOf(".")));return JSON.parse(W.substring(0,W.lastIndexOf("e")))}catch(M){}J(String(O))}}let w=Y;if(W[Y]==="-")Y++;while(W[Y]&&!",]}".includes(W[Y]))Y++;if(Y==X&&!(_1.NUM&$))G("Unterminated number literal");try{return JSON.parse(W.substring(w,Y))}catch(O){if(W.substring(w,Y)==="-"&&_1.NUM&$)G("Not sure what '-' is");try{return JSON.parse(W.substring(w,W.lastIndexOf("e")))}catch(M){J(String(M))}}},_=()=>{while(Y<X&&`
42
+ \r `.includes(W[Y]))Y++};return H()},k5=(W)=>AM(W,_1.ALL^_1.NUM);var a8=function(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X},Z0=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},J1,W2,s8,k2,j5,sX,I5,P5,f5,eX,x5,xH;class z8 extends g${constructor(W){super();J1.add(this),W2.set(this,void 0),s8.set(this,void 0),k2.set(this,void 0),a8(this,W2,W,"f"),a8(this,s8,[],"f")}get currentChatCompletionSnapshot(){return Z0(this,k2,"f")}static fromReadableStream(W){let $=new z8(null);return $._run(()=>$._fromReadableStream(W)),$}static createChatCompletion(W,$,X){let Y=new z8($);return Y._run(()=>Y._runChatCompletion(W,{...$,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createChatCompletion(W,$,X){super._createChatCompletion;let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}Z0(this,J1,"m",j5).call(this);let G=await W.chat.completions.create({...$,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let J of G)Z0(this,J1,"m",I5).call(this,J);if(G.controller.signal?.aborted)throw new G1;return this._addChatCompletion(Z0(this,J1,"m",eX).call(this))}async _fromReadableStream(W,$){let X=$?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}Z0(this,J1,"m",j5).call(this),this._connected();let Y=r1.fromReadableStream(W,this.controller),G;for await(let J of Y){if(G&&G!==J.id)this._addChatCompletion(Z0(this,J1,"m",eX).call(this));Z0(this,J1,"m",I5).call(this,J),G=J.id}if(Y.controller.signal?.aborted)throw new G1;return this._addChatCompletion(Z0(this,J1,"m",eX).call(this))}[(W2=new WeakMap,s8=new WeakMap,k2=new WeakMap,J1=new WeakSet,j5=function W(){if(this.ended)return;a8(this,k2,void 0,"f")},sX=function W($){let X=Z0(this,s8,"f")[$.index];if(X)return X;return X={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Z0(this,s8,"f")[$.index]=X,X},I5=function W($){if(this.ended)return;let X=Z0(this,J1,"m",xH).call(this,$);this._emit("chunk",$,X);for(let Y of $.choices){let G=X.choices[Y.index];if(Y.delta.content!=null&&G.message?.role==="assistant"&&G.message?.content)this._emit("content",Y.delta.content,G.message.content),this._emit("content.delta",{delta:Y.delta.content,snapshot:G.message.content,parsed:G.message.parsed});if(Y.delta.refusal!=null&&G.message?.role==="assistant"&&G.message?.refusal)this._emit("refusal.delta",{delta:Y.delta.refusal,snapshot:G.message.refusal});if(Y.logprobs?.content!=null&&G.message?.role==="assistant")this._emit("logprobs.content.delta",{content:Y.logprobs?.content,snapshot:G.logprobs?.content??[]});if(Y.logprobs?.refusal!=null&&G.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:Y.logprobs?.refusal,snapshot:G.logprobs?.refusal??[]});let J=Z0(this,J1,"m",sX).call(this,G);if(G.finish_reason){if(Z0(this,J1,"m",f5).call(this,G),J.current_tool_call_index!=null)Z0(this,J1,"m",P5).call(this,G,J.current_tool_call_index)}for(let H of Y.delta.tool_calls??[]){if(J.current_tool_call_index!==H.index){if(Z0(this,J1,"m",f5).call(this,G),J.current_tool_call_index!=null)Z0(this,J1,"m",P5).call(this,G,J.current_tool_call_index)}J.current_tool_call_index=H.index}for(let H of Y.delta.tool_calls??[]){let Q=G.message.tool_calls?.[H.index];if(!Q?.type)continue;if(Q?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:Q.function?.name,index:H.index,arguments:Q.function.arguments,parsed_arguments:Q.function.parsed_arguments,arguments_delta:H.function?.arguments??""});else vH(Q?.type)}}},P5=function W($,X){if(Z0(this,J1,"m",sX).call(this,$).done_tool_calls.has(X))return;let G=$.message.tool_calls?.[X];if(!G)throw new Error("no tool call snapshot");if(!G.type)throw new Error("tool call snapshot missing `type`");if(G.type==="function"){let J=Z0(this,W2,"f")?.tools?.find((H)=>H.type==="function"&&H.function.name===G.function.name);this._emit("tool_calls.function.arguments.done",{name:G.function.name,index:X,arguments:G.function.arguments,parsed_arguments:Q8(J)?J.$parseRaw(G.function.arguments):J?.function.strict?JSON.parse(G.function.arguments):null})}else vH(G.type)},f5=function W($){let X=Z0(this,J1,"m",sX).call(this,$);if($.message.content&&!X.content_done){X.content_done=!0;let Y=Z0(this,J1,"m",x5).call(this);this._emit("content.done",{content:$.message.content,parsed:Y?Y.$parseRaw($.message.content):null})}if($.message.refusal&&!X.refusal_done)X.refusal_done=!0,this._emit("refusal.done",{refusal:$.message.refusal});if($.logprobs?.content&&!X.logprobs_content_done)X.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:$.logprobs.content});if($.logprobs?.refusal&&!X.logprobs_refusal_done)X.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:$.logprobs.refusal})},eX=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=Z0(this,k2,"f");if(!$)throw new o("request ended without sending any chunks");return a8(this,k2,void 0,"f"),a8(this,s8,[],"f"),LM($,Z0(this,W2,"f"))},x5=function W(){let $=Z0(this,W2,"f")?.response_format;if(y$($))return $;return null},xH=function W($){var X,Y,G,J;let H=Z0(this,k2,"f"),{choices:Q,...z}=$;if(!H)H=a8(this,k2,{...z,choices:[]},"f");else Object.assign(H,z);for(let{delta:T,finish_reason:F,index:_,logprobs:w=null,...O}of $.choices){let M=H.choices[_];if(!M)M=H.choices[_]={finish_reason:F,index:_,message:{},logprobs:w,...O};if(w)if(!M.logprobs)M.logprobs=Object.assign({},w);else{let{content:h,refusal:x,...m}=w;if(bH(m),Object.assign(M.logprobs,m),h)(X=M.logprobs).content??(X.content=[]),M.logprobs.content.push(...h);if(x)(Y=M.logprobs).refusal??(Y.refusal=[]),M.logprobs.refusal.push(...x)}if(F){if(M.finish_reason=F,Z0(this,W2,"f")&&R5(Z0(this,W2,"f"))){if(F==="length")throw new E$;if(F==="content_filter")throw new L$}}if(Object.assign(M,O),!T)continue;let{content:A,refusal:I,function_call:j,role:R,tool_calls:Z,...P}=T;if(bH(P),Object.assign(M.message,P),I)M.message.refusal=(M.message.refusal||"")+I;if(R)M.message.role=R;if(j)if(!M.message.function_call)M.message.function_call=j;else{if(j.name)M.message.function_call.name=j.name;if(j.arguments)(G=M.message.function_call).arguments??(G.arguments=""),M.message.function_call.arguments+=j.arguments}if(A){if(M.message.content=(M.message.content||"")+A,!M.message.refusal&&Z0(this,J1,"m",x5).call(this))M.message.parsed=k5(M.message.content)}if(Z){if(!M.message.tool_calls)M.message.tool_calls=[];for(let{index:h,id:x,type:m,function:w0,...p0}of Z){let B=(J=M.message.tool_calls)[h]??(J[h]={});if(Object.assign(B,p0),x)B.id=x;if(m)B.type=m;if(w0)B.function??(B.function={name:w0.name??"",arguments:""});if(w0?.name)B.function.name=w0.name;if(w0?.arguments){if(B.function.arguments+=w0.arguments,CH(Z0(this,W2,"f"),B))B.function.parsed_arguments=k5(B.function.arguments)}}}}return H},Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("chunk",(Y)=>{let G=$.shift();if(G)G.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of $)G.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let G of $)G.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((G,J)=>$.push({resolve:G,reject:J})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new r1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function LM(W,$){let{id:X,choices:Y,created:G,model:J,system_fingerprint:H,...Q}=W,z={...Q,id:X,choices:Y.map(({message:T,finish_reason:F,index:_,logprobs:w,...O})=>{if(!F)throw new o(`missing finish_reason for choice ${_}`);let{content:M=null,function_call:A,tool_calls:I,...j}=T,R=T.role;if(!R)throw new o(`missing role for choice ${_}`);if(A){let{arguments:Z,name:P}=A;if(Z==null)throw new o(`missing function_call.arguments for choice ${_}`);if(!P)throw new o(`missing function_call.name for choice ${_}`);return{...O,message:{content:M,function_call:{arguments:Z,name:P},role:R,refusal:T.refusal??null},finish_reason:F,index:_,logprobs:w}}if(I)return{...O,index:_,finish_reason:F,logprobs:w,message:{...j,role:R,content:M,refusal:T.refusal??null,tool_calls:I.map((Z,P)=>{let{function:h,type:x,id:m,...w0}=Z,{arguments:p0,name:B,...V0}=h||{};if(m==null)throw new o(`missing choices[${_}].tool_calls[${P}].id
43
+ ${WY(W)}`);if(x==null)throw new o(`missing choices[${_}].tool_calls[${P}].type
44
+ ${WY(W)}`);if(B==null)throw new o(`missing choices[${_}].tool_calls[${P}].function.name
45
+ ${WY(W)}`);if(p0==null)throw new o(`missing choices[${_}].tool_calls[${P}].function.arguments
46
+ ${WY(W)}`);return{...w0,id:m,type:x,function:{...V0,name:B,arguments:p0}}})}};return{...O,message:{...j,content:M,role:R,refusal:T.refusal??null},finish_reason:F,index:_,logprobs:w}}),created:G,model:J,object:"chat.completion",...H?{system_fingerprint:H}:{}};return qH(z,$)}function WY(W){return JSON.stringify(W)}function bH(W){return}function vH(W){}class T8 extends z8{static fromReadableStream(W){let $=new T8(null);return $._run(()=>$._fromReadableStream(W)),$}static runFunctions(W,$,X){let Y=new T8(null),G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return Y._run(()=>Y._runFunctions(W,$,G)),Y}static runTools(W,$,X){let Y=new T8($),G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools(W,$,G)),Y}}class $Y extends C{parse(W,$){return kH(W.tools),this._client.chat.completions.create(W,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((X)=>h$(X,W))}runFunctions(W,$){if(W.stream)return T8.runFunctions(this._client,W,$);return t8.runFunctions(this._client,W,$)}runTools(W,$){if(W.stream)return T8.runTools(this._client,W,$);return t8.runTools(this._client,W,$)}stream(W,$){return z8.createChatCompletion(this._client,W,$)}}class m$ extends C{constructor(){super(...arguments);this.completions=new $Y(this._client)}}(function(W){W.Completions=$Y})(m$||(m$={}));class p$ extends C{create(W,$){return this._client.post("/realtime/sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class u$ extends C{create(W,$){return this._client.post("/realtime/transcription_sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class F8 extends C{constructor(){super(...arguments);this.sessions=new p$(this._client),this.transcriptionSessions=new u$(this._client)}}F8.Sessions=p$;F8.TranscriptionSessions=u$;class e8 extends C{create(W,$,X){return this._client.post(`/threads/${W}/messages`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/threads/${W}/messages/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/threads/${W}/messages/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/messages`,c$,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$,X){return this._client.delete(`/threads/${W}/messages/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class c$ extends E0{}e8.MessagesPage=c$;class W4 extends C{retrieve(W,$,X,Y={},G){if(z0(Y))return this.retrieve(W,$,X,{},Y);return this._client.get(`/threads/${W}/runs/${$}/steps/${X}`,{query:Y,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}list(W,$,X={},Y){if(z0(X))return this.list(W,$,{},X);return this._client.getAPIList(`/threads/${W}/runs/${$}/steps`,d$,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}class d$ extends E0{}W4.RunStepsPage=d$;class j2 extends C{constructor(){super(...arguments);this.steps=new W4(this._client)}create(W,$,X){let{include:Y,...G}=$;return this._client.post(`/threads/${W}/runs`,{query:{include:Y},body:G,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers},stream:$.stream??!1})}retrieve(W,$,X){return this._client.get(`/threads/${W}/runs/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/threads/${W}/runs/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/runs`,l$,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}cancel(W,$,X){return this._client.post(`/threads/${W}/runs/${$}/cancel`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$,X);return await this.poll(W,Y.id,X)}createAndStream(W,$,X){return s1.createAssistantStream(W,this._client.beta.threads.runs,$,X)}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let{data:G,response:J}=await this.retrieve(W,$,{...X,headers:{...X?.headers,...Y}}).withResponse();switch(G.status){case"queued":case"in_progress":case"cancelling":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=J.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await tW(H);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return G}}}stream(W,$,X){return s1.createAssistantStream(W,this._client.beta.threads.runs,$,X)}submitToolOutputs(W,$,X,Y){return this._client.post(`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers},stream:X.stream??!1})}async submitToolOutputsAndPoll(W,$,X,Y){let G=await this.submitToolOutputs(W,$,X,Y);return await this.poll(W,G.id,Y)}submitToolOutputsStream(W,$,X,Y){return s1.createToolAssistantStream(W,$,this._client.beta.threads.runs,X,Y)}}class l$ extends E0{}j2.RunsPage=l$;j2.Steps=W4;j2.RunStepsPage=d$;class $2 extends C{constructor(){super(...arguments);this.runs=new j2(this._client),this.messages=new e8(this._client)}create(W={},$){if(z0(W))return this.create({},W);return this._client.post("/threads",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/threads/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/threads/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$){return this._client.delete(`/threads/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}createAndRun(W,$){return this._client.post("/threads/runs",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:W.stream??!1})}async createAndRunPoll(W,$){let X=await this.createAndRun(W,$);return await this.runs.poll(X.thread_id,X.id,$)}createAndRunStream(W,$){return s1.createThreadAssistantStream(W,this._client.beta.threads,$)}}$2.Runs=j2;$2.RunsPage=l$;$2.Messages=e8;$2.MessagesPage=c$;class gW extends C{constructor(){super(...arguments);this.realtime=new F8(this._client),this.chat=new m$(this._client),this.assistants=new r8(this._client),this.threads=new $2(this._client)}}gW.Realtime=F8;gW.Assistants=r8;gW.AssistantsPage=v$;gW.Threads=$2;class $4 extends C{create(W,$){return this._client.post("/completions",{body:W,...$,stream:W.stream??!1})}}class X4 extends C{create(W,$){let X=!!W.encoding_format,Y=X?W.encoding_format:"base64";if(X)rW("Request","User defined encoding_format:",W.encoding_format);let G=this._client.post("/embeddings",{body:{...W,encoding_format:Y},...$});if(X)return G;return rW("response","Decoding base64 embeddings to float32 array"),G._thenUnwrap((J)=>{if(J&&J.data)J.data.forEach((H)=>{let Q=H.embedding;H.embedding=KH(Q)});return J})}}class Y4 extends C{retrieve(W,$,X,Y){return this._client.get(`/evals/${W}/runs/${$}/output_items/${X}`,Y)}list(W,$,X={},Y){if(z0(X))return this.list(W,$,{},X);return this._client.getAPIList(`/evals/${W}/runs/${$}/output_items`,o$,{query:X,...Y})}}class o$ extends E0{}Y4.OutputItemListResponsesPage=o$;class I2 extends C{constructor(){super(...arguments);this.outputItems=new Y4(this._client)}create(W,$,X){return this._client.post(`/evals/${W}/runs`,{body:$,...X})}retrieve(W,$,X){return this._client.get(`/evals/${W}/runs/${$}`,X)}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/evals/${W}/runs`,i$,{query:$,...X})}del(W,$,X){return this._client.delete(`/evals/${W}/runs/${$}`,X)}cancel(W,$,X){return this._client.post(`/evals/${W}/runs/${$}`,X)}}class i$ extends E0{}I2.RunListResponsesPage=i$;I2.OutputItems=Y4;I2.OutputItemListResponsesPage=o$;class X2 extends C{constructor(){super(...arguments);this.runs=new I2(this._client)}create(W,$){return this._client.post("/evals",{body:W,...$})}retrieve(W,$){return this._client.get(`/evals/${W}`,$)}update(W,$,X){return this._client.post(`/evals/${W}`,{body:$,...X})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/evals",G4,{query:W,...$})}del(W,$){return this._client.delete(`/evals/${W}`,$)}}class G4 extends E0{}X2.EvalListResponsesPage=G4;X2.Runs=I2;X2.RunListResponsesPage=i$;class _8 extends C{create(W,$){return this._client.post("/files",JW({body:W,...$}))}retrieve(W,$){return this._client.get(`/files/${W}`,$)}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/files",J4,{query:W,...$})}del(W,$){return this._client.delete(`/files/${W}`,$)}content(W,$){return this._client.get(`/files/${W}/content`,{...$,headers:{Accept:"application/binary",...$?.headers},__binaryResponse:!0})}retrieveContent(W,$){return this._client.get(`/files/${W}/content`,$)}async waitForProcessing(W,{pollInterval:$=5000,maxWait:X=1800000}={}){let Y=new Set(["processed","error","deleted"]),G=Date.now(),J=await this.retrieve(W);while(!J.status||!Y.has(J.status))if(await tW($),J=await this.retrieve(W),Date.now()-G>X)throw new e2({message:`Giving up on waiting for file ${W} to finish processing after ${X} milliseconds.`});return J}}class J4 extends E0{}_8.FileObjectsPage=J4;class n$ extends C{}class r$ extends C{run(W,$){return this._client.post("/fine_tuning/alpha/graders/run",{body:W,...$})}validate(W,$){return this._client.post("/fine_tuning/alpha/graders/validate",{body:W,...$})}}class H4 extends C{constructor(){super(...arguments);this.graders=new r$(this._client)}}H4.Graders=r$;class Q4 extends C{create(W,$,X){return this._client.getAPIList(`/fine_tuning/checkpoints/${W}/permissions`,t$,{body:$,method:"post",...X})}retrieve(W,$={},X){if(z0($))return this.retrieve(W,{},$);return this._client.get(`/fine_tuning/checkpoints/${W}/permissions`,{query:$,...X})}del(W,$,X){return this._client.delete(`/fine_tuning/checkpoints/${W}/permissions/${$}`,X)}}class t$ extends aW{}Q4.PermissionCreateResponsesPage=t$;class w8 extends C{constructor(){super(...arguments);this.permissions=new Q4(this._client)}}w8.Permissions=Q4;w8.PermissionCreateResponsesPage=t$;class z4 extends C{list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/checkpoints`,a$,{query:$,...X})}}class a$ extends E0{}z4.FineTuningJobCheckpointsPage=a$;class Y2 extends C{constructor(){super(...arguments);this.checkpoints=new z4(this._client)}create(W,$){return this._client.post("/fine_tuning/jobs",{body:W,...$})}retrieve(W,$){return this._client.get(`/fine_tuning/jobs/${W}`,$)}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/fine_tuning/jobs",s$,{query:W,...$})}cancel(W,$){return this._client.post(`/fine_tuning/jobs/${W}/cancel`,$)}listEvents(W,$={},X){if(z0($))return this.listEvents(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/events`,e$,{query:$,...X})}pause(W,$){return this._client.post(`/fine_tuning/jobs/${W}/pause`,$)}resume(W,$){return this._client.post(`/fine_tuning/jobs/${W}/resume`,$)}}class s$ extends E0{}class e$ extends E0{}Y2.FineTuningJobsPage=s$;Y2.FineTuningJobEventsPage=e$;Y2.Checkpoints=z4;Y2.FineTuningJobCheckpointsPage=a$;class HW extends C{constructor(){super(...arguments);this.methods=new n$(this._client),this.jobs=new Y2(this._client),this.checkpoints=new w8(this._client),this.alpha=new H4(this._client)}}HW.Methods=n$;HW.Jobs=Y2;HW.FineTuningJobsPage=s$;HW.FineTuningJobEventsPage=e$;HW.Checkpoints=w8;HW.Alpha=H4;class W6 extends C{}class U8 extends C{constructor(){super(...arguments);this.graderModels=new W6(this._client)}}U8.GraderModels=W6;class T4 extends C{createVariation(W,$){return this._client.post("/images/variations",JW({body:W,...$}))}edit(W,$){return this._client.post("/images/edits",JW({body:W,...$}))}generate(W,$){return this._client.post("/images/generations",{body:W,...$})}}class D8 extends C{retrieve(W,$){return this._client.get(`/models/${W}`,$)}list(W){return this._client.getAPIList("/models",F4,W)}del(W,$){return this._client.delete(`/models/${W}`,$)}}class F4 extends aW{}D8.ModelsPage=F4;class _4 extends C{create(W,$){return this._client.post("/moderations",{body:W,...$})}}function yH(W,$){if(!$||!uM($))return{...W,output_parsed:null,output:W.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:null};if(X.type==="message")return{...X,content:X.content.map((Y)=>({...Y,parsed:null}))};else return X})};return b5(W,$)}function b5(W,$){let X=W.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:lM($,G)};if(G.type==="message"){let J=G.content.map((H)=>{if(H.type==="output_text")return{...H,parsed:pM($,H.text)};return H});return{...G,content:J}}return G}),Y=Object.assign({},W,{output:X});if(!Object.getOwnPropertyDescriptor(W,"output_text"))v5(Y);return Object.defineProperty(Y,"output_parsed",{enumerable:!0,get(){for(let G of Y.output){if(G.type!=="message")continue;for(let J of G.content)if(J.type==="output_text"&&J.parsed!==null)return J.parsed}return null}}),Y}function pM(W,$){if(W.text?.format?.type!=="json_schema")return null;if("$parseRaw"in W.text?.format)return(W.text?.format).$parseRaw($);return JSON.parse($)}function uM(W){if(y$(W.text?.format))return!0;return!1}function cM(W){return W?.$brand==="auto-parseable-tool"}function dM(W,$){return W.find((X)=>X.type==="function"&&X.name===$)}function lM(W,$){let X=dM(W.tools??[],$.name);return{...$,...$,parsed_arguments:cM(X)?X.$parseRaw($.arguments):X?.strict?JSON.parse($.arguments):null}}function v5(W){let $=[];for(let X of W.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text")$.push(Y.text)}W.output_text=$.join("")}class $6 extends C{list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/responses/${W}/input_items`,y5,{query:$,...X})}}var w4=function(W,$,X,Y,G){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!G)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!G:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call(W,X):G?G.value=X:$.set(W,X),X},P2=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},U4,XY,f2,YY,hH,gH,mH,pH;class GY extends G8{constructor(W){super();U4.add(this),XY.set(this,void 0),f2.set(this,void 0),YY.set(this,void 0),w4(this,XY,W,"f")}static createResponse(W,$,X){let Y=new GY($);return Y._run(()=>Y._createResponse(W,$,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createResponse(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}P2(this,U4,"m",hH).call(this);let G=await W.responses.create({...$,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let J of G)P2(this,U4,"m",gH).call(this,J);if(G.controller.signal?.aborted)throw new G1;return P2(this,U4,"m",mH).call(this)}[(XY=new WeakMap,f2=new WeakMap,YY=new WeakMap,U4=new WeakSet,hH=function W(){if(this.ended)return;w4(this,f2,void 0,"f")},gH=function W($){if(this.ended)return;let X=P2(this,U4,"m",pH).call(this,$);switch(this._emit("event",$),$.type){case"response.output_text.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message"){let G=Y.content[$.content_index];if(!G)throw new o(`missing content at index ${$.content_index}`);if(G.type!=="output_text")throw new o(`expected content to be 'output_text', got ${G.type}`);this._emit("response.output_text.delta",{...$,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="function_call")this._emit("response.function_call_arguments.delta",{...$,snapshot:Y.arguments});break}default:this._emit($.type,$);break}},mH=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=P2(this,f2,"f");if(!$)throw new o("request ended without sending any events");w4(this,f2,void 0,"f");let X=iM($,P2(this,XY,"f"));return w4(this,YY,X,"f"),X},pH=function W($){let X=P2(this,f2,"f");if(!X){if($.type!=="response.created")throw new o(`When snapshot hasn't been set yet, expected 'response.created' event, got ${$.type}`);return X=w4(this,f2,$.response,"f"),X}switch($.type){case"response.output_item.added":{X.output.push($.item);break}case"response.content_part.added":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message")Y.content.push($.part);break}case"response.output_text.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message"){let G=Y.content[$.content_index];if(!G)throw new o(`missing content at index ${$.content_index}`);if(G.type!=="output_text")throw new o(`expected content to be 'output_text', got ${G.type}`);G.text+=$.delta}break}case"response.function_call_arguments.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="function_call")Y.arguments+=$.delta;break}case"response.completed":{w4(this,f2,$.response,"f");break}}return X},Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("event",(Y)=>{let G=$.shift();if(G)G.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of $)G.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let G of $)G.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((G,J)=>$.push({resolve:G,reject:J})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let W=P2(this,YY,"f");if(!W)throw new o("stream ended without producing a ChatCompletion");return W}}function iM(W,$){return yH(W,$)}class V8 extends C{constructor(){super(...arguments);this.inputItems=new $6(this._client)}create(W,$){return this._client.post("/responses",{body:W,...$,stream:W.stream??!1})._thenUnwrap((X)=>{if("object"in X&&X.object==="response")v5(X);return X})}retrieve(W,$={},X){if(z0($))return this.retrieve(W,{},$);return this._client.get(`/responses/${W}`,{query:$,...X})}del(W,$){return this._client.delete(`/responses/${W}`,{...$,headers:{Accept:"*/*",...$?.headers}})}parse(W,$){return this._client.responses.create(W,$)._thenUnwrap((X)=>b5(X,W))}stream(W,$){return GY.createResponse(this._client,W,$)}}class y5 extends E0{}V8.InputItems=$6;class X6 extends C{create(W,$,X){return this._client.post(`/uploads/${W}/parts`,JW({body:$,...X}))}}class M8 extends C{constructor(){super(...arguments);this.parts=new X6(this._client)}create(W,$){return this._client.post("/uploads",{body:W,...$})}cancel(W,$){return this._client.post(`/uploads/${W}/cancel`,$)}complete(W,$,X){return this._client.post(`/uploads/${W}/complete`,{body:$,...X})}}M8.Parts=X6;var uH=async(W)=>{let $=await Promise.allSettled(W),X=$.filter((G)=>G.status==="rejected");if(X.length){for(let G of X)console.error(G.reason);throw new Error(`${X.length} promise(s) failed - see the above errors`)}let Y=[];for(let G of $)if(G.status==="fulfilled")Y.push(G.value);return Y};class O8 extends C{create(W,$,X){return this._client.post(`/vector_stores/${W}/files`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/vector_stores/${W}/files/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/vector_stores/${W}/files/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(z0($))return this.list(W,{},$);return this._client.getAPIList(`/vector_stores/${W}/files`,K8,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$,X){return this._client.delete(`/vector_stores/${W}/files/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$,X);return await this.poll(W,Y.id,X)}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let G=await this.retrieve(W,$,{...X,headers:Y}).withResponse(),J=G.data;switch(J.status){case"in_progress":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=G.response.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await tW(H);break;case"failed":case"completed":return J}}}async upload(W,$,X){let Y=await this._client.files.create({file:$,purpose:"assistants"},X);return this.create(W,{file_id:Y.id},X)}async uploadAndPoll(W,$,X){let Y=await this.upload(W,$,X);return await this.poll(W,Y.id,X)}content(W,$,X){return this._client.getAPIList(`/vector_stores/${W}/files/${$}/content`,Y6,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class K8 extends E0{}class Y6 extends aW{}O8.VectorStoreFilesPage=K8;O8.FileContentResponsesPage=Y6;class G6 extends C{create(W,$,X){return this._client.post(`/vector_stores/${W}/file_batches`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/vector_stores/${W}/file_batches/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}cancel(W,$,X){return this._client.post(`/vector_stores/${W}/file_batches/${$}/cancel`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$);return await this.poll(W,Y.id,X)}listFiles(W,$,X={},Y){if(z0(X))return this.listFiles(W,$,{},X);return this._client.getAPIList(`/vector_stores/${W}/file_batches/${$}/files`,K8,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let{data:G,response:J}=await this.retrieve(W,$,{...X,headers:Y}).withResponse();switch(G.status){case"in_progress":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=J.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await tW(H);break;case"failed":case"cancelled":case"completed":return G}}}async uploadAndPoll(W,{files:$,fileIds:X=[]},Y){if($==null||$.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let G=Y?.maxConcurrency??5,J=Math.min(G,$.length),H=this._client,Q=$.values(),z=[...X];async function T(_){for(let w of _){let O=await H.files.create({file:w,purpose:"assistants"},Y);z.push(O.id)}}let F=Array(J).fill(Q).map(T);return await uH(F),await this.createAndPoll(W,{file_ids:z})}}class QW extends C{constructor(){super(...arguments);this.files=new O8(this._client),this.fileBatches=new G6(this._client)}create(W,$){return this._client.post("/vector_stores",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/vector_stores/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/vector_stores/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W={},$){if(z0(W))return this.list({},W);return this._client.getAPIList("/vector_stores",D4,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/vector_stores/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}search(W,$,X){return this._client.getAPIList(`/vector_stores/${W}/search`,V4,{body:$,method:"post",...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class D4 extends E0{}class V4 extends aW{}QW.VectorStoresPage=D4;QW.VectorStoreSearchResponsesPage=V4;QW.Files=O8;QW.VectorStoreFilesPage=K8;QW.FileContentResponsesPage=Y6;QW.FileBatches=G6;var cH;class H0 extends M5{constructor({baseURL:W=R$("OPENAI_BASE_URL"),apiKey:$=R$("OPENAI_API_KEY"),organization:X=R$("OPENAI_ORG_ID")??null,project:Y=R$("OPENAI_PROJECT_ID")??null,...G}={}){if($===void 0)throw new o("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:$,organization:X,project:Y,...G,baseURL:W||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&OH())throw new o(`It looks like you're running in a browser-like environment.
47
47
 
48
48
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
49
49
  If you understand the risks and have appropriate mitigations in place,
@@ -52,19 +52,19 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
52
52
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
53
53
 
54
54
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
55
- `);super({baseURL:G.baseURL,timeout:G.timeout??600000,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch});this.completions=new e8(this),this.chat=new N2(this),this.embeddings=new W$(this),this.files=new z8(this),this.images=new Q$(this),this.audio=new sW(this),this.moderations=new F$(this),this.models=new U8(this),this.fineTuning=new GW(this),this.graders=new T8(this),this.vectorStores=new HW(this),this.beta=new gW(this),this.batches=new W8(this),this.uploads=new _8(this),this.responses=new w8(this),this.evals=new X2(this),this._options=G,this.apiKey=$,this.organization=X,this.project=Y}defaultQuery(){return this._options.defaultQuery}defaultHeaders(W){return{...super.defaultHeaders(W),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(W){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(W){return s9(W,{arrayFormat:"brackets"})}}pH=H0;H0.OpenAI=pH;H0.DEFAULT_TIMEOUT=600000;H0.OpenAIError=o;H0.APIError=t0;H0.APIConnectionError=r2;H0.APIConnectionTimeoutError=t2;H0.APIUserAbortError=J1;H0.NotFoundError=IX;H0.ConflictError=fX;H0.RateLimitError=xX;H0.BadRequestError=CX;H0.AuthenticationError=kX;H0.InternalServerError=vX;H0.PermissionDeniedError=jX;H0.UnprocessableEntityError=PX;H0.toFile=UJ;H0.fileFromPath=qX;H0.Completions=e8;H0.Chat=N2;H0.ChatCompletionsPage=e2;H0.Embeddings=W$;H0.Files=z8;H0.FileObjectsPage=Y$;H0.Images=Q$;H0.Audio=sW;H0.Moderations=F$;H0.Models=U8;H0.ModelsPage=z$;H0.FineTuning=GW;H0.Graders=T8;H0.VectorStores=HW;H0.VectorStoresPage=w$;H0.VectorStoreSearchResponsesPage=_$;H0.Beta=gW;H0.Batches=W8;H0.BatchesPage=d8;H0.Uploads=_8;H0.Responses=w8;H0.Evals=X2;H0.EvalListResponsesPage=X$;var uH=H0;function tV(W,...$){let[X,Y,J,G]=$,H=[{role:"user",content:C3(Y)},{role:"user",content:X}],Q=G.at(-1);if(Q)H.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(Q.response,null,2),"Here's the error message:",JSON.stringify(Q.error.issues,null,2)].join(`
56
- `)});return{model:W,messages:H}}var a=1e6,cH={"gpt-4.1":{promptPricePerToken:2/a,promptPricePerTokenCached:0.5/a,completionPricePerToken:8/a},"gpt-4.1-mini":{promptPricePerToken:0.4/a,promptPricePerTokenCached:0.1/a,completionPricePerToken:1.6/a},"gpt-4.1-nano":{promptPricePerToken:0.1/a,promptPricePerTokenCached:0.025/a,completionPricePerToken:0.4/a},"gpt-4o":{promptPricePerToken:2.5/a,promptPricePerTokenCached:1.25/a,completionPricePerToken:10/a},"gpt-4o-mini":{promptPricePerToken:0.15/a,promptPricePerTokenCached:0.075/a,completionPricePerToken:0.6/a},o1:{promptPricePerToken:15/a,promptPricePerTokenCached:7.5/a,completionPricePerToken:60/a},"o1-mini":{promptPricePerToken:1.1/a,promptPricePerTokenCached:0.55/a,completionPricePerToken:4.4/a},o3:{promptPricePerToken:10/a,promptPricePerTokenCached:2.5/a,completionPricePerToken:40/a},"o3-mini":{promptPricePerToken:1.1/a,promptPricePerTokenCached:0.55/a,completionPricePerToken:4.4/a},"o4-mini":{promptPricePerToken:1.1/a,promptPricePerTokenCached:0.275/a,completionPricePerToken:4.4/a},"codex-mini-latest":{promptPricePerToken:1.5/a,promptPricePerTokenCached:0.375/a,completionPricePerToken:6/a},"chatgpt-4o-latest":{promptPricePerToken:5/a,promptPricePerTokenCached:5/a,completionPricePerToken:15/a},"gpt-4":{promptPricePerToken:30/a,promptPricePerTokenCached:30/a,completionPricePerToken:60/a},"gpt-4-turbo":{promptPricePerToken:10/a,promptPricePerTokenCached:10/a,completionPricePerToken:30/a},"gpt-3.5-turbo":{promptPricePerToken:0.5/a,promptPricePerTokenCached:0.5/a,completionPricePerToken:1.5/a},"gpt-4-32k":{promptPricePerToken:60/a,promptPricePerTokenCached:60/a,completionPricePerToken:120/a},"gpt-3.5-turbo-16k":{promptPricePerToken:3/a,promptPricePerTokenCached:3/a,completionPricePerToken:4/a}};function aV(W){let X=Object.keys(cH).filter((Y)=>W.startsWith(Y)).sort((Y,J)=>J.length-Y.length)[0];if(!X)return;return cH[X]}function sV(W){return async function $(X,Y){if(!W)throw new Error("This is a bug in safegen. OpenAI client not available to the json generator.");let J=await W.chat.completions.create({...X,stream:!1,response_format:{type:"json_object"}},Y),G=J.choices[0].message?.content,{usage:H}=J;if(G&&H){let Q=H.prompt_tokens,z=H.prompt_tokens_details?.cached_tokens??0,F=Q-z,T=H.completion_tokens,U=aV(X.model),_=0;if(U)_=Q*U.promptPricePerToken+F*(U.promptPricePerTokenCached??0)+T*U.completionPricePerToken;else console.warn(`No pricing facts found for model ${X.model}. Giving a price of 0.`);return{data:JSON.parse(G),usage:H,usdPrice:_}}if(!G&&!H)throw new Error("No content or usage found in completion");if(!G)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var dH=new Map,lH=class{usdBudget;usdMinimum;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;client;lastUsage;constructor({model:W,usdBudget:$,usdMinimum:X,apiKey:Y,cachingMode:J,cacheKey:G="openai-safegen",logger:H}){this.usdBudget=$,this.usdMinimum=X,this.squirrel=new c3(J);let Q=dH.get(Y);if(J!=="read"){if(!Q)Q=new uH({apiKey:Y,dangerouslyAllowBrowser:!1}),dH.set(Y,Q);this.client=Q}this.getUnknownJsonFromOpenAi=sV(this.client),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(G,this.getUnknownJsonFromOpenAi),this.from=q3(async(...z)=>{if(this.usdBudget<this.usdMinimum)return H?.warn("SafeGen budget exhausted"),z[1];let F=tV(W,...z),T=z[0],U=z[3],{data:_,usage:V,usdPrice:K}=await this.getUnknownJsonFromOpenAiSquirreled.for(`${T.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${U.length}`).get(F);return this.lastUsage=V,this.usdBudget-=K,_},H)}from};import{exec as HB}from"child_process";class GY{supported;constructor(W){this.supported=W}refine(W){for(let[$,X]of Object.entries(this.supported))try{if(X(W)===!0&&X!==Boolean)return{type:$,data:W}}catch(Y){try{if(W instanceof X)return{type:$,data:W}}catch(J){}}return null}}var eV=new GY({number:(W)=>typeof W==="number",string:(W)=>typeof W==="string",boolean:(W)=>typeof W==="boolean",null:(W)=>W===null});function WO(W){if(!W)return!1;return Object.getPrototypeOf(W)===Object.prototype}var $O=new GY({object:WO,array:(W)=>Array.isArray(W)}),XO=new GY({...eV.supported,...$O.supported}),oH=(W)=>{if(W===void 0)return"undefined";let $=XO.refine(W);if($)return $.type;return Object.getPrototypeOf(W).constructor.name};var D=Symbol.for("drizzle:entityKind"),nP=Symbol.for("drizzle:hasOwnEntityKind");function E(W,$){if(!W||typeof W!=="object")return!1;if(W instanceof $)return!0;if(!Object.prototype.hasOwnProperty.call($,D))throw new Error(`Class "${$.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 X=Object.getPrototypeOf(W).constructor;if(X)while(X){if(D in X&&X[D]===$[D])return!0;X=Object.getPrototypeOf(X)}return!1}class q0{constructor(W,$){this.table=W,this.config=$,this.name=$.name,this.keyAsName=$.keyAsName,this.notNull=$.notNull,this.default=$.default,this.defaultFn=$.defaultFn,this.onUpdateFn=$.onUpdateFn,this.hasDefault=$.hasDefault,this.primary=$.primaryKey,this.isUnique=$.isUnique,this.uniqueName=$.uniqueName,this.uniqueType=$.uniqueType,this.dataType=$.dataType,this.columnType=$.columnType,this.generated=$.generated,this.generatedIdentity=$.generatedIdentity}static[D]="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(W){return W}mapToDriverValue(W){return W}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class bJ{static[D]="ColumnBuilder";config;constructor(W,$,X){this.config={name:W,keyAsName:W==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:$,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(W){return this.config.default=W,this.config.hasDefault=!0,this}$defaultFn(W){return this.config.defaultFn=W,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(W){return this.config.onUpdateFn=W,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(W){if(this.config.name!=="")return;this.config.name=W}}var RW=Symbol.for("drizzle:Name");class yJ{static[D]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(W,$){if(this.reference=()=>{let{name:X,columns:Y,foreignColumns:J}=W();return{name:X,columns:Y,foreignTable:J[0].table,foreignColumns:J}},$)this._onUpdate=$.onUpdate,this._onDelete=$.onDelete}onUpdate(W){return this._onUpdate=W===void 0?"no action":W,this}onDelete(W){return this._onDelete=W===void 0?"no action":W,this}build(W){return new iH(W,this)}}class iH{constructor(W,$){this.table=W,this.reference=$.reference,this.onUpdate=$._onUpdate,this.onDelete=$._onDelete}static[D]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:W,columns:$,foreignColumns:X}=this.reference(),Y=$.map((H)=>H.name),J=X.map((H)=>H.name),G=[this.table[RW],...Y,X[0].table[RW],...J];return W??`${G.join("_")}_fk`}}function HY(W,...$){return W(...$)}function nH(W,$){return`${W[RW]}_${$.join("_")}_unique`}function rH(W,$,X){for(let Y=$;Y<W.length;Y++){let J=W[Y];if(J==="\\"){Y++;continue}if(J==='"')return[W.slice($,Y).replace(/\\/g,""),Y+1];if(X)continue;if(J===","||J==="}")return[W.slice($,Y).replace(/\\/g,""),Y]}return[W.slice($).replace(/\\/g,""),W.length]}function tH(W,$=0){let X=[],Y=$,J=!1;while(Y<W.length){let G=W[Y];if(G===","){if(J||Y===$)X.push("");J=!0,Y++;continue}if(J=!1,G==="\\"){Y+=2;continue}if(G==='"'){let[z,F]=rH(W,Y+1,!0);X.push(z),Y=F;continue}if(G==="}")return[X,Y+1];if(G==="{"){let[z,F]=tH(W,Y+1);X.push(z),Y=F;continue}let[H,Q]=rH(W,Y,!1);X.push(H),Y=Q}return[X,Y]}function aH(W){let[$]=tH(W,1);return $}function hJ(W){return`{${W.map(($)=>{if(Array.isArray($))return hJ($);if(typeof $==="string")return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${$}`}).join(",")}}`}class u extends bJ{foreignKeyConfigs=[];static[D]="PgColumnBuilder";array(W){return new eH(this.config.name,this,W)}references(W,$={}){return this.foreignKeyConfigs.push({ref:W,actions:$}),this}unique(W,$){return this.config.isUnique=!0,this.config.uniqueName=W,this.config.uniqueType=$?.nulls,this}generatedAlwaysAs(W){return this.config.generated={as:W,type:"always",mode:"stored"},this}buildForeignKeys(W,$){return this.foreignKeyConfigs.map(({ref:X,actions:Y})=>{return HY((J,G)=>{let H=new yJ(()=>{let Q=J();return{columns:[W],foreignColumns:[Q]}});if(G.onUpdate)H.onUpdate(G.onUpdate);if(G.onDelete)H.onDelete(G.onDelete);return H.build($)},X,Y)})}buildExtraConfigColumn(W){return new sH(W,this.config)}}class f extends q0{constructor(W,$){if(!$.uniqueName)$.uniqueName=nH(W,[$.name]);super(W,$);this.table=W}static[D]="PgColumn"}class sH extends f{static[D]="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(W){return this.indexConfig.opClass=W,this}}class Y6{static[D]="IndexedColumn";constructor(W,$,X,Y){this.name=W,this.keyAsName=$,this.type=X,this.indexConfig=Y}name;keyAsName;type;indexConfig}class eH extends u{static[D]="PgArrayBuilder";constructor(W,$,X){super(W,"array","PgArray");this.config.baseBuilder=$,this.config.size=X}build(W){let $=this.config.baseBuilder.build(W);return new gJ(W,this.config,$)}}class gJ extends f{constructor(W,$,X,Y){super(W,$);this.baseColumn=X,this.range=Y,this.size=$.size}size;static[D]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(W){if(typeof W==="string")W=aH(W);return W.map(($)=>this.baseColumn.mapFromDriverValue($))}mapToDriverValue(W,$=!1){let X=W.map((Y)=>Y===null?null:E(this.baseColumn,gJ)?this.baseColumn.mapToDriverValue(Y,!0):this.baseColumn.mapToDriverValue(Y));if($)return X;return hJ(X)}}class WQ extends u{static[D]="PgEnumObjectColumnBuilder";constructor(W,$){super(W,"string","PgEnumObjectColumn");this.config.enum=$}build(W){return new $Q(W,this.config)}}class $Q extends f{static[D]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var QY=Symbol.for("drizzle:isPgEnum");function XQ(W){return!!W&&typeof W==="function"&&QY in W&&W[QY]===!0}class YQ extends u{static[D]="PgEnumColumnBuilder";constructor(W,$){super(W,"string","PgEnumColumn");this.config.enum=$}build(W){return new JQ(W,this.config)}}class JQ extends f{static[D]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}function J6(W,$){return Array.isArray($)?YO(W,[...$],void 0):JO(W,$,void 0)}function YO(W,$,X){let Y=Object.assign((J)=>new YQ(J??"",Y),{enumName:W,enumValues:$,schema:X,[QY]:!0});return Y}function JO(W,$,X){let Y=Object.assign((J)=>new WQ(J??"",Y),{enumName:W,enumValues:Object.values($),schema:X,[QY]:!0});return Y}class H1{static[D]="Subquery";constructor(W,$,X,Y=!1){this._={brand:"Subquery",sql:W,selectedFields:$,alias:X,isWith:Y}}}class G6 extends H1{static[D]="WithSubquery"}var GQ="0.43.1";var mJ,pJ,C0={startActiveSpan(W,$){if(!mJ)return $();if(!pJ)pJ=mJ.trace.getTracer("drizzle-orm",GQ);return HY((X,Y)=>Y.startActiveSpan(W,(J)=>{try{return $(J)}catch(G){throw J.setStatus({code:X.SpanStatusCode.ERROR,message:G instanceof Error?G.message:"Unknown error"}),G}finally{J.end()}}),mJ,pJ)}};var P0=Symbol.for("drizzle:ViewBaseConfig");var zY=Symbol.for("drizzle:Schema"),FY=Symbol.for("drizzle:Columns"),HQ=Symbol.for("drizzle:ExtraConfigColumns"),uJ=Symbol.for("drizzle:OriginalName"),cJ=Symbol.for("drizzle:BaseName"),H6=Symbol.for("drizzle:IsAlias"),QQ=Symbol.for("drizzle:ExtraConfigBuilder"),GO=Symbol.for("drizzle:IsDrizzleTable");class y{static[D]="Table";static Symbol={Name:RW,Schema:zY,OriginalName:uJ,Columns:FY,ExtraConfigColumns:HQ,BaseName:cJ,IsAlias:H6,ExtraConfigBuilder:QQ};[RW];[uJ];[zY];[FY];[HQ];[cJ];[H6]=!1;[GO]=!0;[QQ]=void 0;constructor(W,$,X){this[RW]=this[uJ]=W,this[zY]=$,this[cJ]=X}}function w1(W){return W[RW]}function V8(W){return`${W[zY]??"public"}.${W[RW]}`}function dJ(W){return W!==null&&W!==void 0&&typeof W.getSQL==="function"}function HO(W){let $={sql:"",params:[]};for(let X of W)if($.sql+=X.sql,$.params.push(...X.params),X.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...X.typings)}return $}class Q1{static[D]="StringChunk";value;constructor(W){this.value=Array.isArray(W)?W:[W]}getSQL(){return new g([this])}}class g{constructor(W){this.queryChunks=W}static[D]="SQL";decoder=FQ;shouldInlineParams=!1;append(W){return this.queryChunks.push(...W.queryChunks),this}toQuery(W){return C0.startActiveSpan("drizzle.buildSQL",($)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,W);return $?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(W,$){let X=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:Y,escapeName:J,escapeParam:G,prepareTyping:H,inlineParams:Q,paramStartIndex:z}=X;return HO(W.map((F)=>{if(E(F,Q1))return{sql:F.value.join(""),params:[]};if(E(F,TY))return{sql:J(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let T=[new Q1("(")];for(let[U,_]of F.entries())if(T.push(_),U<F.length-1)T.push(new Q1(", "));return T.push(new Q1(")")),this.buildQueryFromSourceParams(T,X)}if(E(F,g))return this.buildQueryFromSourceParams(F.queryChunks,{...X,inlineParams:Q||F.shouldInlineParams});if(E(F,y)){let T=F[y.Symbol.Schema],U=F[y.Symbol.Name];return{sql:T===void 0||F[H6]?J(U):J(T)+"."+J(U),params:[]}}if(E(F,q0)){let T=Y.getColumnCasing(F);if($.invokeSource==="indexes")return{sql:J(T),params:[]};let U=F.table[y.Symbol.Schema];return{sql:F.table[H6]||U===void 0?J(F.table[y.Symbol.Name])+"."+J(T):J(U)+"."+J(F.table[y.Symbol.Name])+"."+J(T),params:[]}}if(E(F,h1)){let T=F[P0].schema,U=F[P0].name;return{sql:T===void 0||F[P0].isAlias?J(U):J(T)+"."+J(U),params:[]}}if(E(F,s1)){if(E(F.value,I2))return{sql:G(z.value++,F),params:[F],typings:["none"]};let T=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(E(T,g))return this.buildQueryFromSourceParams([T],X);if(Q)return{sql:this.mapInlineParam(T,X),params:[]};let U=["none"];if(H)U=[H(F.encoder)];return{sql:G(z.value++,T),params:[T],typings:U}}if(E(F,I2))return{sql:G(z.value++,F),params:[F],typings:["none"]};if(E(F,g.Aliased)&&F.fieldAlias!==void 0)return{sql:J(F.fieldAlias),params:[]};if(E(F,H1)){if(F._.isWith)return{sql:J(F._.alias),params:[]};return this.buildQueryFromSourceParams([new Q1("("),F._.sql,new Q1(") "),new TY(F._.alias)],X)}if(XQ(F)){if(F.schema)return{sql:J(F.schema)+"."+J(F.enumName),params:[]};return{sql:J(F.enumName),params:[]}}if(dJ(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],X);return this.buildQueryFromSourceParams([new Q1("("),F.getSQL(),new Q1(")")],X)}if(Q)return{sql:this.mapInlineParam(F,X),params:[]};return{sql:G(z.value++,F),params:[F],typings:["none"]}}))}mapInlineParam(W,{escapeString:$}){if(W===null)return"null";if(typeof W==="number"||typeof W==="boolean")return W.toString();if(typeof W==="string")return $(W);if(typeof W==="object"){let X=W.toString();if(X==="[object Object]")return $(JSON.stringify(W));return $(X)}throw new Error("Unexpected param value: "+W)}getSQL(){return this}as(W){if(W===void 0)return this;return new g.Aliased(this,W)}mapWith(W){return this.decoder=typeof W==="function"?{mapFromDriverValue:W}:W,this}inlineParams(){return this.shouldInlineParams=!0,this}if(W){return W?this:void 0}}class TY{constructor(W){this.value=W}static[D]="Name";brand;getSQL(){return new g([this])}}function zQ(W){return typeof W==="object"&&W!==null&&"mapToDriverValue"in W&&typeof W.mapToDriverValue==="function"}var FQ={mapFromDriverValue:(W)=>W},TQ={mapToDriverValue:(W)=>W},bx={...FQ,...TQ};class s1{constructor(W,$=TQ){this.value=W,this.encoder=$}static[D]="Param";brand;getSQL(){return new g([this])}}function M(W,...$){let X=[];if($.length>0||W.length>0&&W[0]!=="")X.push(new Q1(W[0]));for(let[Y,J]of $.entries())X.push(J,new Q1(W[Y+1]));return new g(X)}((W)=>{function $(){return new g([])}W.empty=$;function X(z){return new g(z)}W.fromList=X;function Y(z){return new g([new Q1(z)])}W.raw=Y;function J(z,F){let T=[];for(let[U,_]of z.entries()){if(U>0&&F!==void 0)T.push(F);T.push(_)}return new g(T)}W.join=J;function G(z){return new TY(z)}W.identifier=G;function H(z){return new I2(z)}W.placeholder=H;function Q(z,F){return new s1(z,F)}W.param=Q})(M||(M={}));((W)=>{class ${constructor(X,Y){this.sql=X,this.fieldAlias=Y}static[D]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}W.Aliased=$})(g||(g={}));class I2{constructor(W){this.name=W}static[D]="Placeholder";getSQL(){return new g([this])}}function lJ(W,$){return W.map((X)=>{if(E(X,I2)){if(!(X.name in $))throw new Error(`No value for placeholder "${X.name}" was provided`);return $[X.name]}if(E(X,s1)&&E(X.value,I2)){if(!(X.value.name in $))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue($[X.value.name])}return X})}var QO=Symbol.for("drizzle:IsDrizzleView");class h1{static[D]="View";[P0];[QO]=!0;constructor({name:W,schema:$,selectedFields:X,query:Y}){this[P0]={name:W,originalName:W,schema:$,selectedFields:X,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new g([this])}}q0.prototype.getSQL=function(){return new g([this])};y.prototype.getSQL=function(){return new g([this])};H1.prototype.getSQL=function(){return new g([this])};class D${constructor(W){this.table=W}static[D]="ColumnAliasProxyHandler";get(W,$){if($==="table")return this.table;return W[$]}}class Q6{constructor(W,$){this.alias=W,this.replaceOriginalName=$}static[D]="TableAliasProxyHandler";get(W,$){if($===y.Symbol.IsAlias)return!0;if($===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===y.Symbol.OriginalName)return this.alias;if($===P0)return{...W[P0],name:this.alias,isAlias:!0};if($===y.Symbol.Columns){let Y=W[y.Symbol.Columns];if(!Y)return Y;let J={};return Object.keys(Y).map((G)=>{J[G]=new Proxy(Y[G],new D$(new Proxy(W,this)))}),J}let X=W[$];if(E(X,q0))return new Proxy(X,new D$(new Proxy(W,this)));return X}}function UY(W,$){return new Proxy(W,new Q6($,!1))}function mW(W,$){return new Proxy(W,new D$(new Proxy(W.table,new Q6($,!1))))}function oJ(W,$){return new g.Aliased(z6(W.sql,$),W.fieldAlias)}function z6(W,$){return M.join(W.queryChunks.map((X)=>{if(E(X,q0))return mW(X,$);if(E(X,g))return z6(X,$);if(E(X,g.Aliased))return oJ(X,$);return X}))}class wY extends Error{static[D]="DrizzleError";constructor({message:W,cause:$}){super(W);this.name="DrizzleError",this.cause=$}}class iJ extends wY{static[D]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class UQ{static[D]="ConsoleLogWriter";write(W){console.log(W)}}class nJ{static[D]="DefaultLogger";writer;constructor(W){this.writer=W?.writer??new UQ}logQuery(W,$){let X=$.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),Y=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${W}${Y}`)}}class rJ{static[D]="NoopLogger";logQuery(){}}class k1{static[D]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(W){return this.then(void 0,W)}finally(W){return this.then(($)=>{return W?.(),$},($)=>{throw W?.(),$})}then(W,$){return this.execute().then(W,$)}}function wQ(W,$,X){let Y={},J=W.reduce((G,{path:H,field:Q},z)=>{let F;if(E(Q,q0))F=Q;else if(E(Q,g))F=Q.decoder;else F=Q.sql.decoder;let T=G;for(let[U,_]of H.entries())if(U<H.length-1){if(!(_ in T))T[_]={};T=T[_]}else{let V=$[z],K=T[_]=V===null?null:F.mapFromDriverValue(V);if(X&&E(Q,q0)&&H.length===2){let B=H[0];if(!(B in Y))Y[B]=K===null?w1(Q.table):!1;else if(typeof Y[B]==="string"&&Y[B]!==w1(Q.table))Y[B]=!1}}return G},{});if(X&&Object.keys(Y).length>0){for(let[G,H]of Object.entries(Y))if(typeof H==="string"&&!X[H])J[G]=null}return J}function QW(W,$){return Object.entries(W).reduce((X,[Y,J])=>{if(typeof Y!=="string")return X;let G=$?[...$,Y]:[Y];if(E(J,q0)||E(J,g)||E(J,g.Aliased))X.push({path:G,field:J});else if(E(J,y))X.push(...QW(J[y.Symbol.Columns],G));else X.push(...QW(J,G));return X},[])}function F6(W,$){let X=Object.keys(W),Y=Object.keys($);if(X.length!==Y.length)return!1;for(let[J,G]of X.entries())if(G!==Y[J])return!1;return!0}function _Y(W,$){let X=Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,J])=>{if(E(J,g)||E(J,q0))return[Y,J];else return[Y,new s1(J,W[y.Symbol.Columns][Y])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function _Q(W,$){for(let X of $)for(let Y of Object.getOwnPropertyNames(X.prototype)){if(Y==="constructor")continue;Object.defineProperty(W.prototype,Y,Object.getOwnPropertyDescriptor(X.prototype,Y)||Object.create(null))}}function DQ(W){return W[y.Symbol.Columns]}function J2(W){return E(W,H1)?W._.alias:E(W,h1)?W[P0].name:E(W,g)?void 0:W[y.Symbol.IsAlias]?W[y.Symbol.Name]:W[y.Symbol.BaseName]}function V0(W,$){return{name:typeof W==="string"&&W.length>0?W:"",config:typeof W==="object"?W:$}}function MQ(W){if(typeof W!=="object"||W===null)return!1;if(W.constructor.name!=="Object")return!1;if("logger"in W){let $=typeof W.logger;if($!=="boolean"&&($!=="object"||typeof W.logger.logQuery!=="function")&&$!=="undefined")return!1;return!0}if("schema"in W){let $=typeof W.schema;if($!=="object"&&$!=="undefined")return!1;return!0}if("casing"in W){let $=typeof W.casing;if($!=="string"&&$!=="undefined")return!1;return!0}if("mode"in W){if(W.mode!=="default"||W.mode!=="planetscale"||W.mode!==void 0)return!1;return!0}if("connection"in W){let $=typeof W.connection;if($!=="string"&&$!=="object"&&$!=="undefined")return!1;return!0}if("client"in W){let $=typeof W.client;if($!=="object"&&$!=="function"&&$!=="undefined")return!1;return!0}if(Object.keys(W).length===0)return!0;return!1}class f2 extends u{static[D]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(W){if(W){let{name:$,...X}=W;this.config.generatedIdentity={type:"always",sequenceName:$,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(W){if(W){let{name:$,...X}=W;this.config.generatedIdentity={type:"byDefault",sequenceName:$,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class VQ extends f2{static[D]="PgBigInt53Builder";constructor(W){super(W,"number","PgBigInt53")}build(W){return new OQ(W,this.config)}}class OQ extends f{static[D]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class KQ extends f2{static[D]="PgBigInt64Builder";constructor(W){super(W,"bigint","PgBigInt64")}build(W){return new AQ(W,this.config)}}class AQ extends f{static[D]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(W){return BigInt(W)}}function EQ(W,$){let{name:X,config:Y}=V0(W,$);if(Y.mode==="number")return new VQ(X);return new KQ(X)}class LQ extends u{static[D]="PgBigSerial53Builder";constructor(W){super(W,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new BQ(W,this.config)}}class BQ extends f{static[D]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class RQ extends u{static[D]="PgBigSerial64Builder";constructor(W){super(W,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(W){return new NQ(W,this.config)}}class NQ extends f{static[D]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(W){return BigInt(W)}}function ZQ(W,$){let{name:X,config:Y}=V0(W,$);if(Y.mode==="number")return new LQ(X);return new RQ(X)}class SQ extends u{static[D]="PgBooleanBuilder";constructor(W){super(W,"boolean","PgBoolean")}build(W){return new qQ(W,this.config)}}class qQ extends f{static[D]="PgBoolean";getSQLType(){return"boolean"}}function T6(W){return new SQ(W??"")}class CQ extends u{static[D]="PgCharBuilder";constructor(W,$){super(W,"string","PgChar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new kQ(W,this.config)}}class kQ extends f{static[D]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function jQ(W,$={}){let{name:X,config:Y}=V0(W,$);return new CQ(X,Y)}class IQ extends u{static[D]="PgCidrBuilder";constructor(W){super(W,"string","PgCidr")}build(W){return new fQ(W,this.config)}}class fQ extends f{static[D]="PgCidr";getSQLType(){return"cidr"}}function PQ(W){return new IQ(W??"")}class xQ extends u{static[D]="PgCustomColumnBuilder";constructor(W,$,X){super(W,"custom","PgCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=X}build(W){return new vQ(W,this.config)}}class vQ extends f{static[D]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(W,$){super(W,$);this.sqlName=$.customTypeParams.dataType($.fieldConfig),this.mapTo=$.customTypeParams.toDriver,this.mapFrom=$.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(W){return typeof this.mapFrom==="function"?this.mapFrom(W):W}mapToDriverValue(W){return typeof this.mapTo==="function"?this.mapTo(W):W}}function bQ(W){return($,X)=>{let{name:Y,config:J}=V0($,X);return new xQ(Y,J,W)}}class G2 extends u{static[D]="PgDateColumnBaseBuilder";defaultNow(){return this.default(M`now()`)}}class yQ extends G2{static[D]="PgDateBuilder";constructor(W){super(W,"date","PgDate")}build(W){return new DY(W,this.config)}}class DY extends f{static[D]="PgDate";getSQLType(){return"date"}mapFromDriverValue(W){return new Date(W)}mapToDriverValue(W){return W.toISOString()}}class hQ extends G2{static[D]="PgDateStringBuilder";constructor(W){super(W,"string","PgDateString")}build(W){return new MY(W,this.config)}}class MY extends f{static[D]="PgDateString";getSQLType(){return"date"}}function gQ(W,$){let{name:X,config:Y}=V0(W,$);if(Y?.mode==="date")return new yQ(X);return new hQ(X)}class mQ extends u{static[D]="PgDoublePrecisionBuilder";constructor(W){super(W,"number","PgDoublePrecision")}build(W){return new pQ(W,this.config)}}class pQ extends f{static[D]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseFloat(W);return W}}function uQ(W){return new mQ(W??"")}class cQ extends u{static[D]="PgInetBuilder";constructor(W){super(W,"string","PgInet")}build(W){return new dQ(W,this.config)}}class dQ extends f{static[D]="PgInet";getSQLType(){return"inet"}}function lQ(W){return new cQ(W??"")}class oQ extends f2{static[D]="PgIntegerBuilder";constructor(W){super(W,"number","PgInteger")}build(W){return new iQ(W,this.config)}}class iQ extends f{static[D]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseInt(W);return W}}function U6(W){return new oQ(W??"")}class nQ extends u{static[D]="PgIntervalBuilder";constructor(W,$){super(W,"string","PgInterval");this.config.intervalConfig=$}build(W){return new rQ(W,this.config)}}class rQ extends f{static[D]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let W=this.fields?` ${this.fields}`:"",$=this.precision?`(${this.precision})`:"";return`interval${W}${$}`}}function tQ(W,$={}){let{name:X,config:Y}=V0(W,$);return new nQ(X,Y)}class aQ extends u{static[D]="PgJsonBuilder";constructor(W){super(W,"json","PgJson")}build(W){return new VY(W,this.config)}}class VY extends f{static[D]="PgJson";constructor(W,$){super(W,$)}getSQLType(){return"json"}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){if(typeof W==="string")try{return JSON.parse(W)}catch{return W}return W}}function sQ(W){return new aQ(W??"")}class eQ extends u{static[D]="PgJsonbBuilder";constructor(W){super(W,"json","PgJsonb")}build(W){return new OY(W,this.config)}}class OY extends f{static[D]="PgJsonb";constructor(W,$){super(W,$)}getSQLType(){return"jsonb"}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){if(typeof W==="string")try{return JSON.parse(W)}catch{return W}return W}}function Wz(W){return new eQ(W??"")}class $z extends u{static[D]="PgLineBuilder";constructor(W){super(W,"array","PgLine")}build(W){return new Xz(W,this.config)}}class Xz extends f{static[D]="PgLine";getSQLType(){return"line"}mapFromDriverValue(W){let[$,X,Y]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(X),Number.parseFloat(Y)]}mapToDriverValue(W){return`{${W[0]},${W[1]},${W[2]}}`}}class Yz extends u{static[D]="PgLineABCBuilder";constructor(W){super(W,"json","PgLineABC")}build(W){return new Jz(W,this.config)}}class Jz extends f{static[D]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(W){let[$,X,Y]=W.slice(1,-1).split(",");return{a:Number.parseFloat($),b:Number.parseFloat(X),c:Number.parseFloat(Y)}}mapToDriverValue(W){return`{${W.a},${W.b},${W.c}}`}}function Gz(W,$){let{name:X,config:Y}=V0(W,$);if(!Y?.mode||Y.mode==="tuple")return new $z(X);return new Yz(X)}class Hz extends u{static[D]="PgMacaddrBuilder";constructor(W){super(W,"string","PgMacaddr")}build(W){return new Qz(W,this.config)}}class Qz extends f{static[D]="PgMacaddr";getSQLType(){return"macaddr"}}function zz(W){return new Hz(W??"")}class Fz extends u{static[D]="PgMacaddr8Builder";constructor(W){super(W,"string","PgMacaddr8")}build(W){return new Tz(W,this.config)}}class Tz extends f{static[D]="PgMacaddr8";getSQLType(){return"macaddr8"}}function Uz(W){return new Fz(W??"")}class wz extends u{static[D]="PgNumericBuilder";constructor(W,$,X){super(W,"string","PgNumeric");this.config.precision=$,this.config.scale=X}build(W){return new KY(W,this.config)}}class KY extends f{static[D]="PgNumeric";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(W){if(typeof W==="string")return W;return String(W)}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})`}}class _z extends u{static[D]="PgNumericNumberBuilder";constructor(W,$,X){super(W,"number","PgNumericNumber");this.config.precision=$,this.config.scale=X}build(W){return new Dz(W,this.config)}}class Dz extends f{static[D]="PgNumericNumber";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}mapToDriverValue=String;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})`}}class Mz extends u{static[D]="PgNumericBigIntBuilder";constructor(W,$,X){super(W,"bigint","PgNumericBigInt");this.config.precision=$,this.config.scale=X}build(W){return new Vz(W,this.config)}}class Vz extends f{static[D]="PgNumericBigInt";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;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 Oz(W,$){let{name:X,config:Y}=V0(W,$),J=Y?.mode;return J==="number"?new _z(X,Y?.precision,Y?.scale):J==="bigint"?new Mz(X,Y?.precision,Y?.scale):new wz(X,Y?.precision,Y?.scale)}class Kz extends u{static[D]="PgPointTupleBuilder";constructor(W){super(W,"array","PgPointTuple")}build(W){return new Az(W,this.config)}}class Az extends f{static[D]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,X]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(X)]}return[W.x,W.y]}mapToDriverValue(W){return`(${W[0]},${W[1]})`}}class Ez extends u{static[D]="PgPointObjectBuilder";constructor(W){super(W,"json","PgPointObject")}build(W){return new Lz(W,this.config)}}class Lz extends f{static[D]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,X]=W.slice(1,-1).split(",");return{x:Number.parseFloat($),y:Number.parseFloat(X)}}return W}mapToDriverValue(W){return`(${W.x},${W.y})`}}function Bz(W,$){let{name:X,config:Y}=V0(W,$);if(!Y?.mode||Y.mode==="tuple")return new Kz(X);return new Ez(X)}function zO(W){let $=[];for(let X=0;X<W.length;X+=2)$.push(Number.parseInt(W.slice(X,X+2),16));return new Uint8Array($)}function Rz(W,$){let X=new ArrayBuffer(8),Y=new DataView(X);for(let J=0;J<8;J++)Y.setUint8(J,W[$+J]);return Y.getFloat64(0,!0)}function tJ(W){let $=zO(W),X=0,Y=$[X];X+=1;let J=new DataView($.buffer),G=J.getUint32(X,Y===1);X+=4;let H;if(G&536870912)H=J.getUint32(X,Y===1),X+=4;if((G&65535)===1){let Q=Rz($,X);X+=8;let z=Rz($,X);return X+=8,[Q,z]}throw new Error("Unsupported geometry type")}class Nz extends u{static[D]="PgGeometryBuilder";constructor(W){super(W,"array","PgGeometry")}build(W){return new Zz(W,this.config)}}class Zz extends f{static[D]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){return tJ(W)}mapToDriverValue(W){return`point(${W[0]} ${W[1]})`}}class Sz extends u{static[D]="PgGeometryObjectBuilder";constructor(W){super(W,"json","PgGeometryObject")}build(W){return new qz(W,this.config)}}class qz extends f{static[D]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){let $=tJ(W);return{x:$[0],y:$[1]}}mapToDriverValue(W){return`point(${W.x} ${W.y})`}}function Cz(W,$){let{name:X,config:Y}=V0(W,$);if(!Y?.mode||Y.mode==="tuple")return new Nz(X);return new Sz(X)}class kz extends u{static[D]="PgRealBuilder";constructor(W,$){super(W,"number","PgReal");this.config.length=$}build(W){return new jz(W,this.config)}}class jz extends f{static[D]="PgReal";constructor(W,$){super(W,$)}getSQLType(){return"real"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number.parseFloat(W);return W}}function Iz(W){return new kz(W??"")}class fz extends u{static[D]="PgSerialBuilder";constructor(W){super(W,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new Pz(W,this.config)}}class Pz extends f{static[D]="PgSerial";getSQLType(){return"serial"}}function xz(W){return new fz(W??"")}class vz extends f2{static[D]="PgSmallIntBuilder";constructor(W){super(W,"number","PgSmallInt")}build(W){return new bz(W,this.config)}}class bz extends f{static[D]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number(W);return W}}function yz(W){return new vz(W??"")}class hz extends u{static[D]="PgSmallSerialBuilder";constructor(W){super(W,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new gz(W,this.config)}}class gz extends f{static[D]="PgSmallSerial";getSQLType(){return"smallserial"}}function mz(W){return new hz(W??"")}class pz extends u{static[D]="PgTextBuilder";constructor(W,$){super(W,"string","PgText");this.config.enumValues=$.enum}build(W){return new uz(W,this.config)}}class uz extends f{static[D]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function cz(W,$={}){let{name:X,config:Y}=V0(W,$);return new pz(X,Y)}class dz extends G2{constructor(W,$,X){super(W,"string","PgTime");this.withTimezone=$,this.precision=X,this.config.withTimezone=$,this.config.precision=X}static[D]="PgTimeBuilder";build(W){return new AY(W,this.config)}}class AY extends f{static[D]="PgTime";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function lz(W,$={}){let{name:X,config:Y}=V0(W,$);return new dz(X,Y.withTimezone??!1,Y.precision)}class oz extends G2{static[D]="PgTimestampBuilder";constructor(W,$,X){super(W,"date","PgTimestamp");this.config.withTimezone=$,this.config.precision=X}build(W){return new EY(W,this.config)}}class EY extends f{static[D]="PgTimestamp";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(W)=>{return new Date(this.withTimezone?W:W+"+0000")};mapToDriverValue=(W)=>{return W.toISOString()}}class iz extends G2{static[D]="PgTimestampStringBuilder";constructor(W,$,X){super(W,"string","PgTimestampString");this.config.withTimezone=$,this.config.precision=X}build(W){return new LY(W,this.config)}}class LY extends f{static[D]="PgTimestampString";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function NW(W,$={}){let{name:X,config:Y}=V0(W,$);if(Y?.mode==="string")return new iz(X,Y.withTimezone??!1,Y.precision);return new oz(X,Y?.withTimezone??!1,Y?.precision)}class nz extends u{static[D]="PgUUIDBuilder";constructor(W){super(W,"string","PgUUID")}defaultRandom(){return this.default(M`gen_random_uuid()`)}build(W){return new BY(W,this.config)}}class BY extends f{static[D]="PgUUID";getSQLType(){return"uuid"}}function zW(W){return new nz(W??"")}class rz extends u{static[D]="PgVarcharBuilder";constructor(W,$){super(W,"string","PgVarchar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new tz(W,this.config)}}class tz extends f{static[D]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function j1(W,$={}){let{name:X,config:Y}=V0(W,$);return new rz(X,Y)}class az extends u{static[D]="PgBinaryVectorBuilder";constructor(W,$){super(W,"string","PgBinaryVector");this.config.dimensions=$.dimensions}build(W){return new sz(W,this.config)}}class sz extends f{static[D]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function ez(W,$){let{name:X,config:Y}=V0(W,$);return new az(X,Y)}class WF extends u{static[D]="PgHalfVectorBuilder";constructor(W,$){super(W,"array","PgHalfVector");this.config.dimensions=$.dimensions}build(W){return new $F(W,this.config)}}class $F extends f{static[D]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){return W.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function XF(W,$){let{name:X,config:Y}=V0(W,$);return new WF(X,Y)}class YF extends u{static[D]="PgSparseVectorBuilder";constructor(W,$){super(W,"string","PgSparseVector");this.config.dimensions=$.dimensions}build(W){return new JF(W,this.config)}}class JF extends f{static[D]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function GF(W,$){let{name:X,config:Y}=V0(W,$);return new YF(X,Y)}class HF extends u{static[D]="PgVectorBuilder";constructor(W,$){super(W,"array","PgVector");this.config.dimensions=$.dimensions}build(W){return new QF(W,this.config)}}class QF extends f{static[D]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){return W.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function zF(W,$){let{name:X,config:Y}=V0(W,$);return new HF(X,Y)}function FF(){return{bigint:EQ,bigserial:ZQ,boolean:T6,char:jQ,cidr:PQ,customType:bQ,date:gQ,doublePrecision:uQ,inet:lQ,integer:U6,interval:tQ,json:sQ,jsonb:Wz,line:Gz,macaddr:zz,macaddr8:Uz,numeric:Oz,point:Bz,geometry:Cz,real:Iz,serial:xz,smallint:yz,smallserial:mz,text:cz,time:lz,timestamp:NW,uuid:zW,varchar:j1,bit:ez,halfvec:XF,sparsevec:GF,vector:zF}}var aJ=Symbol.for("drizzle:PgInlineForeignKeys"),TF=Symbol.for("drizzle:EnableRLS");class M1 extends y{static[D]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:aJ,EnableRLS:TF});[aJ]=[];[TF]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}function FO(W,$,X,Y,J=W){let G=new M1(W,Y,J),H=typeof $==="function"?$(FF()):$,Q=Object.fromEntries(Object.entries(H).map(([T,U])=>{let _=U;_.setName(T);let V=_.build(G);return G[aJ].push(..._.buildForeignKeys(V,G)),[T,V]})),z=Object.fromEntries(Object.entries(H).map(([T,U])=>{let _=U;_.setName(T);let V=_.buildExtraConfigColumn(G);return[T,V]})),F=Object.assign(G,Q);if(F[y.Symbol.Columns]=Q,F[y.Symbol.ExtraConfigColumns]=z,X)F[M1.Symbol.ExtraConfigBuilder]=X;return Object.assign(F,{enableRLS:()=>{return F[M1.Symbol.EnableRLS]=!0,F}})}var P2=(W,$,X)=>{return FO(W,$,X,void 0)};function UF(...W){if(W[0].columns)return new w6(W[0].columns,W[0].name);return new w6(W)}class w6{static[D]="PgPrimaryKeyBuilder";columns;name;constructor(W,$){this.columns=W,this.name=$}build(W){return new wF(W,this.columns,this.name)}}class wF{constructor(W,$,X){this.table=W,this.columns=$,this.name=X}static[D]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[M1.Symbol.Name]}_${this.columns.map((W)=>W.name).join("_")}_pk`}}function g1(W,$){if(zQ($)&&!dJ(W)&&!E(W,s1)&&!E(W,I2)&&!E(W,q0)&&!E(W,y)&&!E(W,h1))return new s1(W,$);return W}var RY=(W,$)=>{return M`${W} = ${g1($,W)}`},_F=(W,$)=>{return M`${W} <> ${g1($,W)}`};function _6(...W){let $=W.filter((X)=>X!==void 0);if($.length===0)return;if($.length===1)return new g($);return new g([new Q1("("),M.join($,new Q1(" and ")),new Q1(")")])}function DF(...W){let $=W.filter((X)=>X!==void 0);if($.length===0)return;if($.length===1)return new g($);return new g([new Q1("("),M.join($,new Q1(" or ")),new Q1(")")])}function MF(W){return M`not ${W}`}var NY=(W,$)=>{return M`${W} > ${g1($,W)}`},VF=(W,$)=>{return M`${W} >= ${g1($,W)}`},OF=(W,$)=>{return M`${W} < ${g1($,W)}`},KF=(W,$)=>{return M`${W} <= ${g1($,W)}`};function AF(W,$){if(Array.isArray($)){if($.length===0)return M`false`;return M`${W} in ${$.map((X)=>g1(X,W))}`}return M`${W} in ${g1($,W)}`}function EF(W,$){if(Array.isArray($)){if($.length===0)return M`true`;return M`${W} not in ${$.map((X)=>g1(X,W))}`}return M`${W} not in ${g1($,W)}`}function LF(W){return M`${W} is null`}function BF(W){return M`${W} is not null`}function RF(W){return M`exists ${W}`}function NF(W){return M`not exists ${W}`}function ZF(W,$,X){return M`${W} between ${g1($,W)} and ${g1(X,W)}`}function SF(W,$,X){return M`${W} not between ${g1($,W)} and ${g1(X,W)}`}function qF(W,$){return M`${W} like ${$}`}function CF(W,$){return M`${W} not like ${$}`}function kF(W,$){return M`${W} ilike ${$}`}function jF(W,$){return M`${W} not ilike ${$}`}function IF(W){return M`${W} asc`}function fF(W){return M`${W} desc`}class sJ{constructor(W,$,X){this.sourceTable=W,this.referencedTable=$,this.relationName=X,this.referencedTableName=$[y.Symbol.Name]}static[D]="Relation";referencedTableName;fieldName}class PF{constructor(W,$){this.table=W,this.config=$}static[D]="Relations"}class x2 extends sJ{constructor(W,$,X,Y){super(W,$,X?.relationName);this.config=X,this.isNullable=Y}static[D]="One";withFieldName(W){let $=new x2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=W,$}}class D6 extends sJ{constructor(W,$,X){super(W,$,X?.relationName);this.config=X}static[D]="Many";withFieldName(W){let $=new D6(this.sourceTable,this.referencedTable,this.config);return $.fieldName=W,$}}function xF(){return{and:_6,between:ZF,eq:RY,exists:RF,gt:NY,gte:VF,ilike:kF,inArray:AF,isNull:LF,isNotNull:BF,like:qF,lt:OF,lte:KF,ne:_F,not:MF,notBetween:SF,notExists:NF,notLike:CF,notIlike:jF,notInArray:EF,or:DF,sql:M}}function vF(){return{sql:M,asc:IF,desc:fF}}function bF(W,$){if(Object.keys(W).length===1&&"default"in W&&!E(W.default,y))W=W.default;let X={},Y={},J={};for(let[G,H]of Object.entries(W))if(E(H,y)){let Q=V8(H),z=Y[Q];X[Q]=G,J[G]={tsName:G,dbName:H[y.Symbol.Name],schema:H[y.Symbol.Schema],columns:H[y.Symbol.Columns],relations:z?.relations??{},primaryKey:z?.primaryKey??[]};for(let T of Object.values(H[y.Symbol.Columns]))if(T.primary)J[G].primaryKey.push(T);let F=H[y.Symbol.ExtraConfigBuilder]?.(H[y.Symbol.ExtraConfigColumns]);if(F){for(let T of Object.values(F))if(E(T,w6))J[G].primaryKey.push(...T.columns)}}else if(E(H,PF)){let Q=V8(H.table),z=X[Q],F=H.config($(H.table)),T;for(let[U,_]of Object.entries(F))if(z){let V=J[z];if(V.relations[U]=_,T)V.primaryKey.push(...T)}else{if(!(Q in Y))Y[Q]={relations:{},primaryKey:T};Y[Q].relations[U]=_}}return{tables:J,tableNamesMap:X}}function TO(W){return function $(X,Y){return new x2(W,X,Y,Y?.fields.reduce((J,G)=>J&&G.notNull,!0)??!1)}}function UO(W){return function $(X,Y){return new D6(W,X,Y)}}function yF(W,$,X){if(E(X,x2)&&X.config)return{fields:X.config.fields,references:X.config.references};let Y=$[V8(X.referencedTable)];if(!Y)throw new Error(`Table "${X.referencedTable[y.Symbol.Name]}" not found in schema`);let J=W[Y];if(!J)throw new Error(`Table "${Y}" not found in schema`);let G=X.sourceTable,H=$[V8(G)];if(!H)throw new Error(`Table "${G[y.Symbol.Name]}" not found in schema`);let Q=[];for(let z of Object.values(J.relations))if(X.relationName&&X!==z&&z.relationName===X.relationName||!X.relationName&&z.referencedTable===X.sourceTable)Q.push(z);if(Q.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${Y}"`):new Error(`There are multiple relations between "${Y}" and "${X.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(Q[0]&&E(Q[0],x2)&&Q[0].config)return{fields:Q[0].config.references,references:Q[0].config.fields};throw new Error(`There is not enough information to infer relation "${H}.${X.fieldName}"`)}function hF(W){return{one:TO(W),many:UO(W)}}function ZY(W,$,X,Y,J=(G)=>G){let G={};for(let[H,Q]of Y.entries())if(Q.isJson){let z=$.relations[Q.tsKey],F=X[H],T=typeof F==="string"?JSON.parse(F):F;G[Q.tsKey]=E(z,x2)?T&&ZY(W,W[Q.relationTableTsKey],T,Q.selection,J):T.map((U)=>ZY(W,W[Q.relationTableTsKey],U,Q.selection,J))}else{let z=J(X[H]),F=Q.field,T;if(E(F,q0))T=F;else if(E(F,g))T=F.decoder;else T=F.sql.decoder;G[Q.tsKey]=z===null?null:T.mapFromDriverValue(z)}return G}import WB from"path";import vO from"os";import bO from"fs";var SY=new Map,eJ=new Map,W5=Symbol("OriginError"),M$={};class FW extends Promise{constructor(W,$,X,Y,J={}){let G,H;super((Q,z)=>{G=Q,H=z});this.tagged=Array.isArray(W.raw),this.strings=W,this.args=$,this.handler=X,this.canceller=Y,this.options=J,this.state=null,this.statement=null,this.resolve=(Q)=>(this.active=!1,G(Q)),this.reject=(Q)=>(this.active=!1,H(Q)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[W5]=this.handler.debug?new Error:this.tagged&&wO(this.strings)}get origin(){return(this.handler.debug?this[W5].stack:this.tagged&&eJ.has(this.strings)?eJ.get(this.strings):eJ.set(this.strings,this[W5].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(W=1,$){if(this.options.simple=!1,typeof W==="function")$=W,W=1;if(this.cursorRows=W,typeof $==="function")return this.cursorFn=$,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let Y=new Promise((J,G)=>{this.cursorFn=(H)=>{return J({value:H,done:!1}),new Promise((Q)=>X=Q)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=(H)=>(this.active=!1,G(H))});return this.execute(),Y},return(){return X&&X(M$),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(W){return this.forEachFn=W,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 wO(W){if(SY.has(W))return SY.get(W);let $=Error.stackTraceLimit;return Error.stackTraceLimit=4,SY.set(W,new Error),Error.stackTraceLimit=$,SY.get(W)}class V$ extends Error{constructor(W){super(W.message);this.name=this.constructor.name,Object.assign(this,W)}}var a0={connection:gF,postgres:mF,generic:pF,notSupported:uF};function gF(W,$,X){let{host:Y,port:J}=X||$,G=Object.assign(new Error("write "+W+" "+($.path||Y+":"+J)),{code:W,errno:W,address:$.path||Y},$.path?{}:{port:J});return Error.captureStackTrace(G,gF),G}function mF(W){let $=new V$(W);return Error.captureStackTrace($,mF),$}function pF(W,$){let X=Object.assign(new Error(W+": "+$),{code:W});return Error.captureStackTrace(X,pF),X}function uF(W){let $=Object.assign(new Error(W+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:W});return Error.captureStackTrace($,uF),$}var _O={string:{to:25,from:null,serialize:(W)=>""+W},number:{to:0,from:[21,23,26,700,701],serialize:(W)=>""+W,parse:(W)=>+W},json:{to:114,from:[114,3802],serialize:(W)=>JSON.stringify(W),parse:(W)=>JSON.parse(W)},boolean:{to:16,from:16,serialize:(W)=>W===!0?"t":"f",parse:(W)=>W==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(W)=>(W instanceof Date?W:new Date(W)).toISOString(),parse:(W)=>new Date(W)},bytea:{to:17,from:17,serialize:(W)=>"\\x"+Buffer.from(W).toString("hex"),parse:(W)=>Buffer.from(W.slice(2),"hex")}};class kY{then(){$5()}catch(){$5()}finally(){$5()}}class K6 extends kY{constructor(W){super();this.value=fY(W)}}class pW extends kY{constructor(W,$,X){super();this.value=W,this.type=$,this.array=X}}class jY extends kY{constructor(W,$){super();this.first=W,this.rest=$}build(W,$,X,Y){let J=DO.map(([G,H])=>({fn:H,i:W.search(G)})).sort((G,H)=>G.i-H.i).pop();return J.i===-1?H5(this.first,Y):J.fn(this.first,this.rest,$,X,Y)}}function IY(W,$,X,Y){let J=W instanceof pW?W.value:W;if(J===void 0){if(W instanceof pW?W.value=Y.transform.undefined:J=W=Y.transform.undefined,J===void 0)throw a0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(W instanceof pW?($.push(W.value),W.array?W.array[W.type||CY(W.value)]||W.type||oF(W.value):W.type):($.push(W),CY(W)))}var dF=nF(_O);function J5(W,$,X,Y,J,G){for(let H=1;H<W.strings.length;H++)$+=G5($,X,Y,J,G)+W.strings[H],X=W.args[H];return $}function G5(W,$,X,Y,J){return $ instanceof jY?$.build(W,X,Y,J):$ instanceof FW?Y5($,X,Y,J):$ instanceof K6?$.value:$&&$[0]instanceof FW?$.reduce((G,H)=>G+" "+Y5(H,X,Y,J),""):IY($,X,Y,J)}function Y5(W,$,X,Y){return W.fragment=!0,J5(W,W.strings[0],W.args[0],$,X,Y)}function lF(W,$,X,Y,J){return W.map((G)=>"("+Y.map((H)=>G5("values",G[H],$,X,J)).join(",")+")").join(",")}function cF(W,$,X,Y,J){let G=Array.isArray(W[0]),H=$.length?$.flat():Object.keys(G?W[0]:W);return lF(G?W:[W],X,Y,H,J)}function qY(W,$,X,Y,J){if(typeof W==="string"&&(W=[W].concat($)),Array.isArray(W))return H5(W,J);let G;return($.length?$.flat():Object.keys(W)).map((Q)=>{return G=W[Q],(G instanceof FW?Y5(G,X,Y,J):G instanceof K6?G.value:IY(G,X,Y,J))+" as "+fY(J.transform.column.to?J.transform.column.to(Q):Q)}).join(",")}var DO=Object.entries({values:cF,in:(...W)=>{let $=cF(...W);return $==="()"?"(null)":$},select:qY,as:qY,returning:qY,"\\(":qY,update(W,$,X,Y,J){return($.length?$.flat():Object.keys(W)).map((G)=>fY(J.transform.column.to?J.transform.column.to(G):G)+"="+G5("values",W[G],X,Y,J))},insert(W,$,X,Y,J){let G=$.length?$.flat():Object.keys(Array.isArray(W)?W[0]:W);return"("+H5(G,J)+")values"+lF(Array.isArray(W)?W:[W],X,Y,G,J)}}).map(([W,$])=>[new RegExp("((?:^|[\\s(])"+W+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),$]);function $5(){throw a0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:MO,parsers:VO}=dF;function oF(W){if(Array.isArray(W))return oF(W[0]);return typeof W==="string"?1009:0}var iF=function(W){let $=nF(W||{});return{serializers:Object.assign({},MO,$.serializers),parsers:Object.assign({},VO,$.parsers)}};function nF(W){return Object.keys(W).reduce(($,X)=>{if(W[X].from&&[].concat(W[X].from).forEach((Y)=>$.parsers[Y]=W[X].parse),W[X].serialize)$.serializers[W[X].to]=W[X].serialize,W[X].from&&[].concat(W[X].from).forEach((Y)=>$.serializers[Y]=W[X].serialize);return $},{parsers:{},serializers:{}})}function H5(W,{transform:{column:$}}){return W.map((X)=>fY($.to?$.to(X):X)).join(",")}var fY=function W($){return'"'+$.replace(/"/g,'""').replace(/\./g,'"."')+'"'},CY=function W($){return $ instanceof pW?$.type:$ instanceof Date?1184:$ instanceof Uint8Array?17:$===!0||$===!1?16:typeof $==="bigint"?20:Array.isArray($)?W($[0]):0},OO=/\\/g,KO=/"/g;function AO(W){return W.replace(OO,"\\\\").replace(KO,"\\\"")}var rF=function W($,X,Y,J){if(Array.isArray($)===!1)return $;if(!$.length)return"{}";let G=$[0],H=J===1020?";":",";if(Array.isArray(G)&&!G.type)return"{"+$.map((Q)=>W(Q,X,Y,J)).join(H)+"}";return"{"+$.map((Q)=>{if(Q===void 0){if(Q=Y.transform.undefined,Q===void 0)throw a0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Q===null?"null":'"'+AO(X?X(Q.type?Q.value:Q):""+Q)+'"'}).join(H)+"}"},X5={i:0,char:null,str:"",quoted:!1,last:0},tF=function W($,X,Y){return X5.i=X5.last=0,aF(X5,$,X,Y)};function aF(W,$,X,Y){let J=[],G=Y===1020?";":",";for(;W.i<$.length;W.i++){if(W.char=$[W.i],W.quoted)if(W.char==="\\")W.str+=$[++W.i];else if(W.char==='"')J.push(X?X(W.str):W.str),W.str="",W.quoted=$[W.i+1]==='"',W.last=W.i+2;else W.str+=W.char;else if(W.char==='"')W.quoted=!0;else if(W.char==="{")W.last=++W.i,J.push(aF(W,$,X,Y));else if(W.char==="}"){W.quoted=!1,W.last<W.i&&J.push(X?X($.slice(W.last,W.i)):$.slice(W.last,W.i)),W.last=W.i+1;break}else if(W.char===G&&W.p!=="}"&&W.p!=='"')J.push(X?X($.slice(W.last,W.i)):$.slice(W.last,W.i)),W.last=W.i+1;W.p=W.char}return W.last<W.i&&J.push(X?X($.slice(W.last,W.i+1)):$.slice(W.last,W.i+1)),J}var O8=(W)=>{let $=W[0];for(let X=1;X<W.length;X++)$+=W[X]==="_"?W[++X].toUpperCase():W[X];return $},K8=(W)=>{let $=W[0].toUpperCase();for(let X=1;X<W.length;X++)$+=W[X]==="_"?W[++X].toUpperCase():W[X];return $},A8=(W)=>W.replace(/_/g,"-"),M6=(W)=>W.replace(/([A-Z])/g,"_$1").toLowerCase(),V6=(W)=>(W.slice(0,1)+W.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),O6=(W)=>W.replace(/-/g,"_");function Q5(W){return function $(X,Y){return typeof X==="object"&&X!==null&&(Y.type===114||Y.type===3802)?Array.isArray(X)?X.map((J)=>$(J,Y)):Object.entries(X).reduce((J,[G,H])=>Object.assign(J,{[W(G)]:$(H,Y)}),{}):X}}O8.column={from:O8};O8.value={from:Q5(O8)};M6.column={to:M6};var z5={...O8};z5.column.to=M6;K8.column={from:K8};K8.value={from:Q5(K8)};V6.column={to:V6};var F5={...K8};F5.column.to=V6;A8.column={from:A8};A8.value={from:Q5(A8)};O6.column={to:O6};var T5={...A8};T5.column.to=O6;import sF from"net";import RO from"tls";import A6 from"crypto";import U5 from"stream";import{performance as eF}from"perf_hooks";class E8 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 e1=EO;function EO(W=[]){let $=W.slice(),X=0;return{get length(){return $.length-X},remove:(Y)=>{let J=$.indexOf(Y);return J===-1?null:($.splice(J,1),Y)},push:(Y)=>($.push(Y),Y),shift:()=>{let Y=$[X++];if(X===$.length)X=0,$=[];else $[X-1]=void 0;return Y}}}var B1=Buffer.allocUnsafe(256),LO="BCcDdEFfHPpQSX".split("").reduce((W,$)=>{let X=$.charCodeAt(0);return W[$]=()=>{return B1[0]=X,Z0.i=5,Z0},W},{}),Z0=Object.assign(BO,LO,{N:String.fromCharCode(0),i:0,inc(W){return Z0.i+=W,Z0},str(W){let $=Buffer.byteLength(W);return PY($),Z0.i+=B1.write(W,Z0.i,$,"utf8"),Z0},i16(W){return PY(2),B1.writeUInt16BE(W,Z0.i),Z0.i+=2,Z0},i32(W,$){if($||$===0)return B1.writeUInt32BE(W,$),Z0;return PY(4),B1.writeUInt32BE(W,Z0.i),Z0.i+=4,Z0},z(W){return PY(W),B1.fill(0,Z0.i,Z0.i+W),Z0.i+=W,Z0},raw(W){return B1=Buffer.concat([B1.subarray(0,Z0.i),W]),Z0.i=B1.length,Z0},end(W=1){B1.writeUInt32BE(Z0.i-W,W);let $=B1.subarray(0,Z0.i);return Z0.i=0,B1=Buffer.allocUnsafe(256),$}}),n=Z0;function PY(W){if(B1.length-Z0.i<W){let $=B1,X=$.length;B1=Buffer.allocUnsafe(X+(X>>1)+W),$.copy(B1)}}function BO(){return Z0.i=0,Z0}var D5=XT,NO=1,v2=n().S().end(),WT=n().H().end(),ZO=n().i32(8).i32(80877103).end(8),SO=Buffer.concat([n().E().str(n.N).i32(0).end(),v2]),qO=n().D().str("S").str(n.N).end(),O$=()=>{},CO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),kO={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 XT(W,$={},{onopen:X=O$,onend:Y=O$,onclose:J=O$}={}){let{ssl:G,max:H,user:Q,host:z,port:F,database:T,parsers:U,transform:_,onnotice:V,onnotify:K,onparameter:B,max_pipeline:I,keep_alive:C,backoff:R,target_session_attrs:q}=W,m=e1(),c=NO++,v={pid:null,secret:null},h=_5(B9,W.idle_timeout),w0=_5(B9,W.max_lifetime),p0=_5(p_,W.connect_timeout),L=null,M0,W0=new E8,_0=Buffer.alloc(0),e0=W.fetch_types,V1={},DW={},k8=Math.random().toString(36).slice(2),j=1,s=0,R0=0,m0=0,W1=0,T0=0,j0=0,r0=0,u0=null,b0=null,O1=!1,I0=null,MW=null,K1=null,O2=null,$1=null,y0=null,VW=null,jW=null,x=null,m$=null,A1={queue:$.closed,idleTimer:h,connect(w){K1=w||!0,GG()},terminate:u$,execute:p$,cancel:y_,end:B9,count:0,id:c};return $.closed&&$.closed.push(A1),A1;async function b_(){let w;try{w=W.socket?await Promise.resolve(W.socket(W)):new sF.Socket}catch(O){I8(O);return}return w.on("error",I8),w.on("close",HG),w.on("drain",YG),w}async function y_({pid:w,secret:O},t,L0){try{M0=n().i32(16).i32(80877102).i32(w).i32(O).end(16),await JG(),L.once("error",L0),L.once("close",t)}catch(l0){L0(l0)}}function p$(w){if(O1)return $X(w,a0.connection("CONNECTION_DESTROYED",W));if(w.cancelled)return;try{return w.state=v,x?m.push(w):(x=w,x.active=!0),m_(w),_1(h_(w))&&!w.describeFirst&&!w.cursorFn&&m.length<I&&(!w.options.onexecute||w.options.onexecute(A1))}catch(O){return m.length===0&&_1(v2),IW(O),!0}}function h_(w){if(w.parameters.length>=65534)throw a0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return w.options.simple?n().Q().str(w.statement.string+n.N).end():w.describeFirst?Buffer.concat([WG(w),WT]):w.prepare?w.prepared?WX(w):Buffer.concat([WG(w),WX(w)]):g_(w)}function WG(w){return Buffer.concat([zG(w.statement.string,w.parameters,w.statement.types,w.statement.name),ZD("S",w.statement.name)])}function WX(w){return Buffer.concat([ND(w.parameters,w.statement.types,w.statement.name,w.cursorName),w.cursorFn?FG("",w.cursorRows):SO])}function g_(w){return Buffer.concat([zG(w.statement.string,w.parameters,w.statement.types),qO,WX(w)])}function m_(w){let O=[],t=[],L0=J5(w,w.strings[0],w.args[0],O,t,W);!w.tagged&&w.args.forEach((l0)=>IY(l0,O,t,W)),w.prepare=W.prepare&&("prepare"in w.options?w.options.prepare:!0),w.string=L0,w.signature=w.prepare&&t+L0,w.onlyDescribe&&delete DW[w.signature],w.parameters=w.parameters||O,w.prepared=w.prepare&&w.signature in DW,w.describeFirst=w.onlyDescribe||O.length&&!w.prepared,w.statement=w.prepared?DW[w.signature]:{string:L0,types:t,name:w.prepare?k8+j++:""},typeof W.debug==="function"&&W.debug(c,L0,O,t)}function _1(w,O){if(y0=y0?Buffer.concat([y0,w]):Buffer.from(w),O||y0.length>=1024)return $G(O);return b0===null&&(b0=setImmediate($G)),!0}function $G(w){let O=L.write(y0,w);return b0!==null&&clearImmediate(b0),y0=b0=null,O}function p_(){IW(a0.connection("CONNECT_TIMEOUT",W,L)),L.destroy()}async function XG(){if(_1(ZO),!await new Promise((O)=>L.once("data",(t)=>O(t[0]===83)))&&G==="prefer")return j8();L.removeAllListeners(),L=RO.connect({socket:L,servername:sF.isIP(L.host)?void 0:L.host,...G==="require"||G==="allow"||G==="prefer"?{rejectUnauthorized:!1}:G==="verify-full"?{}:typeof G==="object"?G:{}}),L.on("secureConnect",j8),L.on("error",I8),L.on("close",HG),L.on("drain",YG)}function YG(){!x&&X(A1)}function L9(w){if(I0){if(I0.push(w),R0-=w.length,R0>=0)return}_0=I0?Buffer.concat(I0,T0-R0):_0.length===0?w:Buffer.concat([_0,w],_0.length+w.length);while(_0.length>4){if(T0=_0.readUInt32BE(1),T0>=_0.length){R0=T0-_0.length,I0=[_0];break}try{u_(_0.subarray(0,T0+1))}catch(O){x&&(x.cursorFn||x.describeFirst)&&_1(v2),IW(O)}_0=_0.subarray(T0+1),R0=0,I0=null}}async function JG(){if(O1=!1,V1={},L||(L=await b_()),!L)return;if(p0.start(),W.socket)return G?XG():j8();if(L.on("connect",G?XG:j8),W.path)return L.connect(W.path);L.ssl=G,L.connect(F[m0],z[m0]),L.host=z[m0],L.port=F[m0],m0=(m0+1)%F.length}function GG(){setTimeout(JG,s?s+j0-eF.now():0)}function j8(){try{DW={},e0=W.fetch_types,k8=Math.random().toString(36).slice(2),j=1,w0.start(),L.on("data",L9),C&&L.setKeepAlive&&L.setKeepAlive(!0,1000*C);let w=qD();_1(w)}catch(w){I8(w)}}function I8(w){if(A1.queue===$.connecting&&W.host[W1+1])return;IW(w);while(m.length)$X(m.shift(),w)}function IW(w){$1&&($1.destroy(w),$1=null),x&&$X(x,w),K1&&($X(K1,w),K1=null)}function $X(w,O){"query"in O||"parameters"in O||Object.defineProperties(O,{stack:{value:O.stack+w.origin.replace(/.*\n/,`
57
- `),enumerable:W.debug},query:{value:w.string,enumerable:W.debug},parameters:{value:w.parameters,enumerable:W.debug},args:{value:w.args,enumerable:W.debug},types:{value:w.statement&&w.statement.types,enumerable:W.debug}}),w.reject(O)}function B9(){return O2||(!A1.reserved&&Y(A1),!A1.reserved&&!K1&&!x&&m.length===0?(u$(),new Promise((w)=>L&&L.readyState!=="closed"?L.once("close",w):w())):O2=new Promise((w)=>VW=w))}function u$(){if(O1=!0,$1||x||K1||m.length)I8(a0.connection("CONNECTION_DESTROYED",W));if(clearImmediate(b0),L)L.removeListener("data",L9),L.removeListener("connect",j8),L.readyState==="open"&&L.end(n().X().end());VW&&(VW(),O2=VW=null)}async function HG(w){if(_0=Buffer.alloc(0),R0=0,I0=null,clearImmediate(b0),L.removeListener("data",L9),L.removeListener("connect",j8),h.cancel(),w0.cancel(),p0.cancel(),L.removeAllListeners(),L=null,K1)return GG();!w&&(x||m.length)&&I8(a0.connection("CONNECTION_CLOSED",W,L)),s=eF.now(),w&&W.shared.retries++,j0=(typeof R==="function"?R(W.shared.retries):R)*1000,J(A1,a0.connection("CONNECTION_CLOSED",W,L))}function u_(w,O=w[0]){(O===68?c_:O===100?VD:O===65?TD:O===83?d_:O===90?l_:O===67?o_:O===50?QG:O===49?i_:O===116?n_:O===84?r_:O===82?t_:O===110?XD:O===75?YD:O===69?zD:O===115?UD:O===51?wD:O===71?_D:O===78?KD:O===72?DD:O===99?OD:O===73?AD:O===86?ED:O===118?LD:O===87?MD:BD)(w)}function c_(w){let O=7,t,L0,l0,E1=x.isRaw?new Array(x.statement.columns.length):{};for(let Z1=0;Z1<x.statement.columns.length;Z1++)L0=x.statement.columns[Z1],t=w.readInt32BE(O),O+=4,l0=t===-1?null:x.isRaw===!0?w.subarray(O,O+=t):L0.parser===void 0?w.toString("utf8",O,O+=t):L0.parser.array===!0?L0.parser(w.toString("utf8",O+1,O+=t)):L0.parser(w.toString("utf8",O,O+=t)),x.isRaw?E1[Z1]=x.isRaw===!0?l0:_.value.from?_.value.from(l0,L0):l0:E1[L0.name]=_.value.from?_.value.from(l0,L0):l0;x.forEachFn?x.forEachFn(_.row.from?_.row.from(E1):E1,W0):W0[r0++]=_.row.from?_.row.from(E1):E1}function d_(w){let[O,t]=w.toString("utf8",5,w.length-1).split(n.N);if(V1[O]=t,W.parameters[O]!==t)W.parameters[O]=t,B&&B(O,t)}function l_(w){if(x&&x.options.simple&&x.resolve(MW||W0),x=MW=null,W0=new E8,p0.cancel(),K1){if(q){if(!V1.in_hot_standby||!V1.default_transaction_read_only)return QD();else if(HD(q,V1))return u$()}if(e0)return K1===!0&&(K1=null),JD();K1!==!0&&p$(K1),W.shared.retries=W1=0,K1=null;return}while(m.length&&(x=m.shift())&&(x.active=!0,x.cancelled))XT(W).cancel(x.state,x.cancelled.resolve,x.cancelled.reject);if(x)return;A1.reserved?!A1.reserved.release&&w[5]===73?O2?u$():(A1.reserved=null,X(A1)):A1.reserved():O2?u$():X(A1)}function o_(w){r0=0;for(let O=w.length-1;O>0;O--){if(w[O]===32&&w[O+1]<58&&W0.count===null)W0.count=+w.toString("utf8",O+1,w.length-1);if(w[O-1]>=65){W0.command=w.toString("utf8",5,O),W0.state=v;break}}if(m$&&(m$(),m$=null),W0.command==="BEGIN"&&H!==1&&!A1.reserved)return IW(a0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(x.options.simple)return QG();if(x.cursorFn)W0.count&&x.cursorFn(W0),_1(v2);x.resolve(W0)}function i_(){x.parsing=!1}function QG(){!W0.statement&&(W0.statement=x.statement),W0.columns=x.statement.columns}function n_(w){let O=w.readUInt16BE(5);for(let t=0;t<O;++t)!x.statement.types[t]&&(x.statement.types[t]=w.readUInt32BE(7+t*4));x.prepare&&(DW[x.signature]=x.statement),x.describeFirst&&!x.onlyDescribe&&(_1(WX(x)),x.describeFirst=!1)}function r_(w){if(W0.command)MW=MW||[W0],MW.push(W0=new E8),W0.count=null,x.statement.columns=null;let O=w.readUInt16BE(5),t=7,L0;x.statement.columns=Array(O);for(let l0=0;l0<O;++l0){L0=t;while(w[t++]!==0);let E1=w.readUInt32BE(t),Z1=w.readUInt16BE(t+4),K2=w.readUInt32BE(t+6);x.statement.columns[l0]={name:_.column.from?_.column.from(w.toString("utf8",L0,t-1)):w.toString("utf8",L0,t-1),parser:U[K2],table:E1,number:Z1,type:K2},t+=18}if(W0.statement=x.statement,x.onlyDescribe)return x.resolve(x.statement),_1(v2)}async function t_(w,O=w.readUInt32BE(5)){(O===3?a_:O===5?s_:O===10?e_:O===11?WD:O===12?$D:O!==0?RD:O$)(w,O)}async function a_(){let w=await R9();_1(n().p().str(w).z(1).end())}async function s_(w){let O="md5"+await $T(Buffer.concat([Buffer.from(await $T(await R9()+Q)),w.subarray(9)]));_1(n().p().str(O).z(1).end())}async function e_(){jW=(await A6.randomBytes(18)).toString("base64"),n().p().str("SCRAM-SHA-256"+n.N);let w=n.i;_1(n.inc(4).str("n,,n=*,r="+jW).i32(n.i-w-4,w).end())}async function WD(w){let O=w.toString("utf8",9).split(",").reduce((Z1,K2)=>(Z1[K2[0]]=K2.slice(2),Z1),{}),t=await A6.pbkdf2Sync(await R9(),Buffer.from(O.s,"base64"),parseInt(O.i),32,"sha256"),L0=await xY(t,"Client Key"),l0="n=*,r="+jW+",r="+O.r+",s="+O.s+",i="+O.i+",c=biws,r="+O.r;u0=(await xY(await xY(t,"Server Key"),l0)).toString("base64");let E1="c=biws,r="+O.r+",p="+IO(L0,Buffer.from(await xY(await jO(L0),l0))).toString("base64");_1(n().p().str(E1).end())}function $D(w){if(w.toString("utf8",9).split(n.N,1)[0].slice(2)===u0)return;IW(a0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),L.destroy()}function R9(){return Promise.resolve(typeof W.pass==="function"?W.pass():W.pass)}function XD(){if(W0.statement=x.statement,W0.statement.columns=[],x.onlyDescribe)return x.resolve(x.statement),_1(v2)}function YD(w){v.pid=w.readUInt32BE(5),v.secret=w.readUInt32BE(9)}async function JD(){e0=!1,(await new FW([`
55
+ `);super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new $4(this),this.chat=new q2(this),this.embeddings=new X4(this),this.files=new _8(this),this.images=new T4(this),this.audio=new sW(this),this.moderations=new _4(this),this.models=new D8(this),this.fineTuning=new HW(this),this.graders=new U8(this),this.vectorStores=new QW(this),this.beta=new gW(this),this.batches=new Y8(this),this.uploads=new M8(this),this.responses=new V8(this),this.evals=new X2(this),this._options=J,this.apiKey=$,this.organization=X,this.project=Y}defaultQuery(){return this._options.defaultQuery}defaultHeaders(W){return{...super.defaultHeaders(W),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(W){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(W){return W5(W,{arrayFormat:"brackets"})}}cH=H0;H0.OpenAI=cH;H0.DEFAULT_TIMEOUT=600000;H0.OpenAIError=o;H0.APIError=t0;H0.APIConnectionError=s2;H0.APIConnectionTimeoutError=e2;H0.APIUserAbortError=G1;H0.NotFoundError=IX;H0.ConflictError=PX;H0.RateLimitError=xX;H0.BadRequestError=CX;H0.AuthenticationError=kX;H0.InternalServerError=bX;H0.PermissionDeniedError=jX;H0.UnprocessableEntityError=fX;H0.toFile=U5;H0.fileFromPath=qX;H0.Completions=$4;H0.Chat=q2;H0.ChatCompletionsPage=X8;H0.Embeddings=X4;H0.Files=_8;H0.FileObjectsPage=J4;H0.Images=T4;H0.Audio=sW;H0.Moderations=_4;H0.Models=D8;H0.ModelsPage=F4;H0.FineTuning=HW;H0.Graders=U8;H0.VectorStores=QW;H0.VectorStoresPage=D4;H0.VectorStoreSearchResponsesPage=V4;H0.Beta=gW;H0.Batches=Y8;H0.BatchesPage=o8;H0.Uploads=M8;H0.Responses=V8;H0.Evals=X2;H0.EvalListResponsesPage=G4;var dH=H0;function sM(W,...$){let[X,Y,G,J]=$,H=[{role:"user",content:j3(Y)},{role:"user",content:X}],Q=J.at(-1);if(Q)H.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(Q.response,null,2),"Here's the error message:",JSON.stringify(Q.error.issues,null,2)].join(`
56
+ `)});return{model:W,messages:H}}var a=1e6,lH={"gpt-4.1":{promptPricePerToken:2/a,promptPricePerTokenCached:0.5/a,completionPricePerToken:8/a},"gpt-4.1-mini":{promptPricePerToken:0.4/a,promptPricePerTokenCached:0.1/a,completionPricePerToken:1.6/a},"gpt-4.1-nano":{promptPricePerToken:0.1/a,promptPricePerTokenCached:0.025/a,completionPricePerToken:0.4/a},"gpt-4o":{promptPricePerToken:2.5/a,promptPricePerTokenCached:1.25/a,completionPricePerToken:10/a},"gpt-4o-mini":{promptPricePerToken:0.15/a,promptPricePerTokenCached:0.075/a,completionPricePerToken:0.6/a},o1:{promptPricePerToken:15/a,promptPricePerTokenCached:7.5/a,completionPricePerToken:60/a},"o1-mini":{promptPricePerToken:1.1/a,promptPricePerTokenCached:0.55/a,completionPricePerToken:4.4/a},o3:{promptPricePerToken:10/a,promptPricePerTokenCached:2.5/a,completionPricePerToken:40/a},"o3-mini":{promptPricePerToken:1.1/a,promptPricePerTokenCached:0.55/a,completionPricePerToken:4.4/a},"o4-mini":{promptPricePerToken:1.1/a,promptPricePerTokenCached:0.275/a,completionPricePerToken:4.4/a},"codex-mini-latest":{promptPricePerToken:1.5/a,promptPricePerTokenCached:0.375/a,completionPricePerToken:6/a},"chatgpt-4o-latest":{promptPricePerToken:5/a,promptPricePerTokenCached:5/a,completionPricePerToken:15/a},"gpt-4":{promptPricePerToken:30/a,promptPricePerTokenCached:30/a,completionPricePerToken:60/a},"gpt-4-turbo":{promptPricePerToken:10/a,promptPricePerTokenCached:10/a,completionPricePerToken:30/a},"gpt-3.5-turbo":{promptPricePerToken:0.5/a,promptPricePerTokenCached:0.5/a,completionPricePerToken:1.5/a},"gpt-4-32k":{promptPricePerToken:60/a,promptPricePerTokenCached:60/a,completionPricePerToken:120/a},"gpt-3.5-turbo-16k":{promptPricePerToken:3/a,promptPricePerTokenCached:3/a,completionPricePerToken:4/a}};function eM(W){let X=Object.keys(lH).filter((Y)=>W.startsWith(Y)).sort((Y,G)=>G.length-Y.length)[0];if(!X)return;return lH[X]}function WO(W){return async function $(X,Y){if(!W)throw new Error("This is a bug in safegen. OpenAI client not available to the json generator.");let G=await W.chat.completions.create({...X,stream:!1,response_format:{type:"json_object"}},Y),J=G.choices[0].message?.content,{usage:H}=G;if(J&&H){let Q=H.prompt_tokens,z=H.prompt_tokens_details?.cached_tokens??0,T=Q-z,F=H.completion_tokens,_=eM(X.model),w=0;if(_)w=Q*_.promptPricePerToken+T*(_.promptPricePerTokenCached??0)+F*_.completionPricePerToken;else console.warn(`No pricing facts found for model ${X.model}. Giving a price of 0.`);return{data:JSON.parse(J),usage:H,usdPrice:w}}if(!J&&!H)throw new Error("No content or usage found in completion");if(!J)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var oH=new Map,iH=class{usdBudget;usdMinimum;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;client;lastUsage;constructor({model:W,usdBudget:$,usdMinimum:X,apiKey:Y,cachingMode:G,cacheKey:J="openai-safegen",logger:H}){this.usdBudget=$,this.usdMinimum=X,this.squirrel=new l3(G);let Q=oH.get(Y);if(G!=="read"){if(!Q)Q=new dH({apiKey:Y,dangerouslyAllowBrowser:!1}),oH.set(Y,Q);this.client=Q}this.getUnknownJsonFromOpenAi=WO(this.client),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(J,this.getUnknownJsonFromOpenAi),this.from=k3(async(...z)=>{if(this.usdBudget<this.usdMinimum)return H?.warn("SafeGen budget exhausted"),z[1];let T=sM(W,...z),F=z[0],_=z[3],{data:w,usage:O,usdPrice:M}=await this.getUnknownJsonFromOpenAiSquirreled.for(`${F.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${_.length}`).get(T);return this.lastUsage=O,this.usdBudget-=M,w},H)}from};import{exec as zB}from"child_process";class JY{supported;constructor(W){this.supported=W}refine(W){for(let[$,X]of Object.entries(this.supported))try{if(X(W)===!0&&X!==Boolean)return{type:$,data:W}}catch(Y){try{if(W instanceof X)return{type:$,data:W}}catch(G){}}return null}}var $O=new JY({number:(W)=>typeof W==="number",string:(W)=>typeof W==="string",boolean:(W)=>typeof W==="boolean",null:(W)=>W===null});function XO(W){if(!W)return!1;return Object.getPrototypeOf(W)===Object.prototype}var YO=new JY({object:XO,array:(W)=>Array.isArray(W)}),GO=new JY({...$O.supported,...YO.supported}),nH=(W)=>{if(W===void 0)return"undefined";let $=GO.refine(W);if($)return $.type;return Object.getPrototypeOf(W).constructor.name};var D=Symbol.for("drizzle:entityKind"),_x=Symbol.for("drizzle:hasOwnEntityKind");function L(W,$){if(!W||typeof W!=="object")return!1;if(W instanceof $)return!0;if(!Object.prototype.hasOwnProperty.call($,D))throw new Error(`Class "${$.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 X=Object.getPrototypeOf(W).constructor;if(X)while(X){if(D in X&&X[D]===$[D])return!0;X=Object.getPrototypeOf(X)}return!1}class q0{constructor(W,$){this.table=W,this.config=$,this.name=$.name,this.keyAsName=$.keyAsName,this.notNull=$.notNull,this.default=$.default,this.defaultFn=$.defaultFn,this.onUpdateFn=$.onUpdateFn,this.hasDefault=$.hasDefault,this.primary=$.primaryKey,this.isUnique=$.isUnique,this.uniqueName=$.uniqueName,this.uniqueType=$.uniqueType,this.dataType=$.dataType,this.columnType=$.columnType,this.generated=$.generated,this.generatedIdentity=$.generatedIdentity}static[D]="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(W){return W}mapToDriverValue(W){return W}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class h5{static[D]="ColumnBuilder";config;constructor(W,$,X){this.config={name:W,keyAsName:W==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:$,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(W){return this.config.default=W,this.config.hasDefault=!0,this}$defaultFn(W){return this.config.defaultFn=W,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(W){return this.config.onUpdateFn=W,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(W){if(this.config.name!=="")return;this.config.name=W}}var NW=Symbol.for("drizzle:Name");class g5{static[D]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(W,$){if(this.reference=()=>{let{name:X,columns:Y,foreignColumns:G}=W();return{name:X,columns:Y,foreignTable:G[0].table,foreignColumns:G}},$)this._onUpdate=$.onUpdate,this._onDelete=$.onDelete}onUpdate(W){return this._onUpdate=W===void 0?"no action":W,this}onDelete(W){return this._onDelete=W===void 0?"no action":W,this}build(W){return new rH(W,this)}}class rH{constructor(W,$){this.table=W,this.reference=$.reference,this.onUpdate=$._onUpdate,this.onDelete=$._onDelete}static[D]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:W,columns:$,foreignColumns:X}=this.reference(),Y=$.map((H)=>H.name),G=X.map((H)=>H.name),J=[this.table[NW],...Y,X[0].table[NW],...G];return W??`${J.join("_")}_fk`}}function HY(W,...$){return W(...$)}function tH(W,$){return`${W[NW]}_${$.join("_")}_unique`}function aH(W,$,X){for(let Y=$;Y<W.length;Y++){let G=W[Y];if(G==="\\"){Y++;continue}if(G==='"')return[W.slice($,Y).replace(/\\/g,""),Y+1];if(X)continue;if(G===","||G==="}")return[W.slice($,Y).replace(/\\/g,""),Y]}return[W.slice($).replace(/\\/g,""),W.length]}function sH(W,$=0){let X=[],Y=$,G=!1;while(Y<W.length){let J=W[Y];if(J===","){if(G||Y===$)X.push("");G=!0,Y++;continue}if(G=!1,J==="\\"){Y+=2;continue}if(J==='"'){let[z,T]=aH(W,Y+1,!0);X.push(z),Y=T;continue}if(J==="}")return[X,Y+1];if(J==="{"){let[z,T]=sH(W,Y+1);X.push(z),Y=T;continue}let[H,Q]=aH(W,Y,!1);X.push(H),Y=Q}return[X,Y]}function eH(W){let[$]=sH(W,1);return $}function m5(W){return`{${W.map(($)=>{if(Array.isArray($))return m5($);if(typeof $==="string")return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${$}`}).join(",")}}`}class c extends h5{foreignKeyConfigs=[];static[D]="PgColumnBuilder";array(W){return new $Q(this.config.name,this,W)}references(W,$={}){return this.foreignKeyConfigs.push({ref:W,actions:$}),this}unique(W,$){return this.config.isUnique=!0,this.config.uniqueName=W,this.config.uniqueType=$?.nulls,this}generatedAlwaysAs(W){return this.config.generated={as:W,type:"always",mode:"stored"},this}buildForeignKeys(W,$){return this.foreignKeyConfigs.map(({ref:X,actions:Y})=>{return HY((G,J)=>{let H=new g5(()=>{let Q=G();return{columns:[W],foreignColumns:[Q]}});if(J.onUpdate)H.onUpdate(J.onUpdate);if(J.onDelete)H.onDelete(J.onDelete);return H.build($)},X,Y)})}buildExtraConfigColumn(W){return new WQ(W,this.config)}}class f extends q0{constructor(W,$){if(!$.uniqueName)$.uniqueName=tH(W,[$.name]);super(W,$);this.table=W}static[D]="PgColumn"}class WQ extends f{static[D]="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(W){return this.indexConfig.opClass=W,this}}class J6{static[D]="IndexedColumn";constructor(W,$,X,Y){this.name=W,this.keyAsName=$,this.type=X,this.indexConfig=Y}name;keyAsName;type;indexConfig}class $Q extends c{static[D]="PgArrayBuilder";constructor(W,$,X){super(W,"array","PgArray");this.config.baseBuilder=$,this.config.size=X}build(W){let $=this.config.baseBuilder.build(W);return new p5(W,this.config,$)}}class p5 extends f{constructor(W,$,X,Y){super(W,$);this.baseColumn=X,this.range=Y,this.size=$.size}size;static[D]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(W){if(typeof W==="string")W=eH(W);return W.map(($)=>this.baseColumn.mapFromDriverValue($))}mapToDriverValue(W,$=!1){let X=W.map((Y)=>Y===null?null:L(this.baseColumn,p5)?this.baseColumn.mapToDriverValue(Y,!0):this.baseColumn.mapToDriverValue(Y));if($)return X;return m5(X)}}class XQ extends c{static[D]="PgEnumObjectColumnBuilder";constructor(W,$){super(W,"string","PgEnumObjectColumn");this.config.enum=$}build(W){return new YQ(W,this.config)}}class YQ extends f{static[D]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var QY=Symbol.for("drizzle:isPgEnum");function GQ(W){return!!W&&typeof W==="function"&&QY in W&&W[QY]===!0}class JQ extends c{static[D]="PgEnumColumnBuilder";constructor(W,$){super(W,"string","PgEnumColumn");this.config.enum=$}build(W){return new HQ(W,this.config)}}class HQ extends f{static[D]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}function H6(W,$){return Array.isArray($)?JO(W,[...$],void 0):HO(W,$,void 0)}function JO(W,$,X){let Y=Object.assign((G)=>new JQ(G??"",Y),{enumName:W,enumValues:$,schema:X,[QY]:!0});return Y}function HO(W,$,X){let Y=Object.assign((G)=>new XQ(G??"",Y),{enumName:W,enumValues:Object.values($),schema:X,[QY]:!0});return Y}class H1{static[D]="Subquery";constructor(W,$,X,Y=!1){this._={brand:"Subquery",sql:W,selectedFields:$,alias:X,isWith:Y}}}class Q6 extends H1{static[D]="WithSubquery"}var QQ="0.43.1";var u5,c5,C0={startActiveSpan(W,$){if(!u5)return $();if(!c5)c5=u5.trace.getTracer("drizzle-orm",QQ);return HY((X,Y)=>Y.startActiveSpan(W,(G)=>{try{return $(G)}catch(J){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),u5,c5)}};var f0=Symbol.for("drizzle:ViewBaseConfig");var zY=Symbol.for("drizzle:Schema"),TY=Symbol.for("drizzle:Columns"),zQ=Symbol.for("drizzle:ExtraConfigColumns"),d5=Symbol.for("drizzle:OriginalName"),l5=Symbol.for("drizzle:BaseName"),z6=Symbol.for("drizzle:IsAlias"),TQ=Symbol.for("drizzle:ExtraConfigBuilder"),QO=Symbol.for("drizzle:IsDrizzleTable");class g{static[D]="Table";static Symbol={Name:NW,Schema:zY,OriginalName:d5,Columns:TY,ExtraConfigColumns:zQ,BaseName:l5,IsAlias:z6,ExtraConfigBuilder:TQ};[NW];[d5];[zY];[TY];[zQ];[l5];[z6]=!1;[QO]=!0;[TQ]=void 0;constructor(W,$,X){this[NW]=this[d5]=W,this[zY]=$,this[l5]=X}}function w1(W){return W[NW]}function A8(W){return`${W[zY]??"public"}.${W[NW]}`}function o5(W){return W!==null&&W!==void 0&&typeof W.getSQL==="function"}function zO(W){let $={sql:"",params:[]};for(let X of W)if($.sql+=X.sql,$.params.push(...X.params),X.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...X.typings)}return $}class Q1{static[D]="StringChunk";value;constructor(W){this.value=Array.isArray(W)?W:[W]}getSQL(){return new p([this])}}class p{constructor(W){this.queryChunks=W}static[D]="SQL";decoder=_Q;shouldInlineParams=!1;append(W){return this.queryChunks.push(...W.queryChunks),this}toQuery(W){return C0.startActiveSpan("drizzle.buildSQL",($)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,W);return $?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(W,$){let X=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:Y,escapeName:G,escapeParam:J,prepareTyping:H,inlineParams:Q,paramStartIndex:z}=X;return zO(W.map((T)=>{if(L(T,Q1))return{sql:T.value.join(""),params:[]};if(L(T,FY))return{sql:G(T.value),params:[]};if(T===void 0)return{sql:"",params:[]};if(Array.isArray(T)){let F=[new Q1("(")];for(let[_,w]of T.entries())if(F.push(w),_<T.length-1)F.push(new Q1(", "));return F.push(new Q1(")")),this.buildQueryFromSourceParams(F,X)}if(L(T,p))return this.buildQueryFromSourceParams(T.queryChunks,{...X,inlineParams:Q||T.shouldInlineParams});if(L(T,g)){let F=T[g.Symbol.Schema],_=T[g.Symbol.Name];return{sql:F===void 0||T[z6]?G(_):G(F)+"."+G(_),params:[]}}if(L(T,q0)){let F=Y.getColumnCasing(T);if($.invokeSource==="indexes")return{sql:G(F),params:[]};let _=T.table[g.Symbol.Schema];return{sql:T.table[z6]||_===void 0?G(T.table[g.Symbol.Name])+"."+G(F):G(_)+"."+G(T.table[g.Symbol.Name])+"."+G(F),params:[]}}if(L(T,g1)){let F=T[f0].schema,_=T[f0].name;return{sql:F===void 0||T[f0].isAlias?G(_):G(F)+"."+G(_),params:[]}}if(L(T,e1)){if(L(T.value,x2))return{sql:J(z.value++,T),params:[T],typings:["none"]};let F=T.value===null?null:T.encoder.mapToDriverValue(T.value);if(L(F,p))return this.buildQueryFromSourceParams([F],X);if(Q)return{sql:this.mapInlineParam(F,X),params:[]};let _=["none"];if(H)_=[H(T.encoder)];return{sql:J(z.value++,F),params:[F],typings:_}}if(L(T,x2))return{sql:J(z.value++,T),params:[T],typings:["none"]};if(L(T,p.Aliased)&&T.fieldAlias!==void 0)return{sql:G(T.fieldAlias),params:[]};if(L(T,H1)){if(T._.isWith)return{sql:G(T._.alias),params:[]};return this.buildQueryFromSourceParams([new Q1("("),T._.sql,new Q1(") "),new FY(T._.alias)],X)}if(GQ(T)){if(T.schema)return{sql:G(T.schema)+"."+G(T.enumName),params:[]};return{sql:G(T.enumName),params:[]}}if(o5(T)){if(T.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([T.getSQL()],X);return this.buildQueryFromSourceParams([new Q1("("),T.getSQL(),new Q1(")")],X)}if(Q)return{sql:this.mapInlineParam(T,X),params:[]};return{sql:J(z.value++,T),params:[T],typings:["none"]}}))}mapInlineParam(W,{escapeString:$}){if(W===null)return"null";if(typeof W==="number"||typeof W==="boolean")return W.toString();if(typeof W==="string")return $(W);if(typeof W==="object"){let X=W.toString();if(X==="[object Object]")return $(JSON.stringify(W));return $(X)}throw new Error("Unexpected param value: "+W)}getSQL(){return this}as(W){if(W===void 0)return this;return new p.Aliased(this,W)}mapWith(W){return this.decoder=typeof W==="function"?{mapFromDriverValue:W}:W,this}inlineParams(){return this.shouldInlineParams=!0,this}if(W){return W?this:void 0}}class FY{constructor(W){this.value=W}static[D]="Name";brand;getSQL(){return new p([this])}}function FQ(W){return typeof W==="object"&&W!==null&&"mapToDriverValue"in W&&typeof W.mapToDriverValue==="function"}var _Q={mapFromDriverValue:(W)=>W},wQ={mapToDriverValue:(W)=>W},ex={..._Q,...wQ};class e1{constructor(W,$=wQ){this.value=W,this.encoder=$}static[D]="Param";brand;getSQL(){return new p([this])}}function V(W,...$){let X=[];if($.length>0||W.length>0&&W[0]!=="")X.push(new Q1(W[0]));for(let[Y,G]of $.entries())X.push(G,new Q1(W[Y+1]));return new p(X)}((W)=>{function $(){return new p([])}W.empty=$;function X(z){return new p(z)}W.fromList=X;function Y(z){return new p([new Q1(z)])}W.raw=Y;function G(z,T){let F=[];for(let[_,w]of z.entries()){if(_>0&&T!==void 0)F.push(T);F.push(w)}return new p(F)}W.join=G;function J(z){return new FY(z)}W.identifier=J;function H(z){return new x2(z)}W.placeholder=H;function Q(z,T){return new e1(z,T)}W.param=Q})(V||(V={}));((W)=>{class ${constructor(X,Y){this.sql=X,this.fieldAlias=Y}static[D]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}W.Aliased=$})(p||(p={}));class x2{constructor(W){this.name=W}static[D]="Placeholder";getSQL(){return new p([this])}}function i5(W,$){return W.map((X)=>{if(L(X,x2)){if(!(X.name in $))throw new Error(`No value for placeholder "${X.name}" was provided`);return $[X.name]}if(L(X,e1)&&L(X.value,x2)){if(!(X.value.name in $))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue($[X.value.name])}return X})}var TO=Symbol.for("drizzle:IsDrizzleView");class g1{static[D]="View";[f0];[TO]=!0;constructor({name:W,schema:$,selectedFields:X,query:Y}){this[f0]={name:W,originalName:W,schema:$,selectedFields:X,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new p([this])}}q0.prototype.getSQL=function(){return new p([this])};g.prototype.getSQL=function(){return new p([this])};H1.prototype.getSQL=function(){return new p([this])};class M4{constructor(W){this.table=W}static[D]="ColumnAliasProxyHandler";get(W,$){if($==="table")return this.table;return W[$]}}class T6{constructor(W,$){this.alias=W,this.replaceOriginalName=$}static[D]="TableAliasProxyHandler";get(W,$){if($===g.Symbol.IsAlias)return!0;if($===g.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===g.Symbol.OriginalName)return this.alias;if($===f0)return{...W[f0],name:this.alias,isAlias:!0};if($===g.Symbol.Columns){let Y=W[g.Symbol.Columns];if(!Y)return Y;let G={};return Object.keys(Y).map((J)=>{G[J]=new Proxy(Y[J],new M4(new Proxy(W,this)))}),G}let X=W[$];if(L(X,q0))return new Proxy(X,new M4(new Proxy(W,this)));return X}}function _Y(W,$){return new Proxy(W,new T6($,!1))}function mW(W,$){return new Proxy(W,new M4(new Proxy(W.table,new T6($,!1))))}function n5(W,$){return new p.Aliased(F6(W.sql,$),W.fieldAlias)}function F6(W,$){return V.join(W.queryChunks.map((X)=>{if(L(X,q0))return mW(X,$);if(L(X,p))return F6(X,$);if(L(X,p.Aliased))return n5(X,$);return X}))}class wY extends Error{static[D]="DrizzleError";constructor({message:W,cause:$}){super(W);this.name="DrizzleError",this.cause=$}}class r5 extends wY{static[D]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class UQ{static[D]="ConsoleLogWriter";write(W){console.log(W)}}class t5{static[D]="DefaultLogger";writer;constructor(W){this.writer=W?.writer??new UQ}logQuery(W,$){let X=$.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),Y=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${W}${Y}`)}}class a5{static[D]="NoopLogger";logQuery(){}}class j1{static[D]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(W){return this.then(void 0,W)}finally(W){return this.then(($)=>{return W?.(),$},($)=>{throw W?.(),$})}then(W,$){return this.execute().then(W,$)}}function DQ(W,$,X){let Y={},G=W.reduce((J,{path:H,field:Q},z)=>{let T;if(L(Q,q0))T=Q;else if(L(Q,p))T=Q.decoder;else T=Q.sql.decoder;let F=J;for(let[_,w]of H.entries())if(_<H.length-1){if(!(w in F))F[w]={};F=F[w]}else{let O=$[z],M=F[w]=O===null?null:T.mapFromDriverValue(O);if(X&&L(Q,q0)&&H.length===2){let A=H[0];if(!(A in Y))Y[A]=M===null?w1(Q.table):!1;else if(typeof Y[A]==="string"&&Y[A]!==w1(Q.table))Y[A]=!1}}return J},{});if(X&&Object.keys(Y).length>0){for(let[J,H]of Object.entries(Y))if(typeof H==="string"&&!X[H])G[J]=null}return G}function zW(W,$){return Object.entries(W).reduce((X,[Y,G])=>{if(typeof Y!=="string")return X;let J=$?[...$,Y]:[Y];if(L(G,q0)||L(G,p)||L(G,p.Aliased))X.push({path:J,field:G});else if(L(G,g))X.push(...zW(G[g.Symbol.Columns],J));else X.push(...zW(G,J));return X},[])}function _6(W,$){let X=Object.keys(W),Y=Object.keys($);if(X.length!==Y.length)return!1;for(let[G,J]of X.entries())if(J!==Y[G])return!1;return!0}function UY(W,$){let X=Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,G])=>{if(L(G,p)||L(G,q0))return[Y,G];else return[Y,new e1(G,W[g.Symbol.Columns][Y])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function VQ(W,$){for(let X of $)for(let Y of Object.getOwnPropertyNames(X.prototype)){if(Y==="constructor")continue;Object.defineProperty(W.prototype,Y,Object.getOwnPropertyDescriptor(X.prototype,Y)||Object.create(null))}}function MQ(W){return W[g.Symbol.Columns]}function G2(W){return L(W,H1)?W._.alias:L(W,g1)?W[f0].name:L(W,p)?void 0:W[g.Symbol.IsAlias]?W[g.Symbol.Name]:W[g.Symbol.BaseName]}function M0(W,$){return{name:typeof W==="string"&&W.length>0?W:"",config:typeof W==="object"?W:$}}function OQ(W){if(typeof W!=="object"||W===null)return!1;if(W.constructor.name!=="Object")return!1;if("logger"in W){let $=typeof W.logger;if($!=="boolean"&&($!=="object"||typeof W.logger.logQuery!=="function")&&$!=="undefined")return!1;return!0}if("schema"in W){let $=typeof W.schema;if($!=="object"&&$!=="undefined")return!1;return!0}if("casing"in W){let $=typeof W.casing;if($!=="string"&&$!=="undefined")return!1;return!0}if("mode"in W){if(W.mode!=="default"||W.mode!=="planetscale"||W.mode!==void 0)return!1;return!0}if("connection"in W){let $=typeof W.connection;if($!=="string"&&$!=="object"&&$!=="undefined")return!1;return!0}if("client"in W){let $=typeof W.client;if($!=="object"&&$!=="function"&&$!=="undefined")return!1;return!0}if(Object.keys(W).length===0)return!0;return!1}class b2 extends c{static[D]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(W){if(W){let{name:$,...X}=W;this.config.generatedIdentity={type:"always",sequenceName:$,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(W){if(W){let{name:$,...X}=W;this.config.generatedIdentity={type:"byDefault",sequenceName:$,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class KQ extends b2{static[D]="PgBigInt53Builder";constructor(W){super(W,"number","PgBigInt53")}build(W){return new AQ(W,this.config)}}class AQ extends f{static[D]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class EQ extends b2{static[D]="PgBigInt64Builder";constructor(W){super(W,"bigint","PgBigInt64")}build(W){return new LQ(W,this.config)}}class LQ extends f{static[D]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(W){return BigInt(W)}}function BQ(W,$){let{name:X,config:Y}=M0(W,$);if(Y.mode==="number")return new KQ(X);return new EQ(X)}class RQ extends c{static[D]="PgBigSerial53Builder";constructor(W){super(W,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new NQ(W,this.config)}}class NQ extends f{static[D]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class ZQ extends c{static[D]="PgBigSerial64Builder";constructor(W){super(W,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(W){return new SQ(W,this.config)}}class SQ extends f{static[D]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(W){return BigInt(W)}}function qQ(W,$){let{name:X,config:Y}=M0(W,$);if(Y.mode==="number")return new RQ(X);return new ZQ(X)}class CQ extends c{static[D]="PgBooleanBuilder";constructor(W){super(W,"boolean","PgBoolean")}build(W){return new kQ(W,this.config)}}class kQ extends f{static[D]="PgBoolean";getSQLType(){return"boolean"}}function w6(W){return new CQ(W??"")}class jQ extends c{static[D]="PgCharBuilder";constructor(W,$){super(W,"string","PgChar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new IQ(W,this.config)}}class IQ extends f{static[D]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function PQ(W,$={}){let{name:X,config:Y}=M0(W,$);return new jQ(X,Y)}class fQ extends c{static[D]="PgCidrBuilder";constructor(W){super(W,"string","PgCidr")}build(W){return new xQ(W,this.config)}}class xQ extends f{static[D]="PgCidr";getSQLType(){return"cidr"}}function bQ(W){return new fQ(W??"")}class vQ extends c{static[D]="PgCustomColumnBuilder";constructor(W,$,X){super(W,"custom","PgCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=X}build(W){return new yQ(W,this.config)}}class yQ extends f{static[D]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(W,$){super(W,$);this.sqlName=$.customTypeParams.dataType($.fieldConfig),this.mapTo=$.customTypeParams.toDriver,this.mapFrom=$.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(W){return typeof this.mapFrom==="function"?this.mapFrom(W):W}mapToDriverValue(W){return typeof this.mapTo==="function"?this.mapTo(W):W}}function hQ(W){return($,X)=>{let{name:Y,config:G}=M0($,X);return new vQ(Y,G,W)}}class J2 extends c{static[D]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class gQ extends J2{static[D]="PgDateBuilder";constructor(W){super(W,"date","PgDate")}build(W){return new DY(W,this.config)}}class DY extends f{static[D]="PgDate";getSQLType(){return"date"}mapFromDriverValue(W){return new Date(W)}mapToDriverValue(W){return W.toISOString()}}class mQ extends J2{static[D]="PgDateStringBuilder";constructor(W){super(W,"string","PgDateString")}build(W){return new VY(W,this.config)}}class VY extends f{static[D]="PgDateString";getSQLType(){return"date"}}function pQ(W,$){let{name:X,config:Y}=M0(W,$);if(Y?.mode==="date")return new gQ(X);return new mQ(X)}class uQ extends c{static[D]="PgDoublePrecisionBuilder";constructor(W){super(W,"number","PgDoublePrecision")}build(W){return new cQ(W,this.config)}}class cQ extends f{static[D]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseFloat(W);return W}}function dQ(W){return new uQ(W??"")}class lQ extends c{static[D]="PgInetBuilder";constructor(W){super(W,"string","PgInet")}build(W){return new oQ(W,this.config)}}class oQ extends f{static[D]="PgInet";getSQLType(){return"inet"}}function iQ(W){return new lQ(W??"")}class nQ extends b2{static[D]="PgIntegerBuilder";constructor(W){super(W,"number","PgInteger")}build(W){return new rQ(W,this.config)}}class rQ extends f{static[D]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseInt(W);return W}}function U6(W){return new nQ(W??"")}class tQ extends c{static[D]="PgIntervalBuilder";constructor(W,$){super(W,"string","PgInterval");this.config.intervalConfig=$}build(W){return new aQ(W,this.config)}}class aQ extends f{static[D]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let W=this.fields?` ${this.fields}`:"",$=this.precision?`(${this.precision})`:"";return`interval${W}${$}`}}function sQ(W,$={}){let{name:X,config:Y}=M0(W,$);return new tQ(X,Y)}class eQ extends c{static[D]="PgJsonBuilder";constructor(W){super(W,"json","PgJson")}build(W){return new MY(W,this.config)}}class MY extends f{static[D]="PgJson";constructor(W,$){super(W,$)}getSQLType(){return"json"}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){if(typeof W==="string")try{return JSON.parse(W)}catch{return W}return W}}function Wz(W){return new eQ(W??"")}class $z extends c{static[D]="PgJsonbBuilder";constructor(W){super(W,"json","PgJsonb")}build(W){return new OY(W,this.config)}}class OY extends f{static[D]="PgJsonb";constructor(W,$){super(W,$)}getSQLType(){return"jsonb"}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){if(typeof W==="string")try{return JSON.parse(W)}catch{return W}return W}}function Xz(W){return new $z(W??"")}class Yz extends c{static[D]="PgLineBuilder";constructor(W){super(W,"array","PgLine")}build(W){return new Gz(W,this.config)}}class Gz extends f{static[D]="PgLine";getSQLType(){return"line"}mapFromDriverValue(W){let[$,X,Y]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(X),Number.parseFloat(Y)]}mapToDriverValue(W){return`{${W[0]},${W[1]},${W[2]}}`}}class Jz extends c{static[D]="PgLineABCBuilder";constructor(W){super(W,"json","PgLineABC")}build(W){return new Hz(W,this.config)}}class Hz extends f{static[D]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(W){let[$,X,Y]=W.slice(1,-1).split(",");return{a:Number.parseFloat($),b:Number.parseFloat(X),c:Number.parseFloat(Y)}}mapToDriverValue(W){return`{${W.a},${W.b},${W.c}}`}}function Qz(W,$){let{name:X,config:Y}=M0(W,$);if(!Y?.mode||Y.mode==="tuple")return new Yz(X);return new Jz(X)}class zz extends c{static[D]="PgMacaddrBuilder";constructor(W){super(W,"string","PgMacaddr")}build(W){return new Tz(W,this.config)}}class Tz extends f{static[D]="PgMacaddr";getSQLType(){return"macaddr"}}function Fz(W){return new zz(W??"")}class _z extends c{static[D]="PgMacaddr8Builder";constructor(W){super(W,"string","PgMacaddr8")}build(W){return new wz(W,this.config)}}class wz extends f{static[D]="PgMacaddr8";getSQLType(){return"macaddr8"}}function Uz(W){return new _z(W??"")}class Dz extends c{static[D]="PgNumericBuilder";constructor(W,$,X){super(W,"string","PgNumeric");this.config.precision=$,this.config.scale=X}build(W){return new KY(W,this.config)}}class KY extends f{static[D]="PgNumeric";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(W){if(typeof W==="string")return W;return String(W)}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})`}}class Vz extends c{static[D]="PgNumericNumberBuilder";constructor(W,$,X){super(W,"number","PgNumericNumber");this.config.precision=$,this.config.scale=X}build(W){return new Mz(W,this.config)}}class Mz extends f{static[D]="PgNumericNumber";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}mapToDriverValue=String;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})`}}class Oz extends c{static[D]="PgNumericBigIntBuilder";constructor(W,$,X){super(W,"bigint","PgNumericBigInt");this.config.precision=$,this.config.scale=X}build(W){return new Kz(W,this.config)}}class Kz extends f{static[D]="PgNumericBigInt";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;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 Az(W,$){let{name:X,config:Y}=M0(W,$),G=Y?.mode;return G==="number"?new Vz(X,Y?.precision,Y?.scale):G==="bigint"?new Oz(X,Y?.precision,Y?.scale):new Dz(X,Y?.precision,Y?.scale)}class Ez extends c{static[D]="PgPointTupleBuilder";constructor(W){super(W,"array","PgPointTuple")}build(W){return new Lz(W,this.config)}}class Lz extends f{static[D]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,X]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(X)]}return[W.x,W.y]}mapToDriverValue(W){return`(${W[0]},${W[1]})`}}class Bz extends c{static[D]="PgPointObjectBuilder";constructor(W){super(W,"json","PgPointObject")}build(W){return new Rz(W,this.config)}}class Rz extends f{static[D]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,X]=W.slice(1,-1).split(",");return{x:Number.parseFloat($),y:Number.parseFloat(X)}}return W}mapToDriverValue(W){return`(${W.x},${W.y})`}}function Nz(W,$){let{name:X,config:Y}=M0(W,$);if(!Y?.mode||Y.mode==="tuple")return new Ez(X);return new Bz(X)}function FO(W){let $=[];for(let X=0;X<W.length;X+=2)$.push(Number.parseInt(W.slice(X,X+2),16));return new Uint8Array($)}function Zz(W,$){let X=new ArrayBuffer(8),Y=new DataView(X);for(let G=0;G<8;G++)Y.setUint8(G,W[$+G]);return Y.getFloat64(0,!0)}function s5(W){let $=FO(W),X=0,Y=$[X];X+=1;let G=new DataView($.buffer),J=G.getUint32(X,Y===1);X+=4;let H;if(J&536870912)H=G.getUint32(X,Y===1),X+=4;if((J&65535)===1){let Q=Zz($,X);X+=8;let z=Zz($,X);return X+=8,[Q,z]}throw new Error("Unsupported geometry type")}class Sz extends c{static[D]="PgGeometryBuilder";constructor(W){super(W,"array","PgGeometry")}build(W){return new qz(W,this.config)}}class qz extends f{static[D]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){return s5(W)}mapToDriverValue(W){return`point(${W[0]} ${W[1]})`}}class Cz extends c{static[D]="PgGeometryObjectBuilder";constructor(W){super(W,"json","PgGeometryObject")}build(W){return new kz(W,this.config)}}class kz extends f{static[D]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){let $=s5(W);return{x:$[0],y:$[1]}}mapToDriverValue(W){return`point(${W.x} ${W.y})`}}function jz(W,$){let{name:X,config:Y}=M0(W,$);if(!Y?.mode||Y.mode==="tuple")return new Sz(X);return new Cz(X)}class Iz extends c{static[D]="PgRealBuilder";constructor(W,$){super(W,"number","PgReal");this.config.length=$}build(W){return new Pz(W,this.config)}}class Pz extends f{static[D]="PgReal";constructor(W,$){super(W,$)}getSQLType(){return"real"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number.parseFloat(W);return W}}function fz(W){return new Iz(W??"")}class xz extends c{static[D]="PgSerialBuilder";constructor(W){super(W,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new bz(W,this.config)}}class bz extends f{static[D]="PgSerial";getSQLType(){return"serial"}}function vz(W){return new xz(W??"")}class yz extends b2{static[D]="PgSmallIntBuilder";constructor(W){super(W,"number","PgSmallInt")}build(W){return new hz(W,this.config)}}class hz extends f{static[D]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number(W);return W}}function gz(W){return new yz(W??"")}class mz extends c{static[D]="PgSmallSerialBuilder";constructor(W){super(W,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new pz(W,this.config)}}class pz extends f{static[D]="PgSmallSerial";getSQLType(){return"smallserial"}}function uz(W){return new mz(W??"")}class cz extends c{static[D]="PgTextBuilder";constructor(W,$){super(W,"string","PgText");this.config.enumValues=$.enum}build(W){return new dz(W,this.config)}}class dz extends f{static[D]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function lz(W,$={}){let{name:X,config:Y}=M0(W,$);return new cz(X,Y)}class oz extends J2{constructor(W,$,X){super(W,"string","PgTime");this.withTimezone=$,this.precision=X,this.config.withTimezone=$,this.config.precision=X}static[D]="PgTimeBuilder";build(W){return new AY(W,this.config)}}class AY extends f{static[D]="PgTime";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function iz(W,$={}){let{name:X,config:Y}=M0(W,$);return new oz(X,Y.withTimezone??!1,Y.precision)}class nz extends J2{static[D]="PgTimestampBuilder";constructor(W,$,X){super(W,"date","PgTimestamp");this.config.withTimezone=$,this.config.precision=X}build(W){return new EY(W,this.config)}}class EY extends f{static[D]="PgTimestamp";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(W)=>{return new Date(this.withTimezone?W:W+"+0000")};mapToDriverValue=(W)=>{return W.toISOString()}}class rz extends J2{static[D]="PgTimestampStringBuilder";constructor(W,$,X){super(W,"string","PgTimestampString");this.config.withTimezone=$,this.config.precision=X}build(W){return new LY(W,this.config)}}class LY extends f{static[D]="PgTimestampString";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function ZW(W,$={}){let{name:X,config:Y}=M0(W,$);if(Y?.mode==="string")return new rz(X,Y.withTimezone??!1,Y.precision);return new nz(X,Y?.withTimezone??!1,Y?.precision)}class tz extends c{static[D]="PgUUIDBuilder";constructor(W){super(W,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(W){return new BY(W,this.config)}}class BY extends f{static[D]="PgUUID";getSQLType(){return"uuid"}}function TW(W){return new tz(W??"")}class az extends c{static[D]="PgVarcharBuilder";constructor(W,$){super(W,"string","PgVarchar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new sz(W,this.config)}}class sz extends f{static[D]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function I1(W,$={}){let{name:X,config:Y}=M0(W,$);return new az(X,Y)}class ez extends c{static[D]="PgBinaryVectorBuilder";constructor(W,$){super(W,"string","PgBinaryVector");this.config.dimensions=$.dimensions}build(W){return new WT(W,this.config)}}class WT extends f{static[D]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function $T(W,$){let{name:X,config:Y}=M0(W,$);return new ez(X,Y)}class XT extends c{static[D]="PgHalfVectorBuilder";constructor(W,$){super(W,"array","PgHalfVector");this.config.dimensions=$.dimensions}build(W){return new YT(W,this.config)}}class YT extends f{static[D]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){return W.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function GT(W,$){let{name:X,config:Y}=M0(W,$);return new XT(X,Y)}class JT extends c{static[D]="PgSparseVectorBuilder";constructor(W,$){super(W,"string","PgSparseVector");this.config.dimensions=$.dimensions}build(W){return new HT(W,this.config)}}class HT extends f{static[D]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function QT(W,$){let{name:X,config:Y}=M0(W,$);return new JT(X,Y)}class zT extends c{static[D]="PgVectorBuilder";constructor(W,$){super(W,"array","PgVector");this.config.dimensions=$.dimensions}build(W){return new TT(W,this.config)}}class TT extends f{static[D]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){return W.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function FT(W,$){let{name:X,config:Y}=M0(W,$);return new zT(X,Y)}function _T(){return{bigint:BQ,bigserial:qQ,boolean:w6,char:PQ,cidr:bQ,customType:hQ,date:pQ,doublePrecision:dQ,inet:iQ,integer:U6,interval:sQ,json:Wz,jsonb:Xz,line:Qz,macaddr:Fz,macaddr8:Uz,numeric:Az,point:Nz,geometry:jz,real:fz,serial:vz,smallint:gz,smallserial:uz,text:lz,time:iz,timestamp:ZW,uuid:TW,varchar:I1,bit:$T,halfvec:GT,sparsevec:QT,vector:FT}}var e5=Symbol.for("drizzle:PgInlineForeignKeys"),wT=Symbol.for("drizzle:EnableRLS");class V1 extends g{static[D]="PgTable";static Symbol=Object.assign({},g.Symbol,{InlineForeignKeys:e5,EnableRLS:wT});[e5]=[];[wT]=!1;[g.Symbol.ExtraConfigBuilder]=void 0;[g.Symbol.ExtraConfigColumns]={}}function _O(W,$,X,Y,G=W){let J=new V1(W,Y,G),H=typeof $==="function"?$(_T()):$,Q=Object.fromEntries(Object.entries(H).map(([F,_])=>{let w=_;w.setName(F);let O=w.build(J);return J[e5].push(...w.buildForeignKeys(O,J)),[F,O]})),z=Object.fromEntries(Object.entries(H).map(([F,_])=>{let w=_;w.setName(F);let O=w.buildExtraConfigColumn(J);return[F,O]})),T=Object.assign(J,Q);if(T[g.Symbol.Columns]=Q,T[g.Symbol.ExtraConfigColumns]=z,X)T[V1.Symbol.ExtraConfigBuilder]=X;return Object.assign(T,{enableRLS:()=>{return T[V1.Symbol.EnableRLS]=!0,T}})}var v2=(W,$,X)=>{return _O(W,$,X,void 0)};function UT(...W){if(W[0].columns)return new D6(W[0].columns,W[0].name);return new D6(W)}class D6{static[D]="PgPrimaryKeyBuilder";columns;name;constructor(W,$){this.columns=W,this.name=$}build(W){return new DT(W,this.columns,this.name)}}class DT{constructor(W,$,X){this.table=W,this.columns=$,this.name=X}static[D]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[V1.Symbol.Name]}_${this.columns.map((W)=>W.name).join("_")}_pk`}}function m1(W,$){if(FQ($)&&!o5(W)&&!L(W,e1)&&!L(W,x2)&&!L(W,q0)&&!L(W,g)&&!L(W,g1))return new e1(W,$);return W}var RY=(W,$)=>{return V`${W} = ${m1($,W)}`},VT=(W,$)=>{return V`${W} <> ${m1($,W)}`};function V6(...W){let $=W.filter((X)=>X!==void 0);if($.length===0)return;if($.length===1)return new p($);return new p([new Q1("("),V.join($,new Q1(" and ")),new Q1(")")])}function MT(...W){let $=W.filter((X)=>X!==void 0);if($.length===0)return;if($.length===1)return new p($);return new p([new Q1("("),V.join($,new Q1(" or ")),new Q1(")")])}function OT(W){return V`not ${W}`}var NY=(W,$)=>{return V`${W} > ${m1($,W)}`},KT=(W,$)=>{return V`${W} >= ${m1($,W)}`},AT=(W,$)=>{return V`${W} < ${m1($,W)}`},ET=(W,$)=>{return V`${W} <= ${m1($,W)}`};function LT(W,$){if(Array.isArray($)){if($.length===0)return V`false`;return V`${W} in ${$.map((X)=>m1(X,W))}`}return V`${W} in ${m1($,W)}`}function BT(W,$){if(Array.isArray($)){if($.length===0)return V`true`;return V`${W} not in ${$.map((X)=>m1(X,W))}`}return V`${W} not in ${m1($,W)}`}function RT(W){return V`${W} is null`}function NT(W){return V`${W} is not null`}function ZT(W){return V`exists ${W}`}function ST(W){return V`not exists ${W}`}function qT(W,$,X){return V`${W} between ${m1($,W)} and ${m1(X,W)}`}function CT(W,$,X){return V`${W} not between ${m1($,W)} and ${m1(X,W)}`}function kT(W,$){return V`${W} like ${$}`}function jT(W,$){return V`${W} not like ${$}`}function IT(W,$){return V`${W} ilike ${$}`}function PT(W,$){return V`${W} not ilike ${$}`}function fT(W){return V`${W} asc`}function xT(W){return V`${W} desc`}class W7{constructor(W,$,X){this.sourceTable=W,this.referencedTable=$,this.relationName=X,this.referencedTableName=$[g.Symbol.Name]}static[D]="Relation";referencedTableName;fieldName}class bT{constructor(W,$){this.table=W,this.config=$}static[D]="Relations"}class y2 extends W7{constructor(W,$,X,Y){super(W,$,X?.relationName);this.config=X,this.isNullable=Y}static[D]="One";withFieldName(W){let $=new y2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=W,$}}class M6 extends W7{constructor(W,$,X){super(W,$,X?.relationName);this.config=X}static[D]="Many";withFieldName(W){let $=new M6(this.sourceTable,this.referencedTable,this.config);return $.fieldName=W,$}}function vT(){return{and:V6,between:qT,eq:RY,exists:ZT,gt:NY,gte:KT,ilike:IT,inArray:LT,isNull:RT,isNotNull:NT,like:kT,lt:AT,lte:ET,ne:VT,not:OT,notBetween:CT,notExists:ST,notLike:jT,notIlike:PT,notInArray:BT,or:MT,sql:V}}function yT(){return{sql:V,asc:fT,desc:xT}}function hT(W,$){if(Object.keys(W).length===1&&"default"in W&&!L(W.default,g))W=W.default;let X={},Y={},G={};for(let[J,H]of Object.entries(W))if(L(H,g)){let Q=A8(H),z=Y[Q];X[Q]=J,G[J]={tsName:J,dbName:H[g.Symbol.Name],schema:H[g.Symbol.Schema],columns:H[g.Symbol.Columns],relations:z?.relations??{},primaryKey:z?.primaryKey??[]};for(let F of Object.values(H[g.Symbol.Columns]))if(F.primary)G[J].primaryKey.push(F);let T=H[g.Symbol.ExtraConfigBuilder]?.(H[g.Symbol.ExtraConfigColumns]);if(T){for(let F of Object.values(T))if(L(F,D6))G[J].primaryKey.push(...F.columns)}}else if(L(H,bT)){let Q=A8(H.table),z=X[Q],T=H.config($(H.table)),F;for(let[_,w]of Object.entries(T))if(z){let O=G[z];if(O.relations[_]=w,F)O.primaryKey.push(...F)}else{if(!(Q in Y))Y[Q]={relations:{},primaryKey:F};Y[Q].relations[_]=w}}return{tables:G,tableNamesMap:X}}function wO(W){return function $(X,Y){return new y2(W,X,Y,Y?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function UO(W){return function $(X,Y){return new M6(W,X,Y)}}function gT(W,$,X){if(L(X,y2)&&X.config)return{fields:X.config.fields,references:X.config.references};let Y=$[A8(X.referencedTable)];if(!Y)throw new Error(`Table "${X.referencedTable[g.Symbol.Name]}" not found in schema`);let G=W[Y];if(!G)throw new Error(`Table "${Y}" not found in schema`);let J=X.sourceTable,H=$[A8(J)];if(!H)throw new Error(`Table "${J[g.Symbol.Name]}" not found in schema`);let Q=[];for(let z of Object.values(G.relations))if(X.relationName&&X!==z&&z.relationName===X.relationName||!X.relationName&&z.referencedTable===X.sourceTable)Q.push(z);if(Q.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${Y}"`):new Error(`There are multiple relations between "${Y}" and "${X.sourceTable[g.Symbol.Name]}". Please specify relation name`);if(Q[0]&&L(Q[0],y2)&&Q[0].config)return{fields:Q[0].config.references,references:Q[0].config.fields};throw new Error(`There is not enough information to infer relation "${H}.${X.fieldName}"`)}function mT(W){return{one:wO(W),many:UO(W)}}function ZY(W,$,X,Y,G=(J)=>J){let J={};for(let[H,Q]of Y.entries())if(Q.isJson){let z=$.relations[Q.tsKey],T=X[H],F=typeof T==="string"?JSON.parse(T):T;J[Q.tsKey]=L(z,y2)?F&&ZY(W,W[Q.relationTableTsKey],F,Q.selection,G):F.map((_)=>ZY(W,W[Q.relationTableTsKey],_,Q.selection,G))}else{let z=G(X[H]),T=Q.field,F;if(L(T,q0))F=T;else if(L(T,p))F=T.decoder;else F=T.sql.decoder;J[Q.tsKey]=z===null?null:F.mapFromDriverValue(z)}return J}import XB from"path";import yO from"os";import hO from"fs";var SY=new Map,$7=new Map,X7=Symbol("OriginError"),O4={};class FW extends Promise{constructor(W,$,X,Y,G={}){let J,H;super((Q,z)=>{J=Q,H=z});this.tagged=Array.isArray(W.raw),this.strings=W,this.args=$,this.handler=X,this.canceller=Y,this.options=G,this.state=null,this.statement=null,this.resolve=(Q)=>(this.active=!1,J(Q)),this.reject=(Q)=>(this.active=!1,H(Q)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[X7]=this.handler.debug?new Error:this.tagged&&DO(this.strings)}get origin(){return(this.handler.debug?this[X7].stack:this.tagged&&$7.has(this.strings)?$7.get(this.strings):$7.set(this.strings,this[X7].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(W=1,$){if(this.options.simple=!1,typeof W==="function")$=W,W=1;if(this.cursorRows=W,typeof $==="function")return this.cursorFn=$,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let Y=new Promise((G,J)=>{this.cursorFn=(H)=>{return G({value:H,done:!1}),new Promise((Q)=>X=Q)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(H)=>(this.active=!1,J(H))});return this.execute(),Y},return(){return X&&X(O4),{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(W){return this.forEachFn=W,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 DO(W){if(SY.has(W))return SY.get(W);let $=Error.stackTraceLimit;return Error.stackTraceLimit=4,SY.set(W,new Error),Error.stackTraceLimit=$,SY.get(W)}class K4 extends Error{constructor(W){super(W.message);this.name=this.constructor.name,Object.assign(this,W)}}var a0={connection:pT,postgres:uT,generic:cT,notSupported:dT};function pT(W,$,X){let{host:Y,port:G}=X||$,J=Object.assign(new Error("write "+W+" "+($.path||Y+":"+G)),{code:W,errno:W,address:$.path||Y},$.path?{}:{port:G});return Error.captureStackTrace(J,pT),J}function uT(W){let $=new K4(W);return Error.captureStackTrace($,uT),$}function cT(W,$){let X=Object.assign(new Error(W+": "+$),{code:W});return Error.captureStackTrace(X,cT),X}function dT(W){let $=Object.assign(new Error(W+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:W});return Error.captureStackTrace($,dT),$}var VO={string:{to:25,from:null,serialize:(W)=>""+W},number:{to:0,from:[21,23,26,700,701],serialize:(W)=>""+W,parse:(W)=>+W},json:{to:114,from:[114,3802],serialize:(W)=>JSON.stringify(W),parse:(W)=>JSON.parse(W)},boolean:{to:16,from:16,serialize:(W)=>W===!0?"t":"f",parse:(W)=>W==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(W)=>(W instanceof Date?W:new Date(W)).toISOString(),parse:(W)=>new Date(W)},bytea:{to:17,from:17,serialize:(W)=>"\\x"+Buffer.from(W).toString("hex"),parse:(W)=>Buffer.from(W.slice(2),"hex")}};class kY{then(){Y7()}catch(){Y7()}finally(){Y7()}}class E6 extends kY{constructor(W){super();this.value=PY(W)}}class pW extends kY{constructor(W,$,X){super();this.value=W,this.type=$,this.array=X}}class jY extends kY{constructor(W,$){super();this.first=W,this.rest=$}build(W,$,X,Y){let G=MO.map(([J,H])=>({fn:H,i:W.search(J)})).sort((J,H)=>J.i-H.i).pop();return G.i===-1?z7(this.first,Y):G.fn(this.first,this.rest,$,X,Y)}}function IY(W,$,X,Y){let G=W instanceof pW?W.value:W;if(G===void 0){if(W instanceof pW?W.value=Y.transform.undefined:G=W=Y.transform.undefined,G===void 0)throw a0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(W instanceof pW?($.push(W.value),W.array?W.array[W.type||CY(W.value)]||W.type||nT(W.value):W.type):($.push(W),CY(W)))}var oT=tT(VO);function H7(W,$,X,Y,G,J){for(let H=1;H<W.strings.length;H++)$+=Q7($,X,Y,G,J)+W.strings[H],X=W.args[H];return $}function Q7(W,$,X,Y,G){return $ instanceof jY?$.build(W,X,Y,G):$ instanceof FW?J7($,X,Y,G):$ instanceof E6?$.value:$&&$[0]instanceof FW?$.reduce((J,H)=>J+" "+J7(H,X,Y,G),""):IY($,X,Y,G)}function J7(W,$,X,Y){return W.fragment=!0,H7(W,W.strings[0],W.args[0],$,X,Y)}function iT(W,$,X,Y,G){return W.map((J)=>"("+Y.map((H)=>Q7("values",J[H],$,X,G)).join(",")+")").join(",")}function lT(W,$,X,Y,G){let J=Array.isArray(W[0]),H=$.length?$.flat():Object.keys(J?W[0]:W);return iT(J?W:[W],X,Y,H,G)}function qY(W,$,X,Y,G){if(typeof W==="string"&&(W=[W].concat($)),Array.isArray(W))return z7(W,G);let J;return($.length?$.flat():Object.keys(W)).map((Q)=>{return J=W[Q],(J instanceof FW?J7(J,X,Y,G):J instanceof E6?J.value:IY(J,X,Y,G))+" as "+PY(G.transform.column.to?G.transform.column.to(Q):Q)}).join(",")}var MO=Object.entries({values:lT,in:(...W)=>{let $=lT(...W);return $==="()"?"(null)":$},select:qY,as:qY,returning:qY,"\\(":qY,update(W,$,X,Y,G){return($.length?$.flat():Object.keys(W)).map((J)=>PY(G.transform.column.to?G.transform.column.to(J):J)+"="+Q7("values",W[J],X,Y,G))},insert(W,$,X,Y,G){let J=$.length?$.flat():Object.keys(Array.isArray(W)?W[0]:W);return"("+z7(J,G)+")values"+iT(Array.isArray(W)?W:[W],X,Y,J,G)}}).map(([W,$])=>[new RegExp("((?:^|[\\s(])"+W+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),$]);function Y7(){throw a0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:OO,parsers:KO}=oT;function nT(W){if(Array.isArray(W))return nT(W[0]);return typeof W==="string"?1009:0}var rT=function(W){let $=tT(W||{});return{serializers:Object.assign({},OO,$.serializers),parsers:Object.assign({},KO,$.parsers)}};function tT(W){return Object.keys(W).reduce(($,X)=>{if(W[X].from&&[].concat(W[X].from).forEach((Y)=>$.parsers[Y]=W[X].parse),W[X].serialize)$.serializers[W[X].to]=W[X].serialize,W[X].from&&[].concat(W[X].from).forEach((Y)=>$.serializers[Y]=W[X].serialize);return $},{parsers:{},serializers:{}})}function z7(W,{transform:{column:$}}){return W.map((X)=>PY($.to?$.to(X):X)).join(",")}var PY=function W($){return'"'+$.replace(/"/g,'""').replace(/\./g,'"."')+'"'},CY=function W($){return $ instanceof pW?$.type:$ instanceof Date?1184:$ instanceof Uint8Array?17:$===!0||$===!1?16:typeof $==="bigint"?20:Array.isArray($)?W($[0]):0},AO=/\\/g,EO=/"/g;function LO(W){return W.replace(AO,"\\\\").replace(EO,"\\\"")}var aT=function W($,X,Y,G){if(Array.isArray($)===!1)return $;if(!$.length)return"{}";let J=$[0],H=G===1020?";":",";if(Array.isArray(J)&&!J.type)return"{"+$.map((Q)=>W(Q,X,Y,G)).join(H)+"}";return"{"+$.map((Q)=>{if(Q===void 0){if(Q=Y.transform.undefined,Q===void 0)throw a0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Q===null?"null":'"'+LO(X?X(Q.type?Q.value:Q):""+Q)+'"'}).join(H)+"}"},G7={i:0,char:null,str:"",quoted:!1,last:0},sT=function W($,X,Y){return G7.i=G7.last=0,eT(G7,$,X,Y)};function eT(W,$,X,Y){let G=[],J=Y===1020?";":",";for(;W.i<$.length;W.i++){if(W.char=$[W.i],W.quoted)if(W.char==="\\")W.str+=$[++W.i];else if(W.char==='"')G.push(X?X(W.str):W.str),W.str="",W.quoted=$[W.i+1]==='"',W.last=W.i+2;else W.str+=W.char;else if(W.char==='"')W.quoted=!0;else if(W.char==="{")W.last=++W.i,G.push(eT(W,$,X,Y));else if(W.char==="}"){W.quoted=!1,W.last<W.i&&G.push(X?X($.slice(W.last,W.i)):$.slice(W.last,W.i)),W.last=W.i+1;break}else if(W.char===J&&W.p!=="}"&&W.p!=='"')G.push(X?X($.slice(W.last,W.i)):$.slice(W.last,W.i)),W.last=W.i+1;W.p=W.char}return W.last<W.i&&G.push(X?X($.slice(W.last,W.i+1)):$.slice(W.last,W.i+1)),G}var E8=(W)=>{let $=W[0];for(let X=1;X<W.length;X++)$+=W[X]==="_"?W[++X].toUpperCase():W[X];return $},L8=(W)=>{let $=W[0].toUpperCase();for(let X=1;X<W.length;X++)$+=W[X]==="_"?W[++X].toUpperCase():W[X];return $},B8=(W)=>W.replace(/_/g,"-"),O6=(W)=>W.replace(/([A-Z])/g,"_$1").toLowerCase(),K6=(W)=>(W.slice(0,1)+W.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),A6=(W)=>W.replace(/-/g,"_");function T7(W){return function $(X,Y){return typeof X==="object"&&X!==null&&(Y.type===114||Y.type===3802)?Array.isArray(X)?X.map((G)=>$(G,Y)):Object.entries(X).reduce((G,[J,H])=>Object.assign(G,{[W(J)]:$(H,Y)}),{}):X}}E8.column={from:E8};E8.value={from:T7(E8)};O6.column={to:O6};var F7={...E8};F7.column.to=O6;L8.column={from:L8};L8.value={from:T7(L8)};K6.column={to:K6};var _7={...L8};_7.column.to=K6;B8.column={from:B8};B8.value={from:T7(B8)};A6.column={to:A6};var w7={...B8};w7.column.to=A6;import WF from"net";import ZO from"tls";import L6 from"crypto";import U7 from"stream";import{performance as $F}from"perf_hooks";class R8 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 WW=BO;function BO(W=[]){let $=W.slice(),X=0;return{get length(){return $.length-X},remove:(Y)=>{let G=$.indexOf(Y);return G===-1?null:($.splice(G,1),Y)},push:(Y)=>($.push(Y),Y),shift:()=>{let Y=$[X++];if(X===$.length)X=0,$=[];else $[X-1]=void 0;return Y}}}var B1=Buffer.allocUnsafe(256),RO="BCcDdEFfHPpQSX".split("").reduce((W,$)=>{let X=$.charCodeAt(0);return W[$]=()=>{return B1[0]=X,S0.i=5,S0},W},{}),S0=Object.assign(NO,RO,{N:String.fromCharCode(0),i:0,inc(W){return S0.i+=W,S0},str(W){let $=Buffer.byteLength(W);return fY($),S0.i+=B1.write(W,S0.i,$,"utf8"),S0},i16(W){return fY(2),B1.writeUInt16BE(W,S0.i),S0.i+=2,S0},i32(W,$){if($||$===0)return B1.writeUInt32BE(W,$),S0;return fY(4),B1.writeUInt32BE(W,S0.i),S0.i+=4,S0},z(W){return fY(W),B1.fill(0,S0.i,S0.i+W),S0.i+=W,S0},raw(W){return B1=Buffer.concat([B1.subarray(0,S0.i),W]),S0.i=B1.length,S0},end(W=1){B1.writeUInt32BE(S0.i-W,W);let $=B1.subarray(0,S0.i);return S0.i=0,B1=Buffer.allocUnsafe(256),$}}),n=S0;function fY(W){if(B1.length-S0.i<W){let $=B1,X=$.length;B1=Buffer.allocUnsafe(X+(X>>1)+W),$.copy(B1)}}function NO(){return S0.i=0,S0}var M7=GF,SO=1,h2=n().S().end(),XF=n().H().end(),qO=n().i32(8).i32(80877103).end(8),CO=Buffer.concat([n().E().str(n.N).i32(0).end(),h2]),kO=n().D().str("S").str(n.N).end(),A4=()=>{},jO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),IO={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 GF(W,$={},{onopen:X=A4,onend:Y=A4,onclose:G=A4}={}){let{ssl:J,max:H,user:Q,host:z,port:T,database:F,parsers:_,transform:w,onnotice:O,onnotify:M,onparameter:A,max_pipeline:I,keep_alive:j,backoff:R,target_session_attrs:Z}=W,P=WW(),h=SO++,x={pid:null,secret:null},m=V7(B9,W.idle_timeout),w0=V7(B9,W.max_lifetime),p0=V7(cU,W.connect_timeout),B=null,V0,$0=new R8,U0=Buffer.alloc(0),e0=W.fetch_types,M1={},VW={},P8=Math.random().toString(36).slice(2),k=1,e=0,N0=0,m0=0,W1=0,F0=0,j0=0,r0=0,u0=null,v0=null,O1=!1,I0=null,MW=null,K1=null,O2=null,$1=null,y0=null,OW=null,IW=null,v=null,u4=null,A1={queue:$.closed,idleTimer:m,connect(U){K1=U||!0,QJ()},terminate:d4,execute:c4,cancel:gU,end:B9,count:0,id:h};return $.closed&&$.closed.push(A1),A1;async function hU(){let U;try{U=W.socket?await Promise.resolve(W.socket(W)):new WF.Socket}catch(K){x8(K);return}return U.on("error",x8),U.on("close",zJ),U.on("drain",JJ),U}async function gU({pid:U,secret:K},t,L0){try{V0=n().i32(16).i32(80877102).i32(U).i32(K).end(16),await HJ(),B.once("error",L0),B.once("close",t)}catch(l0){L0(l0)}}function c4(U){if(O1)return YX(U,a0.connection("CONNECTION_DESTROYED",W));if(U.cancelled)return;try{return U.state=x,v?P.push(U):(v=U,v.active=!0),uU(U),U1(mU(U))&&!U.describeFirst&&!U.cursorFn&&P.length<I&&(!U.options.onexecute||U.options.onexecute(A1))}catch(K){return P.length===0&&U1(h2),PW(K),!0}}function mU(U){if(U.parameters.length>=65534)throw a0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?n().Q().str(U.statement.string+n.N).end():U.describeFirst?Buffer.concat([XJ(U),XF]):U.prepare?U.prepared?XX(U):Buffer.concat([XJ(U),XX(U)]):pU(U)}function XJ(U){return Buffer.concat([FJ(U.statement.string,U.parameters,U.statement.types,U.statement.name),qD("S",U.statement.name)])}function XX(U){return Buffer.concat([SD(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?_J("",U.cursorRows):CO])}function pU(U){return Buffer.concat([FJ(U.statement.string,U.parameters,U.statement.types),kO,XX(U)])}function uU(U){let K=[],t=[],L0=H7(U,U.strings[0],U.args[0],K,t,W);!U.tagged&&U.args.forEach((l0)=>IY(l0,K,t,W)),U.prepare=W.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=L0,U.signature=U.prepare&&t+L0,U.onlyDescribe&&delete VW[U.signature],U.parameters=U.parameters||K,U.prepared=U.prepare&&U.signature in VW,U.describeFirst=U.onlyDescribe||K.length&&!U.prepared,U.statement=U.prepared?VW[U.signature]:{string:L0,types:t,name:U.prepare?P8+k++:""},typeof W.debug==="function"&&W.debug(h,L0,K,t)}function U1(U,K){if(y0=y0?Buffer.concat([y0,U]):Buffer.from(U),K||y0.length>=1024)return YJ(K);return v0===null&&(v0=setImmediate(YJ)),!0}function YJ(U){let K=B.write(y0,U);return v0!==null&&clearImmediate(v0),y0=v0=null,K}function cU(){PW(a0.connection("CONNECT_TIMEOUT",W,B)),B.destroy()}async function GJ(){if(U1(qO),!await new Promise((K)=>B.once("data",(t)=>K(t[0]===83)))&&J==="prefer")return f8();B.removeAllListeners(),B=ZO.connect({socket:B,servername:WF.isIP(B.host)?void 0:B.host,...J==="require"||J==="allow"||J==="prefer"?{rejectUnauthorized:!1}:J==="verify-full"?{}:typeof J==="object"?J:{}}),B.on("secureConnect",f8),B.on("error",x8),B.on("close",zJ),B.on("drain",JJ)}function JJ(){!v&&X(A1)}function L9(U){if(I0){if(I0.push(U),N0-=U.length,N0>=0)return}U0=I0?Buffer.concat(I0,F0-N0):U0.length===0?U:Buffer.concat([U0,U],U0.length+U.length);while(U0.length>4){if(F0=U0.readUInt32BE(1),F0>=U0.length){N0=F0-U0.length,I0=[U0];break}try{dU(U0.subarray(0,F0+1))}catch(K){v&&(v.cursorFn||v.describeFirst)&&U1(h2),PW(K)}U0=U0.subarray(F0+1),N0=0,I0=null}}async function HJ(){if(O1=!1,M1={},B||(B=await hU()),!B)return;if(p0.start(),W.socket)return J?GJ():f8();if(B.on("connect",J?GJ:f8),W.path)return B.connect(W.path);B.ssl=J,B.connect(T[m0],z[m0]),B.host=z[m0],B.port=T[m0],m0=(m0+1)%T.length}function QJ(){setTimeout(HJ,e?e+j0-$F.now():0)}function f8(){try{VW={},e0=W.fetch_types,P8=Math.random().toString(36).slice(2),k=1,w0.start(),B.on("data",L9),j&&B.setKeepAlive&&B.setKeepAlive(!0,1000*j);let U=kD();U1(U)}catch(U){x8(U)}}function x8(U){if(A1.queue===$.connecting&&W.host[W1+1])return;PW(U);while(P.length)YX(P.shift(),U)}function PW(U){$1&&($1.destroy(U),$1=null),v&&YX(v,U),K1&&(YX(K1,U),K1=null)}function YX(U,K){"query"in K||"parameters"in K||Object.defineProperties(K,{stack:{value:K.stack+U.origin.replace(/.*\n/,`
57
+ `),enumerable:W.debug},query:{value:U.string,enumerable:W.debug},parameters:{value:U.parameters,enumerable:W.debug},args:{value:U.args,enumerable:W.debug},types:{value:U.statement&&U.statement.types,enumerable:W.debug}}),U.reject(K)}function B9(){return O2||(!A1.reserved&&Y(A1),!A1.reserved&&!K1&&!v&&P.length===0?(d4(),new Promise((U)=>B&&B.readyState!=="closed"?B.once("close",U):U())):O2=new Promise((U)=>OW=U))}function d4(){if(O1=!0,$1||v||K1||P.length)x8(a0.connection("CONNECTION_DESTROYED",W));if(clearImmediate(v0),B)B.removeListener("data",L9),B.removeListener("connect",f8),B.readyState==="open"&&B.end(n().X().end());OW&&(OW(),O2=OW=null)}async function zJ(U){if(U0=Buffer.alloc(0),N0=0,I0=null,clearImmediate(v0),B.removeListener("data",L9),B.removeListener("connect",f8),m.cancel(),w0.cancel(),p0.cancel(),B.removeAllListeners(),B=null,K1)return QJ();!U&&(v||P.length)&&x8(a0.connection("CONNECTION_CLOSED",W,B)),e=$F.now(),U&&W.shared.retries++,j0=(typeof R==="function"?R(W.shared.retries):R)*1000,G(A1,a0.connection("CONNECTION_CLOSED",W,B))}function dU(U,K=U[0]){(K===68?lU:K===100?KD:K===65?wD:K===83?oU:K===90?iU:K===67?nU:K===50?TJ:K===49?rU:K===116?tU:K===84?aU:K===82?sU:K===110?GD:K===75?JD:K===69?FD:K===115?UD:K===51?DD:K===71?VD:K===78?ED:K===72?MD:K===99?AD:K===73?LD:K===86?BD:K===118?RD:K===87?OD:ND)(U)}function lU(U){let K=7,t,L0,l0,E1=v.isRaw?new Array(v.statement.columns.length):{};for(let Z1=0;Z1<v.statement.columns.length;Z1++)L0=v.statement.columns[Z1],t=U.readInt32BE(K),K+=4,l0=t===-1?null:v.isRaw===!0?U.subarray(K,K+=t):L0.parser===void 0?U.toString("utf8",K,K+=t):L0.parser.array===!0?L0.parser(U.toString("utf8",K+1,K+=t)):L0.parser(U.toString("utf8",K,K+=t)),v.isRaw?E1[Z1]=v.isRaw===!0?l0:w.value.from?w.value.from(l0,L0):l0:E1[L0.name]=w.value.from?w.value.from(l0,L0):l0;v.forEachFn?v.forEachFn(w.row.from?w.row.from(E1):E1,$0):$0[r0++]=w.row.from?w.row.from(E1):E1}function oU(U){let[K,t]=U.toString("utf8",5,U.length-1).split(n.N);if(M1[K]=t,W.parameters[K]!==t)W.parameters[K]=t,A&&A(K,t)}function iU(U){if(v&&v.options.simple&&v.resolve(MW||$0),v=MW=null,$0=new R8,p0.cancel(),K1){if(Z){if(!M1.in_hot_standby||!M1.default_transaction_read_only)return TD();else if(zD(Z,M1))return d4()}if(e0)return K1===!0&&(K1=null),HD();K1!==!0&&c4(K1),W.shared.retries=W1=0,K1=null;return}while(P.length&&(v=P.shift())&&(v.active=!0,v.cancelled))GF(W).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;A1.reserved?!A1.reserved.release&&U[5]===73?O2?d4():(A1.reserved=null,X(A1)):A1.reserved():O2?d4():X(A1)}function nU(U){r0=0;for(let K=U.length-1;K>0;K--){if(U[K]===32&&U[K+1]<58&&$0.count===null)$0.count=+U.toString("utf8",K+1,U.length-1);if(U[K-1]>=65){$0.command=U.toString("utf8",5,K),$0.state=x;break}}if(u4&&(u4(),u4=null),$0.command==="BEGIN"&&H!==1&&!A1.reserved)return PW(a0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return TJ();if(v.cursorFn)$0.count&&v.cursorFn($0),U1(h2);v.resolve($0)}function rU(){v.parsing=!1}function TJ(){!$0.statement&&($0.statement=v.statement),$0.columns=v.statement.columns}function tU(U){let K=U.readUInt16BE(5);for(let t=0;t<K;++t)!v.statement.types[t]&&(v.statement.types[t]=U.readUInt32BE(7+t*4));v.prepare&&(VW[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(U1(XX(v)),v.describeFirst=!1)}function aU(U){if($0.command)MW=MW||[$0],MW.push($0=new R8),$0.count=null,v.statement.columns=null;let K=U.readUInt16BE(5),t=7,L0;v.statement.columns=Array(K);for(let l0=0;l0<K;++l0){L0=t;while(U[t++]!==0);let E1=U.readUInt32BE(t),Z1=U.readUInt16BE(t+4),K2=U.readUInt32BE(t+6);v.statement.columns[l0]={name:w.column.from?w.column.from(U.toString("utf8",L0,t-1)):U.toString("utf8",L0,t-1),parser:_[K2],table:E1,number:Z1,type:K2},t+=18}if($0.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),U1(h2)}async function sU(U,K=U.readUInt32BE(5)){(K===3?eU:K===5?WD:K===10?$D:K===11?XD:K===12?YD:K!==0?ZD:A4)(U,K)}async function eU(){let U=await R9();U1(n().p().str(U).z(1).end())}async function WD(U){let K="md5"+await YF(Buffer.concat([Buffer.from(await YF(await R9()+Q)),U.subarray(9)]));U1(n().p().str(K).z(1).end())}async function $D(){IW=(await L6.randomBytes(18)).toString("base64"),n().p().str("SCRAM-SHA-256"+n.N);let U=n.i;U1(n.inc(4).str("n,,n=*,r="+IW).i32(n.i-U-4,U).end())}async function XD(U){let K=U.toString("utf8",9).split(",").reduce((Z1,K2)=>(Z1[K2[0]]=K2.slice(2),Z1),{}),t=await L6.pbkdf2Sync(await R9(),Buffer.from(K.s,"base64"),parseInt(K.i),32,"sha256"),L0=await xY(t,"Client Key"),l0="n=*,r="+IW+",r="+K.r+",s="+K.s+",i="+K.i+",c=biws,r="+K.r;u0=(await xY(await xY(t,"Server Key"),l0)).toString("base64");let E1="c=biws,r="+K.r+",p="+fO(L0,Buffer.from(await xY(await PO(L0),l0))).toString("base64");U1(n().p().str(E1).end())}function YD(U){if(U.toString("utf8",9).split(n.N,1)[0].slice(2)===u0)return;PW(a0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),B.destroy()}function R9(){return Promise.resolve(typeof W.pass==="function"?W.pass():W.pass)}function GD(){if($0.statement=v.statement,$0.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),U1(h2)}function JD(U){x.pid=U.readUInt32BE(5),x.secret=U.readUInt32BE(9)}async function HD(){e0=!1,(await new FW([`
58
58
  select b.oid, b.typarray
59
59
  from pg_catalog.pg_type a
60
60
  left join pg_catalog.pg_type b on b.oid = a.typelem
61
61
  where a.typcategory = 'A'
62
62
  group by b.oid, b.typarray
63
63
  order by b.oid
64
- `],[],p$)).forEach(({oid:O,typarray:t})=>GD(O,t))}function GD(w,O){if(!!W.parsers[O]&&!!W.serializers[O])return;let t=W.parsers[w];W.shared.typeArrayMap[w]=O,W.parsers[O]=(L0)=>tF(L0,t,O),W.parsers[O].array=!0,W.serializers[O]=(L0)=>rF(L0,W.serializers[w],W,O)}function HD(w,O){return w==="read-write"&&O.default_transaction_read_only==="on"||w==="read-only"&&O.default_transaction_read_only==="off"||w==="primary"&&O.in_hot_standby==="on"||w==="standby"&&O.in_hot_standby==="off"||w==="prefer-standby"&&O.in_hot_standby==="off"&&W.host[W1]}function QD(){let w=new FW([`
64
+ `],[],c4)).forEach(({oid:K,typarray:t})=>QD(K,t))}function QD(U,K){if(!!W.parsers[K]&&!!W.serializers[K])return;let t=W.parsers[U];W.shared.typeArrayMap[U]=K,W.parsers[K]=(L0)=>sT(L0,t,K),W.parsers[K].array=!0,W.serializers[K]=(L0)=>aT(L0,W.serializers[U],W,K)}function zD(U,K){return U==="read-write"&&K.default_transaction_read_only==="on"||U==="read-only"&&K.default_transaction_read_only==="off"||U==="primary"&&K.in_hot_standby==="on"||U==="standby"&&K.in_hot_standby==="off"||U==="prefer-standby"&&K.in_hot_standby==="off"&&W.host[W1]}function TD(){let U=new FW([`
65
65
  show transaction_read_only;
66
66
  select pg_catalog.pg_is_in_recovery()
67
- `],[],p$,null,{simple:!0});w.resolve=([[O],[t]])=>{V1.default_transaction_read_only=O.transaction_read_only,V1.in_hot_standby=t.pg_is_in_recovery?"on":"off"},w.execute()}function zD(w){x&&(x.cursorFn||x.describeFirst)&&_1(v2);let O=a0.postgres(w5(w));x&&x.retried?IW(x.retried):x&&x.prepared&&CO.has(O.routine)?FD(x,O):IW(O)}function FD(w,O){delete DW[w.signature],w.retried=O,p$(w)}function TD(w){if(!K)return;let O=9;while(w[O++]!==0);K(w.toString("utf8",9,O-1),w.toString("utf8",O,w.length-1))}async function UD(){try{let w=await Promise.resolve(x.cursorFn(W0));r0=0,w===M$?_1(SD(x.portal)):(W0=new E8,_1(FG("",x.cursorRows)))}catch(w){_1(v2),x.reject(w)}}function wD(){W0.count&&x.cursorFn(W0),x.resolve(W0)}function _D(){$1=new U5.Writable({autoDestroy:!0,write(w,O,t){L.write(n().d().raw(w).end(),t)},destroy(w,O){O(w),L.write(n().f().str(w+n.N).end()),$1=null},final(w){L.write(n().c().end()),m$=w}}),x.resolve($1)}function DD(){$1=new U5.Readable({read(){L.resume()}}),x.resolve($1)}function MD(){$1=new U5.Duplex({autoDestroy:!0,read(){L.resume()},write(w,O,t){L.write(n().d().raw(w).end(),t)},destroy(w,O){O(w),L.write(n().f().str(w+n.N).end()),$1=null},final(w){L.write(n().c().end()),m$=w}}),x.resolve($1)}function VD(w){$1&&($1.push(w.subarray(5))||L.pause())}function OD(){$1&&$1.push(null),$1=null}function KD(w){V?V(w5(w)):console.log(w5(w))}function AD(){}function ED(){IW(a0.notSupported("FunctionCallResponse"))}function LD(){IW(a0.notSupported("NegotiateProtocolVersion"))}function BD(w){console.error("Postgres.js : Unknown Message:",w[0])}function RD(w,O){console.error("Postgres.js : Unknown Auth:",O)}function ND(w,O,t="",L0=""){let l0,E1;return n().B().str(L0+n.N).str(t+n.N).i16(0).i16(w.length),w.forEach((Z1,K2)=>{if(Z1===null)return n.i32(4294967295);E1=O[K2],w[K2]=Z1=E1 in W.serializers?W.serializers[E1](Z1):""+Z1,l0=n.i,n.inc(4).str(Z1).i32(n.i-l0-4,l0)}),n.i16(0),n.end()}function zG(w,O,t,L0=""){return n().P().str(L0+n.N).str(w+n.N).i16(O.length),O.forEach((l0,E1)=>n.i32(t[E1]||0)),n.end()}function ZD(w,O=""){return n().D().str(w).str(O+n.N).end()}function FG(w="",O=0){return Buffer.concat([n().E().str(w+n.N).i32(O).end(),WT])}function SD(w=""){return Buffer.concat([n().C().str("P").str(w+n.N).end(),n().S().end()])}function qD(){return M0||n().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:Q,database:T,client_encoding:"UTF8"},W.connection)).filter(([,w])=>w).map(([w,O])=>w+n.N+O).join(n.N)).z(2).end(0)}}function w5(W){let $={},X=5;for(let Y=5;Y<W.length-1;Y++)if(W[Y]===0)$[kO[W[X]]]=W.toString("utf8",X+1,Y),X=Y+1;return $}function $T(W){return A6.createHash("md5").update(W).digest("hex")}function xY(W,$){return A6.createHmac("sha256",W).update($).digest()}function jO(W){return A6.createHash("sha256").update(W).digest()}function IO(W,$){let X=Math.max(W.length,$.length),Y=Buffer.allocUnsafe(X);for(let J=0;J<X;J++)Y[J]=W[J]^$[J];return Y}function _5(W,$){if($=typeof $==="function"?$():$,!$)return{cancel:O$,start:O$};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(Y,$*1000,arguments)}};function Y(J){W.apply(null,J),X=null}}var YT=()=>{};function M5(W,$){let X=new Map,Y="postgresjs_"+Math.random().toString(36).slice(2),J={},G,H,Q=!1,z=U.sql=W({...$,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...$.connection,replication:"database"},onclose:async function(){if(Q)return;H=null,J.pid=J.secret=void 0,_(await V(z,Y,$.publications)),X.forEach((B)=>B.forEach(({onsubscribe:I})=>I()))},no_subscribe:!0}),F=z.end,T=z.close;return z.end=async()=>{return Q=!0,H&&await new Promise((B)=>(H.once("close",B),H.end())),F()},z.close=async()=>{return H&&await new Promise((B)=>(H.once("close",B),H.end())),T()},U;async function U(B,I,C=YT,R=YT){if(B=xO(B),!G)G=V(z,Y,$.publications);let q={fn:I,onsubscribe:C},m=X.has(B)?X.get(B).add(q):X.set(B,new Set([q])).get(B),c=()=>{m.delete(q),m.size===0&&X.delete(B)};return G.then((v)=>{return _(v),C(),H&&H.on("error",R),{unsubscribe:c,state:J,sql:z}})}function _(B){H=B.stream,J.pid=B.state.pid,J.secret=B.state.secret}async function V(B,I,C){if(!C)throw new Error("Missing publication names");let R=await B.unsafe(`CREATE_REPLICATION_SLOT ${I} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[q]=R,m=await B.unsafe(`START_REPLICATION SLOT ${I} LOGICAL ${q.consistent_point} (proto_version '1', publication_names '${C}')`).writable(),c={lsn:Buffer.concat(q.consistent_point.split("/").map((L)=>Buffer.from(("00000000"+L).slice(-8),"hex")))};return m.on("data",h),m.on("error",v),m.on("close",B.close),{stream:m,state:R.state};function v(L){console.error("Unexpected error during logical streaming - reconnecting",L)}function h(L){if(L[0]===119)PO(L.subarray(25),c,B.options.parsers,w0,$.transform);else if(L[0]===107&&L[17])c.lsn=L.subarray(1,9),p0()}function w0(L,M0){let W0=M0.relation.schema+"."+M0.relation.table;K("*",L,M0),K("*:"+W0,L,M0),M0.relation.keys.length&&K("*:"+W0+"="+M0.relation.keys.map((_0)=>L[_0.name]),L,M0),K(M0.command,L,M0),K(M0.command+":"+W0,L,M0),M0.relation.keys.length&&K(M0.command+":"+W0+"="+M0.relation.keys.map((_0)=>L[_0.name]),L,M0)}function p0(){let L=Buffer.alloc(34);L[0]=114,L.fill(c.lsn,1),L.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),m.write(L)}}function K(B,I,C){X.has(B)&&X.get(B).forEach(({fn:R})=>R(I,C,B))}}function fO(W){return new Date(Date.UTC(2000,0,1)+Number(W/BigInt(1000)))}function PO(W,$,X,Y,J){let G=(H,[Q,z])=>(H[Q.charCodeAt(0)]=z,H);Object.entries({R:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)]={schema:H.toString("utf8",Q+=4,Q=H.indexOf(0,Q))||"pg_catalog",table:H.toString("utf8",Q+1,Q=H.indexOf(0,Q+1)),columns:Array(H.readUInt16BE(Q+=2)),keys:[]};Q+=2;let F=0,T;while(Q<H.length)T=z.columns[F++]={key:H[Q++],name:J.column.from?J.column.from(H.toString("utf8",Q,Q=H.indexOf(0,Q))):H.toString("utf8",Q,Q=H.indexOf(0,Q)),type:H.readUInt32BE(Q+=1),parser:X[H.readUInt32BE(Q)],atttypmod:H.readUInt32BE(Q+=4)},T.key&&z.keys.push(T),Q+=4},Y:()=>{},O:()=>{},B:(H)=>{$.date=fO(H.readBigInt64BE(9)),$.lsn=H.subarray(1,9)},I:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)],{row:F}=vY(H,z.columns,Q+=7,J);Y(F,{command:"insert",relation:z})},D:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)];Q+=4;let F=H[Q]===75;Y(F||H[Q]===79?vY(H,z.columns,Q+=3,J).row:null,{command:"delete",relation:z,key:F})},U:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)];Q+=4;let F=H[Q]===75,T=F||H[Q]===79?vY(H,z.columns,Q+=3,J):null;T&&(Q=T.i);let{row:U}=vY(H,z.columns,Q+3,J);Y(U,{command:"update",relation:z,key:F,old:T&&T.row})},T:()=>{},C:()=>{}}).reduce(G,{})[W[0]](W)}function vY(W,$,X,Y){let J,G,H,Q=Y.raw?new Array($.length):{};for(let z=0;z<$.length;z++)J=W[X++],G=$[z],H=J===110?null:J===117?void 0:G.parser===void 0?W.toString("utf8",X+4,X+=4+W.readUInt32BE(X)):G.parser.array===!0?G.parser(W.toString("utf8",X+5,X+=4+W.readUInt32BE(X))):G.parser(W.toString("utf8",X+4,X+=4+W.readUInt32BE(X))),Y.raw?Q[z]=Y.raw===!0?H:Y.value.from?Y.value.from(H,G):H:Q[G.name]=Y.value.from?Y.value.from(H,G):H;return{i:X,row:Y.row.from?Y.row.from(Q):Q}}function xO(W){let $=W.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!$)throw new Error("Malformed subscribe pattern: "+W);let[,X,Y,J]=$;return(X||"*")+(Y?":"+(Y.indexOf(".")===-1?"public."+Y:Y):"")+(J?"="+J:"")}import JT from"stream";function V5(W,$,X=393216){return new Promise(async(Y,J)=>{await W.begin(async(G)=>{let H;!$&&([{oid:$}]=await G`select lo_creat(-1) as oid`);let[{fd:Q}]=await G`select lo_open(${$}, ${X}) as fd`,z={writable:T,readable:F,close:()=>G`select lo_close(${Q})`.then(H),tell:()=>G`select lo_tell64(${Q})`,read:(U)=>G`select loread(${Q}, ${U}) as data`,write:(U)=>G`select lowrite(${Q}, ${U})`,truncate:(U)=>G`select lo_truncate64(${Q}, ${U})`,seek:(U,_=0)=>G`select lo_lseek64(${Q}, ${U}, ${_})`,size:()=>G`
67
+ `],[],c4,null,{simple:!0});U.resolve=([[K],[t]])=>{M1.default_transaction_read_only=K.transaction_read_only,M1.in_hot_standby=t.pg_is_in_recovery?"on":"off"},U.execute()}function FD(U){v&&(v.cursorFn||v.describeFirst)&&U1(h2);let K=a0.postgres(D7(U));v&&v.retried?PW(v.retried):v&&v.prepared&&jO.has(K.routine)?_D(v,K):PW(K)}function _D(U,K){delete VW[U.signature],U.retried=K,c4(U)}function wD(U){if(!M)return;let K=9;while(U[K++]!==0);M(U.toString("utf8",9,K-1),U.toString("utf8",K,U.length-1))}async function UD(){try{let U=await Promise.resolve(v.cursorFn($0));r0=0,U===O4?U1(CD(v.portal)):($0=new R8,U1(_J("",v.cursorRows)))}catch(U){U1(h2),v.reject(U)}}function DD(){$0.count&&v.cursorFn($0),v.resolve($0)}function VD(){$1=new U7.Writable({autoDestroy:!0,write(U,K,t){B.write(n().d().raw(U).end(),t)},destroy(U,K){K(U),B.write(n().f().str(U+n.N).end()),$1=null},final(U){B.write(n().c().end()),u4=U}}),v.resolve($1)}function MD(){$1=new U7.Readable({read(){B.resume()}}),v.resolve($1)}function OD(){$1=new U7.Duplex({autoDestroy:!0,read(){B.resume()},write(U,K,t){B.write(n().d().raw(U).end(),t)},destroy(U,K){K(U),B.write(n().f().str(U+n.N).end()),$1=null},final(U){B.write(n().c().end()),u4=U}}),v.resolve($1)}function KD(U){$1&&($1.push(U.subarray(5))||B.pause())}function AD(){$1&&$1.push(null),$1=null}function ED(U){O?O(D7(U)):console.log(D7(U))}function LD(){}function BD(){PW(a0.notSupported("FunctionCallResponse"))}function RD(){PW(a0.notSupported("NegotiateProtocolVersion"))}function ND(U){console.error("Postgres.js : Unknown Message:",U[0])}function ZD(U,K){console.error("Postgres.js : Unknown Auth:",K)}function SD(U,K,t="",L0=""){let l0,E1;return n().B().str(L0+n.N).str(t+n.N).i16(0).i16(U.length),U.forEach((Z1,K2)=>{if(Z1===null)return n.i32(4294967295);E1=K[K2],U[K2]=Z1=E1 in W.serializers?W.serializers[E1](Z1):""+Z1,l0=n.i,n.inc(4).str(Z1).i32(n.i-l0-4,l0)}),n.i16(0),n.end()}function FJ(U,K,t,L0=""){return n().P().str(L0+n.N).str(U+n.N).i16(K.length),K.forEach((l0,E1)=>n.i32(t[E1]||0)),n.end()}function qD(U,K=""){return n().D().str(U).str(K+n.N).end()}function _J(U="",K=0){return Buffer.concat([n().E().str(U+n.N).i32(K).end(),XF])}function CD(U=""){return Buffer.concat([n().C().str("P").str(U+n.N).end(),n().S().end()])}function kD(){return V0||n().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:Q,database:F,client_encoding:"UTF8"},W.connection)).filter(([,U])=>U).map(([U,K])=>U+n.N+K).join(n.N)).z(2).end(0)}}function D7(W){let $={},X=5;for(let Y=5;Y<W.length-1;Y++)if(W[Y]===0)$[IO[W[X]]]=W.toString("utf8",X+1,Y),X=Y+1;return $}function YF(W){return L6.createHash("md5").update(W).digest("hex")}function xY(W,$){return L6.createHmac("sha256",W).update($).digest()}function PO(W){return L6.createHash("sha256").update(W).digest()}function fO(W,$){let X=Math.max(W.length,$.length),Y=Buffer.allocUnsafe(X);for(let G=0;G<X;G++)Y[G]=W[G]^$[G];return Y}function V7(W,$){if($=typeof $==="function"?$():$,!$)return{cancel:A4,start:A4};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(Y,$*1000,arguments)}};function Y(G){W.apply(null,G),X=null}}var JF=()=>{};function O7(W,$){let X=new Map,Y="postgresjs_"+Math.random().toString(36).slice(2),G={},J,H,Q=!1,z=_.sql=W({...$,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...$.connection,replication:"database"},onclose:async function(){if(Q)return;H=null,G.pid=G.secret=void 0,w(await O(z,Y,$.publications)),X.forEach((A)=>A.forEach(({onsubscribe:I})=>I()))},no_subscribe:!0}),T=z.end,F=z.close;return z.end=async()=>{return Q=!0,H&&await new Promise((A)=>(H.once("close",A),H.end())),T()},z.close=async()=>{return H&&await new Promise((A)=>(H.once("close",A),H.end())),F()},_;async function _(A,I,j=JF,R=JF){if(A=vO(A),!J)J=O(z,Y,$.publications);let Z={fn:I,onsubscribe:j},P=X.has(A)?X.get(A).add(Z):X.set(A,new Set([Z])).get(A),h=()=>{P.delete(Z),P.size===0&&X.delete(A)};return J.then((x)=>{return w(x),j(),H&&H.on("error",R),{unsubscribe:h,state:G,sql:z}})}function w(A){H=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function O(A,I,j){if(!j)throw new Error("Missing publication names");let R=await A.unsafe(`CREATE_REPLICATION_SLOT ${I} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[Z]=R,P=await A.unsafe(`START_REPLICATION SLOT ${I} LOGICAL ${Z.consistent_point} (proto_version '1', publication_names '${j}')`).writable(),h={lsn:Buffer.concat(Z.consistent_point.split("/").map((B)=>Buffer.from(("00000000"+B).slice(-8),"hex")))};return P.on("data",m),P.on("error",x),P.on("close",A.close),{stream:P,state:R.state};function x(B){console.error("Unexpected error during logical streaming - reconnecting",B)}function m(B){if(B[0]===119)bO(B.subarray(25),h,A.options.parsers,w0,$.transform);else if(B[0]===107&&B[17])h.lsn=B.subarray(1,9),p0()}function w0(B,V0){let $0=V0.relation.schema+"."+V0.relation.table;M("*",B,V0),M("*:"+$0,B,V0),V0.relation.keys.length&&M("*:"+$0+"="+V0.relation.keys.map((U0)=>B[U0.name]),B,V0),M(V0.command,B,V0),M(V0.command+":"+$0,B,V0),V0.relation.keys.length&&M(V0.command+":"+$0+"="+V0.relation.keys.map((U0)=>B[U0.name]),B,V0)}function p0(){let B=Buffer.alloc(34);B[0]=114,B.fill(h.lsn,1),B.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),P.write(B)}}function M(A,I,j){X.has(A)&&X.get(A).forEach(({fn:R})=>R(I,j,A))}}function xO(W){return new Date(Date.UTC(2000,0,1)+Number(W/BigInt(1000)))}function bO(W,$,X,Y,G){let J=(H,[Q,z])=>(H[Q.charCodeAt(0)]=z,H);Object.entries({R:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)]={schema:H.toString("utf8",Q+=4,Q=H.indexOf(0,Q))||"pg_catalog",table:H.toString("utf8",Q+1,Q=H.indexOf(0,Q+1)),columns:Array(H.readUInt16BE(Q+=2)),keys:[]};Q+=2;let T=0,F;while(Q<H.length)F=z.columns[T++]={key:H[Q++],name:G.column.from?G.column.from(H.toString("utf8",Q,Q=H.indexOf(0,Q))):H.toString("utf8",Q,Q=H.indexOf(0,Q)),type:H.readUInt32BE(Q+=1),parser:X[H.readUInt32BE(Q)],atttypmod:H.readUInt32BE(Q+=4)},F.key&&z.keys.push(F),Q+=4},Y:()=>{},O:()=>{},B:(H)=>{$.date=xO(H.readBigInt64BE(9)),$.lsn=H.subarray(1,9)},I:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)],{row:T}=bY(H,z.columns,Q+=7,G);Y(T,{command:"insert",relation:z})},D:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)];Q+=4;let T=H[Q]===75;Y(T||H[Q]===79?bY(H,z.columns,Q+=3,G).row:null,{command:"delete",relation:z,key:T})},U:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)];Q+=4;let T=H[Q]===75,F=T||H[Q]===79?bY(H,z.columns,Q+=3,G):null;F&&(Q=F.i);let{row:_}=bY(H,z.columns,Q+3,G);Y(_,{command:"update",relation:z,key:T,old:F&&F.row})},T:()=>{},C:()=>{}}).reduce(J,{})[W[0]](W)}function bY(W,$,X,Y){let G,J,H,Q=Y.raw?new Array($.length):{};for(let z=0;z<$.length;z++)G=W[X++],J=$[z],H=G===110?null:G===117?void 0:J.parser===void 0?W.toString("utf8",X+4,X+=4+W.readUInt32BE(X)):J.parser.array===!0?J.parser(W.toString("utf8",X+5,X+=4+W.readUInt32BE(X))):J.parser(W.toString("utf8",X+4,X+=4+W.readUInt32BE(X))),Y.raw?Q[z]=Y.raw===!0?H:Y.value.from?Y.value.from(H,J):H:Q[J.name]=Y.value.from?Y.value.from(H,J):H;return{i:X,row:Y.row.from?Y.row.from(Q):Q}}function vO(W){let $=W.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!$)throw new Error("Malformed subscribe pattern: "+W);let[,X,Y,G]=$;return(X||"*")+(Y?":"+(Y.indexOf(".")===-1?"public."+Y:Y):"")+(G?"="+G:"")}import HF from"stream";function K7(W,$,X=393216){return new Promise(async(Y,G)=>{await W.begin(async(J)=>{let H;!$&&([{oid:$}]=await J`select lo_creat(-1) as oid`);let[{fd:Q}]=await J`select lo_open(${$}, ${X}) as fd`,z={writable:F,readable:T,close:()=>J`select lo_close(${Q})`.then(H),tell:()=>J`select lo_tell64(${Q})`,read:(_)=>J`select loread(${Q}, ${_}) as data`,write:(_)=>J`select lowrite(${Q}, ${_})`,truncate:(_)=>J`select lo_truncate64(${Q}, ${_})`,seek:(_,w=0)=>J`select lo_lseek64(${Q}, ${_}, ${w})`,size:()=>J`
68
68
  select
69
69
  lo_lseek64(${Q}, location, 0) as position,
70
70
  seek.size
@@ -74,62 +74,62 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
74
74
  tell.location
75
75
  from (select lo_tell64($1) as location) tell
76
76
  ) seek
77
- `};return Y(z),new Promise(async(U)=>H=U);async function F({highWaterMark:U=16384,start:_=0,end:V=1/0}={}){let K=V-_;return _&&await z.seek(_),new JT.Readable({highWaterMark:U,async read(B){let I=B>K?B-K:B;K-=B;let[{data:C}]=await z.read(I);if(this.push(C),C.length<B)this.push(null)}})}async function T({highWaterMark:U=16384,start:_=0}={}){return _&&await z.seek(_),new JT.Writable({highWaterMark:U,write(V,K,B){z.write(V).then(()=>B(),B)}})}}).catch(J)})}Object.assign(bY,{PostgresError:V$,toPascal:K8,pascal:F5,toCamel:O8,camel:z5,toKebab:A8,kebab:T5,fromPascal:V6,fromCamel:M6,fromKebab:O6,BigInt:{to:20,from:[20],parse:(W)=>BigInt(W),serialize:(W)=>W.toString()}});var K$=bY;function bY(W,$){let X=yO(W,$),Y=X.no_subscribe||M5(bY,{...X}),J=!1,G=e1(),H=e1(),Q=e1(),z=e1(),F=e1(),T=e1(),U=e1(),_=e1(),V={connecting:H,reserved:Q,closed:z,ended:F,open:T,busy:U,full:_},K=[...Array(X.max)].map(()=>D5(X,V,{onopen:DW,onend:V1,onclose:k8})),B=I(w0);return Object.assign(B,{get parameters(){return X.parameters},largeObject:V5.bind(null,B),subscribe:Y,CLOSE:M$,END:M$,PostgresError:V$,options:X,reserve:q,listen:C,begin:m,close:W0,end:M0}),B;function I(j){return j.debug=X.debug,Object.entries(X.types).reduce((T0,[j0,r0])=>{return T0[j0]=(u0)=>new pW(u0,r0.to),T0},s),Object.assign(R0,{types:s,typed:s,unsafe:m0,notify:R,array:h,json:v,file:W1}),R0;function s(T0,j0){return new pW(T0,j0)}function R0(T0,...j0){return T0&&Array.isArray(T0.raw)?new FW(T0,j0,j,L):typeof T0==="string"&&!j0.length?new K6(X.transform.column.to?X.transform.column.to(T0):T0):new jY(T0,j0)}function m0(T0,j0=[],r0={}){return arguments.length===2&&!Array.isArray(j0)&&(r0=j0,j0=[]),new FW([T0],j0,j,L,{prepare:!1,...r0,simple:"simple"in r0?r0.simple:j0.length===0})}function W1(T0,j0=[],r0={}){return arguments.length===2&&!Array.isArray(j0)&&(r0=j0,j0=[]),new FW([],j0,(b0)=>{bO.readFile(T0,"utf8",(O1,I0)=>{if(O1)return b0.reject(O1);b0.strings=[I0],j(b0)})},L,{...r0,simple:"simple"in r0?r0.simple:j0.length===0})}}async function C(j,s,R0){let m0={fn:s,onlisten:R0},W1=C.sql||(C.sql=bY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(C.channels).forEach(([b0,{listeners:O1}])=>{delete C.channels[b0],Promise.all(O1.map((I0)=>C(b0,I0.fn,I0.onlisten).catch(()=>{})))})},onnotify(b0,O1){b0 in C.channels&&C.channels[b0].listeners.forEach((I0)=>I0.fn(O1))}})),T0=C.channels||(C.channels={});if(j in T0){T0[j].listeners.push(m0);let b0=await T0[j].result;return m0.onlisten&&m0.onlisten(),{state:b0.state,unlisten:u0}}T0[j]={result:W1`listen ${W1.unsafe('"'+j.replace(/"/g,'""')+'"')}`,listeners:[m0]};let r0=await T0[j].result;return m0.onlisten&&m0.onlisten(),{state:r0.state,unlisten:u0};async function u0(){if(j in T0===!1)return;if(T0[j].listeners=T0[j].listeners.filter((b0)=>b0!==m0),T0[j].listeners.length)return;return delete T0[j],W1`unlisten ${W1.unsafe('"'+j.replace(/"/g,'""')+'"')}`}}async function R(j,s){return await B`select pg_notify(${j}, ${""+s})`}async function q(){let j=e1(),s=T.length?T.shift():await new Promise((W1)=>{G.push({reserve:W1}),z.length&&e0(z.shift())});c(s,Q),s.reserved=()=>j.length?s.execute(j.shift()):c(s,Q),s.reserved.release=!0;let R0=I(m0);return R0.release=()=>{s.reserved=null,DW(s)},R0;function m0(W1){s.queue===_?j.push(W1):s.execute(W1)||c(s,_)}}async function m(j,s){!s&&(s=j,j="");let R0=e1(),m0=0,W1,T0=null;try{return await B.unsafe("begin "+j.replace(/[^a-z ]/ig,""),[],{onexecute:r0}).execute(),await Promise.race([j0(W1,s),new Promise((u0,b0)=>W1.onclose=b0)])}catch(u0){throw u0}async function j0(u0,b0,O1){let I0=I($1);I0.savepoint=O2,I0.prepare=(y0)=>T0=y0.replace(/[^a-z0-9$-_. ]/gi);let MW,K1;O1&&await I0`savepoint ${I0(O1)}`;try{if(K1=await new Promise((y0,VW)=>{let jW=b0(I0);Promise.resolve(Array.isArray(jW)?Promise.all(jW):jW).then(y0,VW)}),MW)throw MW}catch(y0){throw await(O1?I0`rollback to ${I0(O1)}`:I0`rollback`),y0 instanceof V$&&y0.code==="25P02"&&MW||y0}if(!O1)T0?await I0`prepare transaction '${I0.unsafe(T0)}'`:await I0`commit`;return K1;function O2(y0,VW){if(y0&&Array.isArray(y0.raw))return O2((jW)=>jW.apply(jW,arguments));return arguments.length===1&&(VW=y0,y0=null),j0(u0,VW,"s"+m0+++(y0?"_"+y0:""))}function $1(y0){y0.catch((VW)=>MW||(MW=VW)),u0.queue===_?R0.push(y0):u0.execute(y0)||c(u0,_)}}function r0(u0){W1=u0,c(u0,Q),u0.reserved=()=>R0.length?u0.execute(R0.shift()):c(u0,Q)}}function c(j,s){return j.queue.remove(j),s.push(j),j.queue=s,s===T?j.idleTimer.start():j.idleTimer.cancel(),j}function v(j){return new pW(j,3802)}function h(j,s){if(!Array.isArray(j))return h(Array.from(arguments));return new pW(j,s||(j.length?CY(j)||25:0),X.shared.typeArrayMap)}function w0(j){if(J)return j.reject(a0.connection("CONNECTION_ENDED",X,X));if(T.length)return p0(T.shift(),j);if(z.length)return e0(z.shift(),j);U.length?p0(U.shift(),j):G.push(j)}function p0(j,s){return j.execute(s)?c(j,U):c(j,_)}function L(j){return new Promise((s,R0)=>{j.state?j.active?D5(X).cancel(j.state,s,R0):j.cancelled={resolve:s,reject:R0}:(G.remove(j),j.cancelled=!0,j.reject(a0.generic("57014","canceling statement due to user request")),s())})}async function M0({timeout:j=null}={}){if(J)return J;await 1;let s;return J=Promise.race([new Promise((R0)=>j!==null&&(s=setTimeout(_0,j*1000,R0))),Promise.all(K.map((R0)=>R0.end()).concat(C.sql?C.sql.end({timeout:0}):[],Y.sql?Y.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(s))}async function W0(){await Promise.all(K.map((j)=>j.end()))}async function _0(j){await Promise.all(K.map((s)=>s.terminate()));while(G.length)G.shift().reject(a0.connection("CONNECTION_DESTROYED",X));j()}function e0(j,s){return c(j,H),j.connect(s),j}function V1(j){c(j,F)}function DW(j){if(G.length===0)return c(j,T);let s=Math.ceil(G.length/(H.length+1)),R0=!0;while(R0&&G.length&&s-- >0){let m0=G.shift();if(m0.reserve)return m0.reserve(j);R0=j.execute(m0)}R0?c(j,U):c(j,_)}function k8(j,s){c(j,z),j.reserved=null,j.onclose&&(j.onclose(s),j.onclose=null),X.onclose&&X.onclose(j.id),G.length&&e0(j,G.shift())}}function yO(W,$){if(W&&W.shared)return W;let X=process.env,Y=(!W||typeof W==="string"?$:W)||{},{url:J,multihost:G}=uO(W),H=[...J.searchParams].reduce((_,[V,K])=>(_[V]=K,_),{}),Q=Y.hostname||Y.host||G||J.hostname||X.PGHOST||"localhost",z=Y.port||J.port||X.PGPORT||5432,F=Y.user||Y.username||J.username||X.PGUSERNAME||X.PGUSER||cO();Y.no_prepare&&(Y.prepare=!1),H.sslmode&&(H.ssl=H.sslmode,delete H.sslmode),"timeout"in Y&&(console.log("The timeout option is deprecated, use idle_timeout instead"),Y.idle_timeout=Y.timeout),H.sslrootcert==="system"&&(H.ssl="verify-full");let T=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],U={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:mO,max_pipeline:100,backoff:gO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Q)?Q:Q.split(",").map((_)=>_.split(":")[0]),port:Array.isArray(z)?z:Q.split(",").map((_)=>parseInt(_.split(":")[1]||z)),path:Y.path||Q.indexOf("/")>-1&&Q+"/.s.PGSQL."+z,database:Y.database||Y.db||(J.pathname||"").slice(1)||X.PGDATABASE||F,user:F,pass:Y.pass||Y.password||J.password||X.PGPASSWORD||"",...Object.entries(U).reduce((_,[V,K])=>{let B=V in Y?Y[V]:(V in H)?H[V]==="disable"||H[V]==="false"?!1:H[V]:X["PG"+V.toUpperCase()]||K;return _[V]=typeof B==="string"&&T.includes(V)?+B:B,_},{}),connection:{application_name:"postgres.js",...Y.connection,...Object.entries(H).reduce((_,[V,K])=>((V in U)||(_[V]=K),_),{})},types:Y.types||{},target_session_attrs:hO(Y,J,X),onnotice:Y.onnotice,onnotify:Y.onnotify,onclose:Y.onclose,onparameter:Y.onparameter,socket:Y.socket,transform:pO(Y.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...iF(Y.types)}}function hO(W,$,X){let Y=W.target_session_attrs||$.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!Y||["read-write","read-only","primary","standby","prefer-standby"].includes(Y))return Y;throw new Error("target_session_attrs "+Y+" is not supported")}function gO(W){return(0.5+Math.random()/2)*Math.min(3**W/100,20)}function mO(){return 60*(30+Math.random()*30)}function pO(W){return{undefined:W.undefined,column:{from:typeof W.column==="function"?W.column:W.column&&W.column.from,to:W.column&&W.column.to},value:{from:typeof W.value==="function"?W.value:W.value&&W.value.from,to:W.value&&W.value.to},row:{from:typeof W.row==="function"?W.row:W.row&&W.row.from,to:W.row&&W.row.to}}}function uO(W){if(!W||typeof W!=="string")return{url:{searchParams:new Map}};let $=W;$=$.slice($.indexOf("://")+3).split(/[?/]/)[0],$=decodeURIComponent($.slice($.indexOf("@")+1));let X=new URL(W.replace($,$.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:$.indexOf(",")>-1&&$}}function cO(){try{return vO.userInfo().username}catch(W){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class n0{static[D]="SelectionProxyHandler";config;constructor(W){this.config={...W}}get(W,$){if($==="_")return{...W._,selectedFields:new Proxy(W._.selectedFields,this)};if($===P0)return{...W[P0],selectedFields:new Proxy(W[P0].selectedFields,this)};if(typeof $==="symbol")return W[$];let Y=(E(W,H1)?W._.selectedFields:E(W,h1)?W[P0].selectedFields:W)[$];if(E(Y,g.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!Y.isSelectionField)return Y.sql;let J=Y.clone();return J.isSelectionField=!0,J}if(E(Y,g)){if(this.config.sqlBehavior==="sql")return Y;throw new Error(`You tried to reference "${$}" 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(E(Y,q0)){if(this.config.alias)return new Proxy(Y,new D$(new Proxy(Y.table,new Q6(this.config.alias,this.config.replaceOriginalName??!1))));return Y}if(typeof Y!=="object"||Y===null)return Y;return new Proxy(Y,new n0(this.config))}}class yY extends k1{constructor(W,$,X,Y){super();this.session=$,this.dialect=X,this.config={table:W,withList:Y}}static[D]="PgDelete";config;where(W){return this.config.where=W,this}returning(W=this.config.table[y.Symbol.Columns]){return this.config.returningFields=W,this.config.returning=QW(W),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new n0({alias:w1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function dO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function lO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,Y,J)=>{let G=J===0?Y.toLowerCase():`${Y[0].toUpperCase()}${Y.slice(1)}`;return X+G},"")}function oO(W){return W}class O5{static[D]="CasingCache";cache={};cachedTables={};convert;constructor(W){this.convert=W==="snake_case"?dO:W==="camelCase"?lO:oO}getColumnCasing(W){if(!W.keyAsName)return W.name;let $=W.table[y.Symbol.Schema]??"public",X=W.table[y.Symbol.OriginalName],Y=`${$}.${X}.${W.name}`;if(!this.cache[Y])this.cacheTable(W.table);return this.cache[Y]}cacheTable(W){let $=W[y.Symbol.Schema]??"public",X=W[y.Symbol.OriginalName],Y=`${$}.${X}`;if(!this.cachedTables[Y]){for(let J of Object.values(W[y.Symbol.Columns])){let G=`${Y}.${J.name}`;this.cache[G]=this.convert(J.name)}this.cachedTables[Y]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class E6 extends h1{static[D]="PgViewBase"}class L8{static[D]="PgDialect";casing;constructor(W){this.casing=new O5(W?.casing)}async migrate(W,$,X){let Y=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",J=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",G=M`
78
- CREATE TABLE IF NOT EXISTS ${M.identifier(J)}.${M.identifier(Y)} (
77
+ `};return Y(z),new Promise(async(_)=>H=_);async function T({highWaterMark:_=16384,start:w=0,end:O=1/0}={}){let M=O-w;return w&&await z.seek(w),new HF.Readable({highWaterMark:_,async read(A){let I=A>M?A-M:A;M-=A;let[{data:j}]=await z.read(I);if(this.push(j),j.length<A)this.push(null)}})}async function F({highWaterMark:_=16384,start:w=0}={}){return w&&await z.seek(w),new HF.Writable({highWaterMark:_,write(O,M,A){z.write(O).then(()=>A(),A)}})}}).catch(G)})}Object.assign(vY,{PostgresError:K4,toPascal:L8,pascal:_7,toCamel:E8,camel:F7,toKebab:B8,kebab:w7,fromPascal:K6,fromCamel:O6,fromKebab:A6,BigInt:{to:20,from:[20],parse:(W)=>BigInt(W),serialize:(W)=>W.toString()}});var E4=vY;function vY(W,$){let X=gO(W,$),Y=X.no_subscribe||O7(vY,{...X}),G=!1,J=WW(),H=WW(),Q=WW(),z=WW(),T=WW(),F=WW(),_=WW(),w=WW(),O={connecting:H,reserved:Q,closed:z,ended:T,open:F,busy:_,full:w},M=[...Array(X.max)].map(()=>M7(X,O,{onopen:VW,onend:M1,onclose:P8})),A=I(w0);return Object.assign(A,{get parameters(){return X.parameters},largeObject:K7.bind(null,A),subscribe:Y,CLOSE:O4,END:O4,PostgresError:K4,options:X,reserve:Z,listen:j,begin:P,close:$0,end:V0}),A;function I(k){return k.debug=X.debug,Object.entries(X.types).reduce((F0,[j0,r0])=>{return F0[j0]=(u0)=>new pW(u0,r0.to),F0},e),Object.assign(N0,{types:e,typed:e,unsafe:m0,notify:R,array:m,json:x,file:W1}),N0;function e(F0,j0){return new pW(F0,j0)}function N0(F0,...j0){return F0&&Array.isArray(F0.raw)?new FW(F0,j0,k,B):typeof F0==="string"&&!j0.length?new E6(X.transform.column.to?X.transform.column.to(F0):F0):new jY(F0,j0)}function m0(F0,j0=[],r0={}){return arguments.length===2&&!Array.isArray(j0)&&(r0=j0,j0=[]),new FW([F0],j0,k,B,{prepare:!1,...r0,simple:"simple"in r0?r0.simple:j0.length===0})}function W1(F0,j0=[],r0={}){return arguments.length===2&&!Array.isArray(j0)&&(r0=j0,j0=[]),new FW([],j0,(v0)=>{hO.readFile(F0,"utf8",(O1,I0)=>{if(O1)return v0.reject(O1);v0.strings=[I0],k(v0)})},B,{...r0,simple:"simple"in r0?r0.simple:j0.length===0})}}async function j(k,e,N0){let m0={fn:e,onlisten:N0},W1=j.sql||(j.sql=vY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(j.channels).forEach(([v0,{listeners:O1}])=>{delete j.channels[v0],Promise.all(O1.map((I0)=>j(v0,I0.fn,I0.onlisten).catch(()=>{})))})},onnotify(v0,O1){v0 in j.channels&&j.channels[v0].listeners.forEach((I0)=>I0.fn(O1))}})),F0=j.channels||(j.channels={});if(k in F0){F0[k].listeners.push(m0);let v0=await F0[k].result;return m0.onlisten&&m0.onlisten(),{state:v0.state,unlisten:u0}}F0[k]={result:W1`listen ${W1.unsafe('"'+k.replace(/"/g,'""')+'"')}`,listeners:[m0]};let r0=await F0[k].result;return m0.onlisten&&m0.onlisten(),{state:r0.state,unlisten:u0};async function u0(){if(k in F0===!1)return;if(F0[k].listeners=F0[k].listeners.filter((v0)=>v0!==m0),F0[k].listeners.length)return;return delete F0[k],W1`unlisten ${W1.unsafe('"'+k.replace(/"/g,'""')+'"')}`}}async function R(k,e){return await A`select pg_notify(${k}, ${""+e})`}async function Z(){let k=WW(),e=F.length?F.shift():await new Promise((W1)=>{J.push({reserve:W1}),z.length&&e0(z.shift())});h(e,Q),e.reserved=()=>k.length?e.execute(k.shift()):h(e,Q),e.reserved.release=!0;let N0=I(m0);return N0.release=()=>{e.reserved=null,VW(e)},N0;function m0(W1){e.queue===w?k.push(W1):e.execute(W1)||h(e,w)}}async function P(k,e){!e&&(e=k,k="");let N0=WW(),m0=0,W1,F0=null;try{return await A.unsafe("begin "+k.replace(/[^a-z ]/ig,""),[],{onexecute:r0}).execute(),await Promise.race([j0(W1,e),new Promise((u0,v0)=>W1.onclose=v0)])}catch(u0){throw u0}async function j0(u0,v0,O1){let I0=I($1);I0.savepoint=O2,I0.prepare=(y0)=>F0=y0.replace(/[^a-z0-9$-_. ]/gi);let MW,K1;O1&&await I0`savepoint ${I0(O1)}`;try{if(K1=await new Promise((y0,OW)=>{let IW=v0(I0);Promise.resolve(Array.isArray(IW)?Promise.all(IW):IW).then(y0,OW)}),MW)throw MW}catch(y0){throw await(O1?I0`rollback to ${I0(O1)}`:I0`rollback`),y0 instanceof K4&&y0.code==="25P02"&&MW||y0}if(!O1)F0?await I0`prepare transaction '${I0.unsafe(F0)}'`:await I0`commit`;return K1;function O2(y0,OW){if(y0&&Array.isArray(y0.raw))return O2((IW)=>IW.apply(IW,arguments));return arguments.length===1&&(OW=y0,y0=null),j0(u0,OW,"s"+m0+++(y0?"_"+y0:""))}function $1(y0){y0.catch((OW)=>MW||(MW=OW)),u0.queue===w?N0.push(y0):u0.execute(y0)||h(u0,w)}}function r0(u0){W1=u0,h(u0,Q),u0.reserved=()=>N0.length?u0.execute(N0.shift()):h(u0,Q)}}function h(k,e){return k.queue.remove(k),e.push(k),k.queue=e,e===F?k.idleTimer.start():k.idleTimer.cancel(),k}function x(k){return new pW(k,3802)}function m(k,e){if(!Array.isArray(k))return m(Array.from(arguments));return new pW(k,e||(k.length?CY(k)||25:0),X.shared.typeArrayMap)}function w0(k){if(G)return k.reject(a0.connection("CONNECTION_ENDED",X,X));if(F.length)return p0(F.shift(),k);if(z.length)return e0(z.shift(),k);_.length?p0(_.shift(),k):J.push(k)}function p0(k,e){return k.execute(e)?h(k,_):h(k,w)}function B(k){return new Promise((e,N0)=>{k.state?k.active?M7(X).cancel(k.state,e,N0):k.cancelled={resolve:e,reject:N0}:(J.remove(k),k.cancelled=!0,k.reject(a0.generic("57014","canceling statement due to user request")),e())})}async function V0({timeout:k=null}={}){if(G)return G;await 1;let e;return G=Promise.race([new Promise((N0)=>k!==null&&(e=setTimeout(U0,k*1000,N0))),Promise.all(M.map((N0)=>N0.end()).concat(j.sql?j.sql.end({timeout:0}):[],Y.sql?Y.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(e))}async function $0(){await Promise.all(M.map((k)=>k.end()))}async function U0(k){await Promise.all(M.map((e)=>e.terminate()));while(J.length)J.shift().reject(a0.connection("CONNECTION_DESTROYED",X));k()}function e0(k,e){return h(k,H),k.connect(e),k}function M1(k){h(k,T)}function VW(k){if(J.length===0)return h(k,F);let e=Math.ceil(J.length/(H.length+1)),N0=!0;while(N0&&J.length&&e-- >0){let m0=J.shift();if(m0.reserve)return m0.reserve(k);N0=k.execute(m0)}N0?h(k,_):h(k,w)}function P8(k,e){h(k,z),k.reserved=null,k.onclose&&(k.onclose(e),k.onclose=null),X.onclose&&X.onclose(k.id),J.length&&e0(k,J.shift())}}function gO(W,$){if(W&&W.shared)return W;let X=process.env,Y=(!W||typeof W==="string"?$:W)||{},{url:G,multihost:J}=dO(W),H=[...G.searchParams].reduce((w,[O,M])=>(w[O]=M,w),{}),Q=Y.hostname||Y.host||J||G.hostname||X.PGHOST||"localhost",z=Y.port||G.port||X.PGPORT||5432,T=Y.user||Y.username||G.username||X.PGUSERNAME||X.PGUSER||lO();Y.no_prepare&&(Y.prepare=!1),H.sslmode&&(H.ssl=H.sslmode,delete H.sslmode),"timeout"in Y&&(console.log("The timeout option is deprecated, use idle_timeout instead"),Y.idle_timeout=Y.timeout),H.sslrootcert==="system"&&(H.ssl="verify-full");let F=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],_={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:uO,max_pipeline:100,backoff:pO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Q)?Q:Q.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(z)?z:Q.split(",").map((w)=>parseInt(w.split(":")[1]||z)),path:Y.path||Q.indexOf("/")>-1&&Q+"/.s.PGSQL."+z,database:Y.database||Y.db||(G.pathname||"").slice(1)||X.PGDATABASE||T,user:T,pass:Y.pass||Y.password||G.password||X.PGPASSWORD||"",...Object.entries(_).reduce((w,[O,M])=>{let A=O in Y?Y[O]:(O in H)?H[O]==="disable"||H[O]==="false"?!1:H[O]:X["PG"+O.toUpperCase()]||M;return w[O]=typeof A==="string"&&F.includes(O)?+A:A,w},{}),connection:{application_name:"postgres.js",...Y.connection,...Object.entries(H).reduce((w,[O,M])=>((O in _)||(w[O]=M),w),{})},types:Y.types||{},target_session_attrs:mO(Y,G,X),onnotice:Y.onnotice,onnotify:Y.onnotify,onclose:Y.onclose,onparameter:Y.onparameter,socket:Y.socket,transform:cO(Y.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...rT(Y.types)}}function mO(W,$,X){let Y=W.target_session_attrs||$.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!Y||["read-write","read-only","primary","standby","prefer-standby"].includes(Y))return Y;throw new Error("target_session_attrs "+Y+" is not supported")}function pO(W){return(0.5+Math.random()/2)*Math.min(3**W/100,20)}function uO(){return 60*(30+Math.random()*30)}function cO(W){return{undefined:W.undefined,column:{from:typeof W.column==="function"?W.column:W.column&&W.column.from,to:W.column&&W.column.to},value:{from:typeof W.value==="function"?W.value:W.value&&W.value.from,to:W.value&&W.value.to},row:{from:typeof W.row==="function"?W.row:W.row&&W.row.from,to:W.row&&W.row.to}}}function dO(W){if(!W||typeof W!=="string")return{url:{searchParams:new Map}};let $=W;$=$.slice($.indexOf("://")+3).split(/[?/]/)[0],$=decodeURIComponent($.slice($.indexOf("@")+1));let X=new URL(W.replace($,$.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:$.indexOf(",")>-1&&$}}function lO(){try{return yO.userInfo().username}catch(W){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class n0{static[D]="SelectionProxyHandler";config;constructor(W){this.config={...W}}get(W,$){if($==="_")return{...W._,selectedFields:new Proxy(W._.selectedFields,this)};if($===f0)return{...W[f0],selectedFields:new Proxy(W[f0].selectedFields,this)};if(typeof $==="symbol")return W[$];let Y=(L(W,H1)?W._.selectedFields:L(W,g1)?W[f0].selectedFields:W)[$];if(L(Y,p.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!Y.isSelectionField)return Y.sql;let G=Y.clone();return G.isSelectionField=!0,G}if(L(Y,p)){if(this.config.sqlBehavior==="sql")return Y;throw new Error(`You tried to reference "${$}" 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(L(Y,q0)){if(this.config.alias)return new Proxy(Y,new M4(new Proxy(Y.table,new T6(this.config.alias,this.config.replaceOriginalName??!1))));return Y}if(typeof Y!=="object"||Y===null)return Y;return new Proxy(Y,new n0(this.config))}}class yY extends j1{constructor(W,$,X,Y){super();this.session=$,this.dialect=X,this.config={table:W,withList:Y}}static[D]="PgDelete";config;where(W){return this.config.where=W,this}returning(W=this.config.table[g.Symbol.Columns]){return this.config.returningFields=W,this.config.returning=zW(W),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new n0({alias:w1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function oO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function iO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,Y,G)=>{let J=G===0?Y.toLowerCase():`${Y[0].toUpperCase()}${Y.slice(1)}`;return X+J},"")}function nO(W){return W}class A7{static[D]="CasingCache";cache={};cachedTables={};convert;constructor(W){this.convert=W==="snake_case"?oO:W==="camelCase"?iO:nO}getColumnCasing(W){if(!W.keyAsName)return W.name;let $=W.table[g.Symbol.Schema]??"public",X=W.table[g.Symbol.OriginalName],Y=`${$}.${X}.${W.name}`;if(!this.cache[Y])this.cacheTable(W.table);return this.cache[Y]}cacheTable(W){let $=W[g.Symbol.Schema]??"public",X=W[g.Symbol.OriginalName],Y=`${$}.${X}`;if(!this.cachedTables[Y]){for(let G of Object.values(W[g.Symbol.Columns])){let J=`${Y}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[Y]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class B6 extends g1{static[D]="PgViewBase"}class N8{static[D]="PgDialect";casing;constructor(W){this.casing=new A7(W?.casing)}async migrate(W,$,X){let Y=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",G=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",J=V`
78
+ CREATE TABLE IF NOT EXISTS ${V.identifier(G)}.${V.identifier(Y)} (
79
79
  id SERIAL PRIMARY KEY,
80
80
  hash text NOT NULL,
81
81
  created_at bigint
82
82
  )
83
- `;await $.execute(M`CREATE SCHEMA IF NOT EXISTS ${M.identifier(J)}`),await $.execute(G);let Q=(await $.all(M`select id, hash, created_at from ${M.identifier(J)}.${M.identifier(Y)} order by created_at desc limit 1`))[0];await $.transaction(async(z)=>{for await(let F of W)if(!Q||Number(Q.created_at)<F.folderMillis){for(let T of F.sql)await z.execute(M.raw(T));await z.execute(M`insert into ${M.identifier(J)}.${M.identifier(Y)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(W){return`"${W}"`}escapeParam(W){return`$${W+1}`}escapeString(W){return`'${W.replace(/'/g,"''")}'`}buildWithCTE(W){if(!W?.length)return;let $=[M`with `];for(let[X,Y]of W.entries())if($.push(M`${M.identifier(Y._.alias)} as (${Y._.sql})`),X<W.length-1)$.push(M`, `);return $.push(M` `),M.join($)}buildDeleteQuery({table:W,where:$,returning:X,withList:Y}){let J=this.buildWithCTE(Y),G=X?M` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,H=$?M` where ${$}`:void 0;return M`${J}delete from ${W}${H}${G}`}buildUpdateSet(W,$){let X=W[y.Symbol.Columns],Y=Object.keys(X).filter((G)=>$[G]!==void 0||X[G]?.onUpdateFn!==void 0),J=Y.length;return M.join(Y.flatMap((G,H)=>{let Q=X[G],z=$[G]??M.param(Q.onUpdateFn(),Q),F=M`${M.identifier(this.casing.getColumnCasing(Q))} = ${z}`;if(H<J-1)return[F,M.raw(", ")];return[F]}))}buildUpdateQuery({table:W,set:$,where:X,returning:Y,withList:J,from:G,joins:H}){let Q=this.buildWithCTE(J),z=W[M1.Symbol.Name],F=W[M1.Symbol.Schema],T=W[M1.Symbol.OriginalName],U=z===T?void 0:z,_=M`${F?M`${M.identifier(F)}.`:void 0}${M.identifier(T)}${U&&M` ${M.identifier(U)}`}`,V=this.buildUpdateSet(W,$),K=G&&M.join([M.raw(" from "),this.buildFromTable(G)]),B=this.buildJoins(H),I=Y?M` returning ${this.buildSelection(Y,{isSingleTable:!G})}`:void 0,C=X?M` where ${X}`:void 0;return M`${Q}update ${_} set ${V}${K}${B}${C}${I}`}buildSelection(W,{isSingleTable:$=!1}={}){let X=W.length,Y=W.flatMap(({field:J},G)=>{let H=[];if(E(J,g.Aliased)&&J.isSelectionField)H.push(M.identifier(J.fieldAlias));else if(E(J,g.Aliased)||E(J,g)){let Q=E(J,g.Aliased)?J.sql:J;if($)H.push(new g(Q.queryChunks.map((z)=>{if(E(z,f))return M.identifier(this.casing.getColumnCasing(z));return z})));else H.push(Q);if(E(J,g.Aliased))H.push(M` as ${M.identifier(J.fieldAlias)}`)}else if(E(J,q0))if($)H.push(M.identifier(this.casing.getColumnCasing(J)));else H.push(J);if(G<X-1)H.push(M`, `);return H});return M.join(Y)}buildJoins(W){if(!W||W.length===0)return;let $=[];for(let[X,Y]of W.entries()){if(X===0)$.push(M` `);let J=Y.table,G=Y.lateral?M` lateral`:void 0,H=Y.on?M` on ${Y.on}`:void 0;if(E(J,M1)){let Q=J[M1.Symbol.Name],z=J[M1.Symbol.Schema],F=J[M1.Symbol.OriginalName],T=Q===F?void 0:Y.alias;$.push(M`${M.raw(Y.joinType)} join${G} ${z?M`${M.identifier(z)}.`:void 0}${M.identifier(F)}${T&&M` ${M.identifier(T)}`}${H}`)}else if(E(J,h1)){let Q=J[P0].name,z=J[P0].schema,F=J[P0].originalName,T=Q===F?void 0:Y.alias;$.push(M`${M.raw(Y.joinType)} join${G} ${z?M`${M.identifier(z)}.`:void 0}${M.identifier(F)}${T&&M` ${M.identifier(T)}`}${H}`)}else $.push(M`${M.raw(Y.joinType)} join${G} ${J}${H}`);if(X<W.length-1)$.push(M` `)}return M.join($)}buildFromTable(W){if(E(W,y)&&W[y.Symbol.IsAlias]){let $=M`${M.identifier(W[y.Symbol.OriginalName])}`;if(W[y.Symbol.Schema])$=M`${M.identifier(W[y.Symbol.Schema])}.${$}`;return M`${$} ${M.identifier(W[y.Symbol.Name])}`}return W}buildSelectQuery({withList:W,fields:$,fieldsFlat:X,where:Y,having:J,table:G,joins:H,orderBy:Q,groupBy:z,limit:F,offset:T,lockingClause:U,distinct:_,setOperators:V}){let K=X??QW($);for(let _0 of K)if(E(_0.field,q0)&&w1(_0.field.table)!==(E(G,H1)?G._.alias:E(G,E6)?G[P0].name:E(G,g)?void 0:w1(G))&&!((e0)=>H?.some(({alias:V1})=>V1===(e0[y.Symbol.IsAlias]?w1(e0):e0[y.Symbol.BaseName])))(_0.field.table)){let e0=w1(_0.field.table);throw new Error(`Your "${_0.path.join("->")}" field references a column "${e0}"."${_0.field.name}", but the table "${e0}" is not part of the query! Did you forget to join it?`)}let B=!H||H.length===0,I=this.buildWithCTE(W),C;if(_)C=_===!0?M` distinct`:M` distinct on (${M.join(_.on,M`, `)})`;let R=this.buildSelection(K,{isSingleTable:B}),q=this.buildFromTable(G),m=this.buildJoins(H),c=Y?M` where ${Y}`:void 0,v=J?M` having ${J}`:void 0,h;if(Q&&Q.length>0)h=M` order by ${M.join(Q,M`, `)}`;let w0;if(z&&z.length>0)w0=M` group by ${M.join(z,M`, `)}`;let p0=typeof F==="object"||typeof F==="number"&&F>=0?M` limit ${F}`:void 0,L=T?M` offset ${T}`:void 0,M0=M.empty();if(U){let _0=M` for ${M.raw(U.strength)}`;if(U.config.of)_0.append(M` of ${M.join(Array.isArray(U.config.of)?U.config.of:[U.config.of],M`, `)}`);if(U.config.noWait)_0.append(M` nowait`);else if(U.config.skipLocked)_0.append(M` skip locked`);M0.append(_0)}let W0=M`${I}select${C} ${R} from ${q}${m}${c}${w0}${v}${h}${p0}${L}${M0}`;if(V.length>0)return this.buildSetOperations(W0,V);return W0}buildSetOperations(W,$){let[X,...Y]=$;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(Y.length===0)return this.buildSetOperationQuery({leftSelect:W,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:W,setOperator:X}),Y)}buildSetOperationQuery({leftSelect:W,setOperator:{type:$,isAll:X,rightSelect:Y,limit:J,orderBy:G,offset:H}}){let Q=M`(${W.getSQL()}) `,z=M`(${Y.getSQL()})`,F;if(G&&G.length>0){let V=[];for(let K of G)if(E(K,f))V.push(M.identifier(K.name));else if(E(K,g)){for(let B=0;B<K.queryChunks.length;B++){let I=K.queryChunks[B];if(E(I,f))K.queryChunks[B]=M.identifier(I.name)}V.push(M`${K}`)}else V.push(M`${K}`);F=M` order by ${M.join(V,M`, `)} `}let T=typeof J==="object"||typeof J==="number"&&J>=0?M` limit ${J}`:void 0,U=M.raw(`${$} ${X?"all ":""}`),_=H?M` offset ${H}`:void 0;return M`${Q}${U}${z}${F}${T}${_}`}buildInsertQuery({table:W,values:$,onConflict:X,returning:Y,withList:J,select:G,overridingSystemValue_:H}){let Q=[],z=W[y.Symbol.Columns],F=Object.entries(z).filter(([I,C])=>!C.shouldDisableInsert()),T=F.map(([,I])=>M.identifier(this.casing.getColumnCasing(I)));if(G){let I=$;if(E(I,g))Q.push(I);else Q.push(I.getSQL())}else{let I=$;Q.push(M.raw("values "));for(let[C,R]of I.entries()){let q=[];for(let[m,c]of F){let v=R[m];if(v===void 0||E(v,s1)&&v.value===void 0)if(c.defaultFn!==void 0){let h=c.defaultFn(),w0=E(h,g)?h:M.param(h,c);q.push(w0)}else if(!c.default&&c.onUpdateFn!==void 0){let h=c.onUpdateFn(),w0=E(h,g)?h:M.param(h,c);q.push(w0)}else q.push(M`default`);else q.push(v)}if(Q.push(q),C<I.length-1)Q.push(M`, `)}}let U=this.buildWithCTE(J),_=M.join(Q),V=Y?M` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,K=X?M` on conflict ${X}`:void 0,B=H===!0?M`overriding system value `:void 0;return M`${U}insert into ${W} ${T} ${B}${_}${K}${V}`}buildRefreshMaterializedViewQuery({view:W,concurrently:$,withNoData:X}){let Y=$?M` concurrently`:void 0,J=X?M` with no data`:void 0;return M`refresh materialized view${Y} ${W}${J}`}prepareTyping(W){if(E(W,OY)||E(W,VY))return"json";else if(E(W,KY))return"decimal";else if(E(W,AY))return"time";else if(E(W,EY)||E(W,LY))return"timestamp";else if(E(W,DY)||E(W,MY))return"date";else if(E(W,BY))return"uuid";else return"none"}sqlToQuery(W,$){return W.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:$})}buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:X,table:Y,tableConfig:J,queryConfig:G,tableAlias:H,nestedQueryRelation:Q,joinOn:z}){let F=[],T,U,_=[],V,K=[];if(G===!0)F=Object.entries(J.columns).map(([C,R])=>({dbKey:R.name,tsKey:C,field:mW(R,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(J.columns).map(([v,h])=>[v,mW(h,H)]));if(G.where){let v=typeof G.where==="function"?G.where(I,xF()):G.where;V=v&&z6(v,H)}let C=[],R=[];if(G.columns){let v=!1;for(let[h,w0]of Object.entries(G.columns)){if(w0===void 0)continue;if(h in J.columns){if(!v&&w0===!0)v=!0;R.push(h)}}if(R.length>0)R=v?R.filter((h)=>G.columns?.[h]===!0):Object.keys(J.columns).filter((h)=>!R.includes(h))}else R=Object.keys(J.columns);for(let v of R){let h=J.columns[v];C.push({tsKey:v,value:h})}let q=[];if(G.with)q=Object.entries(G.with).filter((v)=>!!v[1]).map(([v,h])=>({tsKey:v,queryConfig:h,relation:J.relations[v]}));let m;if(G.extras){m=typeof G.extras==="function"?G.extras(I,{sql:M}):G.extras;for(let[v,h]of Object.entries(m))C.push({tsKey:v,value:oJ(h,H)})}for(let{tsKey:v,value:h}of C)F.push({dbKey:E(h,g.Aliased)?h.fieldAlias:J.columns[v].name,tsKey:v,field:E(h,q0)?mW(h,H):h,relationTableTsKey:void 0,isJson:!1,selection:[]});let c=typeof G.orderBy==="function"?G.orderBy(I,vF()):G.orderBy??[];if(!Array.isArray(c))c=[c];_=c.map((v)=>{if(E(v,q0))return mW(v,H);return z6(v,H)}),T=G.limit,U=G.offset;for(let{tsKey:v,queryConfig:h,relation:w0}of q){let p0=yF($,X,w0),L=V8(w0.referencedTable),M0=X[L],W0=`${H}_${v}`,_0=_6(...p0.fields.map((DW,k8)=>RY(mW(p0.references[k8],W0),mW(DW,H)))),e0=this.buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:X,table:W[M0],tableConfig:$[M0],queryConfig:E(w0,x2)?h===!0?{limit:1}:{...h,limit:1}:h,tableAlias:W0,joinOn:_0,nestedQueryRelation:w0}),V1=M`${M.identifier(W0)}.${M.identifier("data")}`.as(v);K.push({on:M`true`,table:new H1(e0.sql,{},W0),alias:W0,joinType:"left",lateral:!0}),F.push({dbKey:v,tsKey:v,field:V1,relationTableTsKey:M0,isJson:!0,selection:e0.selection})}}if(F.length===0)throw new wY({message:`No fields selected for table "${J.tsName}" ("${H}")`});let B;if(V=_6(z,V),Q){let I=M`json_build_array(${M.join(F.map(({field:q,tsKey:m,isJson:c})=>c?M`${M.identifier(`${H}_${m}`)}.${M.identifier("data")}`:E(q,g.Aliased)?q.sql:q),M`, `)})`;if(E(Q,D6))I=M`coalesce(json_agg(${I}${_.length>0?M` order by ${M.join(_,M`, `)}`:void 0}), '[]'::json)`;let C=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:F}];if(T!==void 0||U!==void 0||_.length>0)B=this.buildSelectQuery({table:UY(Y,H),fields:{},fieldsFlat:[{path:[],field:M.raw("*")}],where:V,limit:T,offset:U,orderBy:_,setOperators:[]}),V=void 0,T=void 0,U=void 0,_=[];else B=UY(Y,H);B=this.buildSelectQuery({table:E(B,M1)?B:new H1(B,{},H),fields:{},fieldsFlat:C.map(({field:q})=>({path:[],field:E(q,q0)?mW(q,H):q})),joins:K,where:V,limit:T,offset:U,orderBy:_,setOperators:[]})}else B=this.buildSelectQuery({table:UY(Y,H),fields:{},fieldsFlat:F.map(({field:I})=>({path:[],field:E(I,q0)?mW(I,H):I})),joins:K,where:V,limit:T,offset:U,orderBy:_,setOperators:[]});return{tableTsKey:J.tsName,sql:B,selection:F}}}class K5{static[D]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class I1{static[D]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(W){if(this.fields=W.fields,this.session=W.session,this.dialect=W.dialect,W.withList)this.withList=W.withList;this.distinct=W.distinct}authToken;setToken(W){return this.authToken=W,this}from(W){let $=!!this.fields,X=W,Y;if(this.fields)Y=this.fields;else if(E(X,H1))Y=Object.fromEntries(Object.keys(X._.selectedFields).map((J)=>[J,X[J]]));else if(E(X,E6))Y=X[P0].selectedFields;else if(E(X,g))Y={};else Y=DQ(X);return new A5({table:X,fields:Y,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class GT extends K5{static[D]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:W,fields:$,isPartialSelect:X,session:Y,dialect:J,withList:G,distinct:H}){super();this.config={withList:G,table:W,fields:{...$},distinct:H,setOperators:[]},this.isPartialSelect=X,this.session=Y,this.dialect=J,this._={selectedFields:$},this.tableName=J2(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(W,$){return(X,Y)=>{let J=this.tableName,G=J2(X);if(typeof G==="string"&&this.config.joins?.some((H)=>H.alias===G))throw new Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof G==="string"&&!E(X,g)){let H=E(X,H1)?X._.selectedFields:E(X,h1)?X[P0].selectedFields:X[y.Symbol.Columns];this.config.fields[G]=H}}if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:Y,table:X,joinType:W,alias:G,lateral:$}),typeof G==="string")switch(W){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[G]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(W,$){return(X)=>{let Y=typeof X==="function"?X(iO()):X;if(!F6(this.getSelectedFields(),Y.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:W,isAll:$,rightSelect:Y}),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(W){return this.config.setOperators.push(...W),this}where(W){if(typeof W==="function")W=W(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=W,this}having(W){if(typeof W==="function")W=W(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=W,this}groupBy(...W){if(typeof W[0]==="function"){let $=W[0](new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray($)?$:[$]}else this.config.groupBy=W;return this}orderBy(...W){if(typeof W[0]==="function"){let $=W[0](new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let $=W;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}return this}limit(W){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=W;else this.config.limit=W;return this}offset(W){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=W;else this.config.offset=W;return this}for(W,$={}){return this.config.lockingClause={strength:W,config:$},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}as(W){return new Proxy(new H1(this.getSQL(),this.config.fields,W),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new n0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class A5 extends GT{static[D]="PgSelect";_prepare(W){let{session:$,config:X,dialect:Y,joinsNotNullableMap:J,authToken:G}=this;if(!$)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return C0.startActiveSpan("drizzle.prepareQuery",()=>{let H=QW(X.fields),Q=$.prepareQuery(Y.sqlToQuery(this.getSQL()),H,W,!0);return Q.joinsNotNullableMap=J,Q.setToken(G)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})}}_Q(A5,[k1]);function A$(W,$){return(X,Y,...J)=>{let G=[Y,...J].map((H)=>({type:W,isAll:$,rightSelect:H}));for(let H of G)if(!F6(X.getSelectedFields(),H.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(G)}}var iO=()=>({union:nO,unionAll:rO,intersect:tO,intersectAll:aO,except:sO,exceptAll:eO}),nO=A$("union",!1),rO=A$("union",!0),tO=A$("intersect",!1),aO=A$("intersect",!0),sO=A$("except",!1),eO=A$("except",!0);class L6{static[D]="PgQueryBuilder";dialect;dialectConfig;constructor(W){this.dialect=E(W,L8)?W:void 0,this.dialectConfig=E(W,L8)?void 0:W}$with=(W,$)=>{let X=this;return{as:(J)=>{if(typeof J==="function")J=J(X);return new Proxy(new G6(J.getSQL(),$??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),W,!0),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...W){let $=this;function X(G){return new I1({fields:G??void 0,session:void 0,dialect:$.getDialect(),withList:W})}function Y(G){return new I1({fields:G??void 0,session:void 0,dialect:$.getDialect(),distinct:!0})}function J(G,H){return new I1({fields:H??void 0,session:void 0,dialect:$.getDialect(),distinct:{on:G}})}return{select:X,selectDistinct:Y,selectDistinctOn:J}}select(W){return new I1({fields:W??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(W){return new I1({fields:W??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(W,$){return new I1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:W}})}getDialect(){if(!this.dialect)this.dialect=new L8(this.dialectConfig);return this.dialect}}class hY{constructor(W,$,X,Y,J){this.table=W,this.session=$,this.dialect=X,this.withList=Y,this.overridingSystemValue_=J}static[D]="PgInsertBuilder";authToken;setToken(W){return this.authToken=W,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(W){if(W=Array.isArray(W)?W:[W],W.length===0)throw new Error("values() must be called with at least one value");let $=W.map((X)=>{let Y={},J=this.table[y.Symbol.Columns];for(let G of Object.keys(X)){let H=X[G];Y[G]=E(H,g)?H:new s1(H,J[G])}return Y});return new E5(this.table,$,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(W){let $=typeof W==="function"?W(new L6):W;if(!E($,g)&&!F6(this.table[FY],$._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new E5(this.table,$,this.session,this.dialect,this.withList,!0)}}class E5 extends k1{constructor(W,$,X,Y,J,G,H){super();this.session=X,this.dialect=Y,this.config={table:W,values:$,withList:J,select:G,overridingSystemValue_:H}}static[D]="PgInsert";config;returning(W=this.config.table[y.Symbol.Columns]){return this.config.returningFields=W,this.config.returning=QW(W),this}onConflictDoNothing(W={}){if(W.target===void 0)this.config.onConflict=M`do nothing`;else{let $="";$=Array.isArray(W.target)?W.target.map((Y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target));let X=W.where?M` where ${W.where}`:void 0;this.config.onConflict=M`(${M.raw($)})${X} do nothing`}return this}onConflictDoUpdate(W){if(W.where&&(W.targetWhere||W.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 $=W.where?M` where ${W.where}`:void 0,X=W.targetWhere?M` where ${W.targetWhere}`:void 0,Y=W.setWhere?M` where ${W.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,_Y(this.config.table,W.set)),G="";return G=Array.isArray(W.target)?W.target.map((H)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(H))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target)),this.config.onConflict=M`(${M.raw(G)})${X} do update set ${J}${$}${Y}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new n0({alias:w1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class L5 extends k1{constructor(W,$,X){super();this.session=$,this.dialect=X,this.config={view:W}}static[D]="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:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})}}class gY{constructor(W,$,X,Y){this.table=W,this.session=$,this.dialect=X,this.withList=Y}static[D]="PgUpdateBuilder";authToken;setToken(W){return this.authToken=W,this}set(W){return new HT(this.table,_Y(this.table,W),this.session,this.dialect,this.withList).setToken(this.authToken)}}class HT extends k1{constructor(W,$,X,Y,J){super();this.session=X,this.dialect=Y,this.config={set:$,table:W,withList:J,joins:[]},this.tableName=J2(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[D]="PgUpdate";config;tableName;joinsNotNullableMap;from(W){let $=W,X=J2($);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=$,this}getTableLikeFields(W){if(E(W,M1))return W[y.Symbol.Columns];else if(E(W,H1))return W._.selectedFields;return W[P0].selectedFields}createJoin(W){return($,X)=>{let Y=J2($);if(typeof Y==="string"&&this.config.joins.some((J)=>J.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(typeof X==="function"){let J=this.config.from&&!E(this.config.from,g)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[y.Symbol.Columns],new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:$,joinType:W,alias:Y}),typeof Y==="string")switch(W){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[Y]=!0;break}case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[Y]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(W){return this.config.where=W,this}returning(W){if(!W){if(W=Object.assign({},this.config.table[y.Symbol.Columns]),this.config.from){let $=J2(this.config.from);if(typeof $==="string"&&this.config.from&&!E(this.config.from,g)){let X=this.getTableLikeFields(this.config.from);W[$]=X}for(let X of this.config.joins){let Y=J2(X.table);if(typeof Y==="string"&&!E(X.table,g)){let J=this.getTableLikeFields(X.table);W[Y]=J}}}}return this.config.returningFields=W,this.config.returning=QW(W),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){let $=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0);return $.joinsNotNullableMap=this.joinsNotNullableMap,$}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return this._prepare().execute(W,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new n0({alias:w1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class B6 extends g{constructor(W){super(B6.buildEmbeddedCount(W.source,W.filters).queryChunks);this.params=W,this.mapWith(Number),this.session=W.session,this.sql=B6.buildCount(W.source,W.filters)}sql;token;static[D]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(W,$){return M`(select count(*) from ${W}${M.raw(" where ").if($)}${$})`}static buildCount(W,$){return M`select count(*) as count from ${W}${M.raw(" where ").if($)}${$};`}setToken(W){return this.token=W,this}then(W,$){return Promise.resolve(this.session.count(this.sql,this.token)).then(W,$)}catch(W){return this.then(void 0,W)}finally(W){return this.then(($)=>{return W?.(),$},($)=>{throw W?.(),$})}}class R5{constructor(W,$,X,Y,J,G,H){this.fullSchema=W,this.schema=$,this.tableNamesMap=X,this.table=Y,this.tableConfig=J,this.dialect=G,this.session=H}static[D]="PgRelationalQueryBuilder";findMany(W){return new B5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?W:{},"many")}findFirst(W){return new B5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?{...W,limit:1}:{limit:1},"first")}}class B5 extends k1{constructor(W,$,X,Y,J,G,H,Q,z){super();this.fullSchema=W,this.schema=$,this.tableNamesMap=X,this.table=Y,this.tableConfig=J,this.dialect=G,this.session=H,this.config=Q,this.mode=z}static[D]="PgRelationalQuery";_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:$,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,W,!0,(Y,J)=>{let G=Y.map((H)=>ZY(this.schema,this.tableConfig,H,$.selection,J));if(this.mode==="first")return G[0];return G})})}prepare(W){return this._prepare(W)}_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 W=this._getQuery(),$=this.dialect.sqlToQuery(W.sql);return{query:W,builtQuery:$}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(W){return this.authToken=W,this}execute(){return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class N5 extends k1{constructor(W,$,X,Y){super();this.execute=W,this.sql=$,this.query=X,this.mapBatchResult=Y}static[D]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(W,$){return $?this.mapBatchResult(W):W}_prepare(){return this}isResponseInArrayMode(){return!1}}class R6{constructor(W,$,X){if(this.dialect=W,this.session=$,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:$}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:$},this.query={},this._.schema)for(let[Y,J]of Object.entries(this._.schema))this.query[Y]=new R5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[Y],J,W,$)}static[D]="PgDatabase";query;$with=(W,$)=>{let X=this;return{as:(J)=>{if(typeof J==="function")J=J(new L6(X.dialect));return new Proxy(new G6(J.getSQL(),$??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),W,!0),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(W,$){return new B6({source:W,filters:$,session:this.session})}with(...W){let $=this;function X(z){return new I1({fields:z??void 0,session:$.session,dialect:$.dialect,withList:W})}function Y(z){return new I1({fields:z??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:!0})}function J(z,F){return new I1({fields:F??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:{on:z}})}function G(z){return new gY(z,$.session,$.dialect,W)}function H(z){return new hY(z,$.session,$.dialect,W)}function Q(z){return new yY(z,$.session,$.dialect,W)}return{select:X,selectDistinct:Y,selectDistinctOn:J,update:G,insert:H,delete:Q}}select(W){return new I1({fields:W??void 0,session:this.session,dialect:this.dialect})}selectDistinct(W){return new I1({fields:W??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(W,$){return new I1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:{on:W}})}update(W){return new gY(W,this.session,this.dialect)}insert(W){return new hY(W,this.session,this.dialect)}delete(W){return new yY(W,this.session,this.dialect)}refreshMaterializedView(W){return new L5(W,this.session,this.dialect)}authToken;execute(W){let $=typeof W==="string"?M.raw(W):W.getSQL(),X=this.dialect.sqlToQuery($),Y=this.session.prepareQuery(X,void 0,void 0,!1);return new N5(()=>Y.execute(void 0,this.authToken),$,X,(J)=>Y.mapResult(J,!0))}transaction(W,$){return this.session.transaction(W,$)}}class QT{constructor(W,$){this.unique=W,this.name=$}static[D]="PgIndexBuilderOn";on(...W){return new mY(W.map(($)=>{if(E($,g))return $;$=$;let X=new Y6($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...W){return new mY(W.map(($)=>{if(E($,g))return $;$=$;let X=new Y6($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=$.defaultConfig,X}),this.unique,!0,this.name)}using(W,...$){return new mY($.map((X)=>{if(E(X,g))return X;X=X;let Y=new Y6(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),Y}),this.unique,!0,this.name,W)}}class mY{static[D]="PgIndexBuilder";config;constructor(W,$,X,Y,J="btree"){this.config={name:Y,columns:W,unique:$,only:X,method:J}}concurrently(){return this.config.concurrently=!0,this}with(W){return this.config.with=W,this}where(W){return this.config.where=W,this}build(W){return new zT(this.config,W)}}class zT{static[D]="PgIndex";config;constructor(W,$){this.config={...W,table:$}}}function Z5(W){return new QT(!0,W)}class S5{constructor(W){this.query=W}authToken;getQuery(){return this.query}mapResult(W,$){return W}setToken(W){return this.authToken=W,this}static[D]="PgPreparedQuery";joinsNotNullableMap}class q5{constructor(W){this.dialect=W}static[D]="PgSession";execute(W,$){return C0.startActiveSpan("drizzle.operation",()=>{return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(W),void 0,void 0,!1)}).setToken($).execute(void 0,$)})}all(W){return this.prepareQuery(this.dialect.sqlToQuery(W),void 0,void 0,!1).all()}async count(W,$){let X=await this.execute(W,$);return Number(X[0].count)}}class C5 extends R6{constructor(W,$,X,Y=0){super(W,$,X);this.schema=X,this.nestedIndex=Y}static[D]="PgTransaction";rollback(){throw new iJ}getTransactionConfigSQL(W){let $=[];if(W.isolationLevel)$.push(`isolation level ${W.isolationLevel}`);if(W.accessMode)$.push(W.accessMode);if(typeof W.deferrable==="boolean")$.push(W.deferrable?"deferrable":"not deferrable");return M.raw($.join(" "))}setTransaction(W){return this.session.execute(M`set transaction ${this.getTransactionConfigSQL(W)}`)}}class FT extends S5{constructor(W,$,X,Y,J,G,H){super({sql:$,params:X});this.client=W,this.queryString=$,this.params=X,this.logger=Y,this.fields=J,this._isResponseInArrayMode=G,this.customResultMapper=H}static[D]="PostgresJsPreparedQuery";async execute(W={}){return C0.startActiveSpan("drizzle.execute",async($)=>{let X=lJ(this.params,W);$?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:Y,queryString:J,client:G,joinsNotNullableMap:H,customResultMapper:Q}=this;if(!Y&&!Q)return C0.startActiveSpan("drizzle.driver.execute",()=>{return G.unsafe(J,X)});let z=await C0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(X)}),G.unsafe(J,X).values()});return C0.startActiveSpan("drizzle.mapResponse",()=>{return Q?Q(z):z.map((F)=>wQ(Y,F,H))})})}all(W={}){return C0.startActiveSpan("drizzle.execute",async($)=>{let X=lJ(this.params,W);return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),C0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.client.unsafe(this.queryString,X)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class N6 extends q5{constructor(W,$,X,Y={}){super($);this.client=W,this.schema=X,this.options=Y,this.logger=Y.logger??new rJ}static[D]="PostgresJsSession";logger;prepareQuery(W,$,X,Y,J){return new FT(this.client,W.sql,W.params,this.logger,$,Y,J)}query(W,$){return this.logger.logQuery(W,$),this.client.unsafe(W,$).values()}queryObjects(W,$){return this.client.unsafe(W,$)}transaction(W,$){return this.client.begin(async(X)=>{let Y=new N6(X,this.dialect,this.schema,this.options),J=new k5(this.dialect,Y,this.schema);if($)await J.setTransaction($);return W(J)})}}class k5 extends C5{constructor(W,$,X,Y=0){super(W,$,X,Y);this.session=$}static[D]="PostgresJsTransaction";transaction(W){return this.session.client.savepoint(($)=>{let X=new N6($,this.dialect,this.schema,this.session.options),Y=new k5(this.dialect,X,this.schema);return W(Y)})}}class TT extends R6{static[D]="PostgresJsDatabase"}function E$(W,$={}){let X=(z)=>z;for(let z of["1184","1082","1083","1114","1182","1185","1115","1231"])W.options.parsers[z]=X,W.options.serializers[z]=X;W.options.serializers["114"]=X,W.options.serializers["3802"]=X;let Y=new L8({casing:$.casing}),J;if($.logger===!0)J=new nJ;else if($.logger!==!1)J=$.logger;let G;if($.schema){let z=bF($.schema,hF);G={fullSchema:$.schema,schema:z.tables,tableNamesMap:z.tableNamesMap}}let H=new N6(W,Y,G,{logger:J}),Q=new TT(Y,H,G);return Q.$client=W,Q}function pY(...W){if(typeof W[0]==="string"){let $=K$(W[0]);return E$($,W[1])}if(MQ(W[0])){let{connection:$,client:X,...Y}=W[0];if(X)return E$(X,Y);if(typeof $==="object"&&$.url!==void 0){let{url:G,...H}=$,Q=K$(G,H);return E$(Q,Y)}let J=K$($);return E$(J,Y)}return E$(W[0],W[1])}((W)=>{function $(X){return E$({options:{parsers:{},serializers:{}}},X)}W.mock=$})(pY||(pY={}));function UT(W,$){if(W instanceof Promise)throw new Error($)}function WK(W,$){let X={},Y=[];for(let J in W){let G=W[J]["~standard"].validate($[J]);if(UT(G,`Validation must be synchronous, but ${J} returned a Promise.`),G.issues){Y.push(...G.issues.map((H)=>({...H,path:[J,...H.path??[]]})));continue}X[J]=G.value}if(Y.length)return{issues:Y};return{value:X}}function j5(W){let $=W.runtimeEnvStrict??W.runtimeEnv??process.env;if(W.emptyStringAsUndefined??!1){for(let[R,q]of Object.entries($))if(q==="")delete $[R]}if(!!W.skipValidation)return $;let J=typeof W.client==="object"?W.client:{},G=typeof W.server==="object"?W.server:{},H=typeof W.shared==="object"?W.shared:{},Q=W.isServer??(typeof window==="undefined"||("Deno"in window)),z=Q?{...G,...H,...J}:{...J,...H},F=W.createFinalSchema?.(z,Q)["~standard"].validate($)??WK(z,$);UT(F,"Validation must be synchronous");let T=W.onValidationError??((R)=>{throw console.error("\u274C Invalid environment variables:",R),new Error("Invalid environment variables")}),U=W.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(F.issues)return T(F.issues);let _=(R)=>{if(!W.clientPrefix)return!0;return!R.startsWith(W.clientPrefix)&&!(R in H)},V=(R)=>{return Q||!_(R)},K=(R)=>{return R==="__esModule"||R==="$$typeof"},B=(W.extends??[]).reduce((R,q)=>{return Object.assign(R,q)},{}),I=Object.assign(B,F.value);return new Proxy(I,{get(R,q){if(typeof q!=="string")return;if(K(q))return;if(!V(q))return U(q);return Reflect.get(R,q)}})}var b2=(W)=>Array.isArray(W)?W:[W],wT=(W,$)=>{let X=[[],[]];for(let Y of W)if($(Y))X[0].push(Y);else X[1].push(Y);return X},uY=Array,H2=(W,$)=>W.includes($),_T=(W,$=0)=>[...new Array(W)].map((X,Y)=>Y+$),D0=(W,$,X)=>{if(W===void 0)return $===void 0?[]:Array.isArray($)?$:[$];if(X?.prepend)if(Array.isArray($))W.unshift(...$);else W.unshift($);else if(Array.isArray($))W.push(...$);else W.push($);return W},Q2=(W,$)=>{if($===void 0||$===null)return W??[];if(W===void 0||W===null)return b2($);return W.concat($)},DT=(...W)=>W.reduce(Q2,[]),uW=(W,$,X)=>{if(W===void 0)return Array.isArray($)?$:[$];let Y=X?.isEqual??((J,G)=>J===G);for(let J of b2($))if(!W.some((G)=>Y(G,J)))W.push(J);return W},MT=(W,$)=>W.reduce((X,Y)=>{let J=Y[$];return X[J]=D0(X[J],Y),X},{}),z2=(W,$,X)=>W.length===$.length&&W.every(X?.isEqual?(Y,J)=>X.isEqual(Y,$[J]):(Y,J)=>Y===$[J]);var m1=(W,$)=>z1(W)===$,z1=(W)=>{let $=typeof W;return $==="object"?W===null?"null":"object":$==="function"?"object":$},p1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},VT={...p1,function:"a function"};class OT extends Error{}var K0=(W)=>B8(W,OT),B8=(W,$=Error)=>{throw new $(W)};class Z6 extends Error{name="ParseError"}var A=(W)=>B8(W,Z6),ZW=(W)=>` ${W}`;var X0=(W,$)=>{let X={},Y=Array.isArray(W),J=!1;for(let[G,H]of Object.entries(W).entries()){let Q=Y?$(G,H[1]):$(...H,G);J||=typeof Q[0]==="number";let z=Array.isArray(Q[0])||Q.length===0?Q:[Q];for(let[F,T]of z)if(typeof F==="object")X[F.group]=D0(X[F.group],T);else X[F]=T}return J?Object.values(X):X};var I5=Object.entries;var F1=(W,$)=>(W in $),L$=(W,$)=>($ in W);class f5{constructor(W){Object.assign(this,W)}}var KT=class{};class S6 extends KT{}var $K=(W,$)=>{let X={},Y={},J;for(J in W)if(J in $)X[J]=W[J];else Y[J]=W[J];return[X,Y]};var AT=(W,$)=>$K(W,$)[1],cW=(W)=>Object.keys(W).length===0,R8=(W)=>[...Object.entries(W),...Object.getOwnPropertySymbols(W).map(($)=>[$,W[$]])],ET=(W,$)=>Object.defineProperties(W,Object.getOwnPropertyDescriptors($)),LT=(W)=>{let $=Object.keys(W).sort(),X={};for(let Y=0;Y<$.length;Y++)X[$[Y]]=W[$[Y]];return X};var WW=ZW("represents an uninitialized value"),BT=(W)=>Object.values(W).filter(($)=>{if(typeof $==="number")return!0;return typeof W[$]!=="number"});var P5={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},x5=globalThis.File??Blob,v5={ArrayBuffer,Blob,File:x5,FormData,Headers,Request,Response,URL},XK={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},N8={...P5,...v5,...XK,String,Number,Boolean},q6=(W)=>{let $=Object.getPrototypeOf(W);while($?.constructor&&(!F1($.constructor.name,N8)||!(W instanceof N8[$.constructor.name])))$=Object.getPrototypeOf($);let X=$?.constructor?.name;if(X===void 0||X==="Object")return;return X},C6=(W)=>typeof W==="object"&&W!==null?q6(W)??"object":z1(W);var k0=Array.isArray,YK={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},JK={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},GK={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},RT={...YK,...JK,...GK},k6=(W)=>{let $=Object(W).name??null;return $&&F1($,N8)&&N8[$]===W?$:null};var b5=(W,$)=>{let X=W.prototype;while(X!==null){if(X===$.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var NT=(W)=>ZT(W,new Map),ZT=(W,$)=>{if(typeof W!=="object"||W===null)return W;if($?.has(W))return $.get(W);let X=k6(W.constructor);if(X==="Date")return new Date(W.getTime());if(X&&X!=="Array")return W;let Y=Array.isArray(W)?W.slice():Object.create(Object.getPrototypeOf(W)),J=Object.getOwnPropertyDescriptors(W);if($){$.set(W,Y);for(let G in J){let H=J[G];if("get"in H||"set"in H)continue;H.value=ZT(H.value,$)}}return Object.defineProperties(Y,J),Y};var HK=(W)=>{let $=WW;return()=>$===WW?$=W():$},y2=(W)=>typeof W==="function"&&W.length===0;var ST=class extends Function{constructor(...W){let $=W.slice(0,-1),X=W.at(-1);try{super(...$,X)}catch(Y){return K0(`Encountered an unexpected error while compiling your definition:
83
+ `;await $.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(G)}`),await $.execute(J);let Q=(await $.all(V`select id, hash, created_at from ${V.identifier(G)}.${V.identifier(Y)} order by created_at desc limit 1`))[0];await $.transaction(async(z)=>{for await(let T of W)if(!Q||Number(Q.created_at)<T.folderMillis){for(let F of T.sql)await z.execute(V.raw(F));await z.execute(V`insert into ${V.identifier(G)}.${V.identifier(Y)} ("hash", "created_at") values(${T.hash}, ${T.folderMillis})`)}})}escapeName(W){return`"${W}"`}escapeParam(W){return`$${W+1}`}escapeString(W){return`'${W.replace(/'/g,"''")}'`}buildWithCTE(W){if(!W?.length)return;let $=[V`with `];for(let[X,Y]of W.entries())if($.push(V`${V.identifier(Y._.alias)} as (${Y._.sql})`),X<W.length-1)$.push(V`, `);return $.push(V` `),V.join($)}buildDeleteQuery({table:W,where:$,returning:X,withList:Y}){let G=this.buildWithCTE(Y),J=X?V` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,H=$?V` where ${$}`:void 0;return V`${G}delete from ${W}${H}${J}`}buildUpdateSet(W,$){let X=W[g.Symbol.Columns],Y=Object.keys(X).filter((J)=>$[J]!==void 0||X[J]?.onUpdateFn!==void 0),G=Y.length;return V.join(Y.flatMap((J,H)=>{let Q=X[J],z=$[J]??V.param(Q.onUpdateFn(),Q),T=V`${V.identifier(this.casing.getColumnCasing(Q))} = ${z}`;if(H<G-1)return[T,V.raw(", ")];return[T]}))}buildUpdateQuery({table:W,set:$,where:X,returning:Y,withList:G,from:J,joins:H}){let Q=this.buildWithCTE(G),z=W[V1.Symbol.Name],T=W[V1.Symbol.Schema],F=W[V1.Symbol.OriginalName],_=z===F?void 0:z,w=V`${T?V`${V.identifier(T)}.`:void 0}${V.identifier(F)}${_&&V` ${V.identifier(_)}`}`,O=this.buildUpdateSet(W,$),M=J&&V.join([V.raw(" from "),this.buildFromTable(J)]),A=this.buildJoins(H),I=Y?V` returning ${this.buildSelection(Y,{isSingleTable:!J})}`:void 0,j=X?V` where ${X}`:void 0;return V`${Q}update ${w} set ${O}${M}${A}${j}${I}`}buildSelection(W,{isSingleTable:$=!1}={}){let X=W.length,Y=W.flatMap(({field:G},J)=>{let H=[];if(L(G,p.Aliased)&&G.isSelectionField)H.push(V.identifier(G.fieldAlias));else if(L(G,p.Aliased)||L(G,p)){let Q=L(G,p.Aliased)?G.sql:G;if($)H.push(new p(Q.queryChunks.map((z)=>{if(L(z,f))return V.identifier(this.casing.getColumnCasing(z));return z})));else H.push(Q);if(L(G,p.Aliased))H.push(V` as ${V.identifier(G.fieldAlias)}`)}else if(L(G,q0))if($)H.push(V.identifier(this.casing.getColumnCasing(G)));else H.push(G);if(J<X-1)H.push(V`, `);return H});return V.join(Y)}buildJoins(W){if(!W||W.length===0)return;let $=[];for(let[X,Y]of W.entries()){if(X===0)$.push(V` `);let G=Y.table,J=Y.lateral?V` lateral`:void 0,H=Y.on?V` on ${Y.on}`:void 0;if(L(G,V1)){let Q=G[V1.Symbol.Name],z=G[V1.Symbol.Schema],T=G[V1.Symbol.OriginalName],F=Q===T?void 0:Y.alias;$.push(V`${V.raw(Y.joinType)} join${J} ${z?V`${V.identifier(z)}.`:void 0}${V.identifier(T)}${F&&V` ${V.identifier(F)}`}${H}`)}else if(L(G,g1)){let Q=G[f0].name,z=G[f0].schema,T=G[f0].originalName,F=Q===T?void 0:Y.alias;$.push(V`${V.raw(Y.joinType)} join${J} ${z?V`${V.identifier(z)}.`:void 0}${V.identifier(T)}${F&&V` ${V.identifier(F)}`}${H}`)}else $.push(V`${V.raw(Y.joinType)} join${J} ${G}${H}`);if(X<W.length-1)$.push(V` `)}return V.join($)}buildFromTable(W){if(L(W,g)&&W[g.Symbol.IsAlias]){let $=V`${V.identifier(W[g.Symbol.OriginalName])}`;if(W[g.Symbol.Schema])$=V`${V.identifier(W[g.Symbol.Schema])}.${$}`;return V`${$} ${V.identifier(W[g.Symbol.Name])}`}return W}buildSelectQuery({withList:W,fields:$,fieldsFlat:X,where:Y,having:G,table:J,joins:H,orderBy:Q,groupBy:z,limit:T,offset:F,lockingClause:_,distinct:w,setOperators:O}){let M=X??zW($);for(let U0 of M)if(L(U0.field,q0)&&w1(U0.field.table)!==(L(J,H1)?J._.alias:L(J,B6)?J[f0].name:L(J,p)?void 0:w1(J))&&!((e0)=>H?.some(({alias:M1})=>M1===(e0[g.Symbol.IsAlias]?w1(e0):e0[g.Symbol.BaseName])))(U0.field.table)){let e0=w1(U0.field.table);throw new Error(`Your "${U0.path.join("->")}" field references a column "${e0}"."${U0.field.name}", but the table "${e0}" is not part of the query! Did you forget to join it?`)}let A=!H||H.length===0,I=this.buildWithCTE(W),j;if(w)j=w===!0?V` distinct`:V` distinct on (${V.join(w.on,V`, `)})`;let R=this.buildSelection(M,{isSingleTable:A}),Z=this.buildFromTable(J),P=this.buildJoins(H),h=Y?V` where ${Y}`:void 0,x=G?V` having ${G}`:void 0,m;if(Q&&Q.length>0)m=V` order by ${V.join(Q,V`, `)}`;let w0;if(z&&z.length>0)w0=V` group by ${V.join(z,V`, `)}`;let p0=typeof T==="object"||typeof T==="number"&&T>=0?V` limit ${T}`:void 0,B=F?V` offset ${F}`:void 0,V0=V.empty();if(_){let U0=V` for ${V.raw(_.strength)}`;if(_.config.of)U0.append(V` of ${V.join(Array.isArray(_.config.of)?_.config.of:[_.config.of],V`, `)}`);if(_.config.noWait)U0.append(V` nowait`);else if(_.config.skipLocked)U0.append(V` skip locked`);V0.append(U0)}let $0=V`${I}select${j} ${R} from ${Z}${P}${h}${w0}${x}${m}${p0}${B}${V0}`;if(O.length>0)return this.buildSetOperations($0,O);return $0}buildSetOperations(W,$){let[X,...Y]=$;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(Y.length===0)return this.buildSetOperationQuery({leftSelect:W,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:W,setOperator:X}),Y)}buildSetOperationQuery({leftSelect:W,setOperator:{type:$,isAll:X,rightSelect:Y,limit:G,orderBy:J,offset:H}}){let Q=V`(${W.getSQL()}) `,z=V`(${Y.getSQL()})`,T;if(J&&J.length>0){let O=[];for(let M of J)if(L(M,f))O.push(V.identifier(M.name));else if(L(M,p)){for(let A=0;A<M.queryChunks.length;A++){let I=M.queryChunks[A];if(L(I,f))M.queryChunks[A]=V.identifier(I.name)}O.push(V`${M}`)}else O.push(V`${M}`);T=V` order by ${V.join(O,V`, `)} `}let F=typeof G==="object"||typeof G==="number"&&G>=0?V` limit ${G}`:void 0,_=V.raw(`${$} ${X?"all ":""}`),w=H?V` offset ${H}`:void 0;return V`${Q}${_}${z}${T}${F}${w}`}buildInsertQuery({table:W,values:$,onConflict:X,returning:Y,withList:G,select:J,overridingSystemValue_:H}){let Q=[],z=W[g.Symbol.Columns],T=Object.entries(z).filter(([I,j])=>!j.shouldDisableInsert()),F=T.map(([,I])=>V.identifier(this.casing.getColumnCasing(I)));if(J){let I=$;if(L(I,p))Q.push(I);else Q.push(I.getSQL())}else{let I=$;Q.push(V.raw("values "));for(let[j,R]of I.entries()){let Z=[];for(let[P,h]of T){let x=R[P];if(x===void 0||L(x,e1)&&x.value===void 0)if(h.defaultFn!==void 0){let m=h.defaultFn(),w0=L(m,p)?m:V.param(m,h);Z.push(w0)}else if(!h.default&&h.onUpdateFn!==void 0){let m=h.onUpdateFn(),w0=L(m,p)?m:V.param(m,h);Z.push(w0)}else Z.push(V`default`);else Z.push(x)}if(Q.push(Z),j<I.length-1)Q.push(V`, `)}}let _=this.buildWithCTE(G),w=V.join(Q),O=Y?V` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,M=X?V` on conflict ${X}`:void 0,A=H===!0?V`overriding system value `:void 0;return V`${_}insert into ${W} ${F} ${A}${w}${M}${O}`}buildRefreshMaterializedViewQuery({view:W,concurrently:$,withNoData:X}){let Y=$?V` concurrently`:void 0,G=X?V` with no data`:void 0;return V`refresh materialized view${Y} ${W}${G}`}prepareTyping(W){if(L(W,OY)||L(W,MY))return"json";else if(L(W,KY))return"decimal";else if(L(W,AY))return"time";else if(L(W,EY)||L(W,LY))return"timestamp";else if(L(W,DY)||L(W,VY))return"date";else if(L(W,BY))return"uuid";else return"none"}sqlToQuery(W,$){return W.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:$})}buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:X,table:Y,tableConfig:G,queryConfig:J,tableAlias:H,nestedQueryRelation:Q,joinOn:z}){let T=[],F,_,w=[],O,M=[];if(J===!0)T=Object.entries(G.columns).map(([j,R])=>({dbKey:R.name,tsKey:j,field:mW(R,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(G.columns).map(([x,m])=>[x,mW(m,H)]));if(J.where){let x=typeof J.where==="function"?J.where(I,vT()):J.where;O=x&&F6(x,H)}let j=[],R=[];if(J.columns){let x=!1;for(let[m,w0]of Object.entries(J.columns)){if(w0===void 0)continue;if(m in G.columns){if(!x&&w0===!0)x=!0;R.push(m)}}if(R.length>0)R=x?R.filter((m)=>J.columns?.[m]===!0):Object.keys(G.columns).filter((m)=>!R.includes(m))}else R=Object.keys(G.columns);for(let x of R){let m=G.columns[x];j.push({tsKey:x,value:m})}let Z=[];if(J.with)Z=Object.entries(J.with).filter((x)=>!!x[1]).map(([x,m])=>({tsKey:x,queryConfig:m,relation:G.relations[x]}));let P;if(J.extras){P=typeof J.extras==="function"?J.extras(I,{sql:V}):J.extras;for(let[x,m]of Object.entries(P))j.push({tsKey:x,value:n5(m,H)})}for(let{tsKey:x,value:m}of j)T.push({dbKey:L(m,p.Aliased)?m.fieldAlias:G.columns[x].name,tsKey:x,field:L(m,q0)?mW(m,H):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let h=typeof J.orderBy==="function"?J.orderBy(I,yT()):J.orderBy??[];if(!Array.isArray(h))h=[h];w=h.map((x)=>{if(L(x,q0))return mW(x,H);return F6(x,H)}),F=J.limit,_=J.offset;for(let{tsKey:x,queryConfig:m,relation:w0}of Z){let p0=gT($,X,w0),B=A8(w0.referencedTable),V0=X[B],$0=`${H}_${x}`,U0=V6(...p0.fields.map((VW,P8)=>RY(mW(p0.references[P8],$0),mW(VW,H)))),e0=this.buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:X,table:W[V0],tableConfig:$[V0],queryConfig:L(w0,y2)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:$0,joinOn:U0,nestedQueryRelation:w0}),M1=V`${V.identifier($0)}.${V.identifier("data")}`.as(x);M.push({on:V`true`,table:new H1(e0.sql,{},$0),alias:$0,joinType:"left",lateral:!0}),T.push({dbKey:x,tsKey:x,field:M1,relationTableTsKey:V0,isJson:!0,selection:e0.selection})}}if(T.length===0)throw new wY({message:`No fields selected for table "${G.tsName}" ("${H}")`});let A;if(O=V6(z,O),Q){let I=V`json_build_array(${V.join(T.map(({field:Z,tsKey:P,isJson:h})=>h?V`${V.identifier(`${H}_${P}`)}.${V.identifier("data")}`:L(Z,p.Aliased)?Z.sql:Z),V`, `)})`;if(L(Q,M6))I=V`coalesce(json_agg(${I}${w.length>0?V` order by ${V.join(w,V`, `)}`:void 0}), '[]'::json)`;let j=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:T}];if(F!==void 0||_!==void 0||w.length>0)A=this.buildSelectQuery({table:_Y(Y,H),fields:{},fieldsFlat:[{path:[],field:V.raw("*")}],where:O,limit:F,offset:_,orderBy:w,setOperators:[]}),O=void 0,F=void 0,_=void 0,w=[];else A=_Y(Y,H);A=this.buildSelectQuery({table:L(A,V1)?A:new H1(A,{},H),fields:{},fieldsFlat:j.map(({field:Z})=>({path:[],field:L(Z,q0)?mW(Z,H):Z})),joins:M,where:O,limit:F,offset:_,orderBy:w,setOperators:[]})}else A=this.buildSelectQuery({table:_Y(Y,H),fields:{},fieldsFlat:T.map(({field:I})=>({path:[],field:L(I,q0)?mW(I,H):I})),joins:M,where:O,limit:F,offset:_,orderBy:w,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:T}}}class E7{static[D]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class P1{static[D]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(W){if(this.fields=W.fields,this.session=W.session,this.dialect=W.dialect,W.withList)this.withList=W.withList;this.distinct=W.distinct}authToken;setToken(W){return this.authToken=W,this}from(W){let $=!!this.fields,X=W,Y;if(this.fields)Y=this.fields;else if(L(X,H1))Y=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(L(X,B6))Y=X[f0].selectedFields;else if(L(X,p))Y={};else Y=MQ(X);return new L7({table:X,fields:Y,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class QF extends E7{static[D]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:W,fields:$,isPartialSelect:X,session:Y,dialect:G,withList:J,distinct:H}){super();this.config={withList:J,table:W,fields:{...$},distinct:H,setOperators:[]},this.isPartialSelect=X,this.session=Y,this.dialect=G,this._={selectedFields:$},this.tableName=G2(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(W,$){return(X,Y)=>{let G=this.tableName,J=G2(X);if(typeof J==="string"&&this.config.joins?.some((H)=>H.alias===J))throw new Error(`Alias "${J}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof J==="string"&&!L(X,p)){let H=L(X,H1)?X._.selectedFields:L(X,g1)?X[f0].selectedFields:X[g.Symbol.Columns];this.config.fields[J]=H}}if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:Y,table:X,joinType:W,alias:J,lateral:$}),typeof J==="string")switch(W){case"left":{this.joinsNotNullableMap[J]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[J]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[J]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[J]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(W,$){return(X)=>{let Y=typeof X==="function"?X(rO()):X;if(!_6(this.getSelectedFields(),Y.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:W,isAll:$,rightSelect:Y}),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(W){return this.config.setOperators.push(...W),this}where(W){if(typeof W==="function")W=W(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=W,this}having(W){if(typeof W==="function")W=W(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=W,this}groupBy(...W){if(typeof W[0]==="function"){let $=W[0](new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray($)?$:[$]}else this.config.groupBy=W;return this}orderBy(...W){if(typeof W[0]==="function"){let $=W[0](new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let $=W;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}return this}limit(W){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=W;else this.config.limit=W;return this}offset(W){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=W;else this.config.offset=W;return this}for(W,$={}){return this.config.lockingClause={strength:W,config:$},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}as(W){return new Proxy(new H1(this.getSQL(),this.config.fields,W),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new n0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class L7 extends QF{static[D]="PgSelect";_prepare(W){let{session:$,config:X,dialect:Y,joinsNotNullableMap:G,authToken:J}=this;if(!$)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return C0.startActiveSpan("drizzle.prepareQuery",()=>{let H=zW(X.fields),Q=$.prepareQuery(Y.sqlToQuery(this.getSQL()),H,W,!0);return Q.joinsNotNullableMap=G,Q.setToken(J)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})}}VQ(L7,[j1]);function L4(W,$){return(X,Y,...G)=>{let J=[Y,...G].map((H)=>({type:W,isAll:$,rightSelect:H}));for(let H of J)if(!_6(X.getSelectedFields(),H.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(J)}}var rO=()=>({union:tO,unionAll:aO,intersect:sO,intersectAll:eO,except:WK,exceptAll:$K}),tO=L4("union",!1),aO=L4("union",!0),sO=L4("intersect",!1),eO=L4("intersect",!0),WK=L4("except",!1),$K=L4("except",!0);class R6{static[D]="PgQueryBuilder";dialect;dialectConfig;constructor(W){this.dialect=L(W,N8)?W:void 0,this.dialectConfig=L(W,N8)?void 0:W}$with=(W,$)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(X);return new Proxy(new Q6(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),W,!0),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...W){let $=this;function X(J){return new P1({fields:J??void 0,session:void 0,dialect:$.getDialect(),withList:W})}function Y(J){return new P1({fields:J??void 0,session:void 0,dialect:$.getDialect(),distinct:!0})}function G(J,H){return new P1({fields:H??void 0,session:void 0,dialect:$.getDialect(),distinct:{on:J}})}return{select:X,selectDistinct:Y,selectDistinctOn:G}}select(W){return new P1({fields:W??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(W){return new P1({fields:W??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(W,$){return new P1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:W}})}getDialect(){if(!this.dialect)this.dialect=new N8(this.dialectConfig);return this.dialect}}class hY{constructor(W,$,X,Y,G){this.table=W,this.session=$,this.dialect=X,this.withList=Y,this.overridingSystemValue_=G}static[D]="PgInsertBuilder";authToken;setToken(W){return this.authToken=W,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(W){if(W=Array.isArray(W)?W:[W],W.length===0)throw new Error("values() must be called with at least one value");let $=W.map((X)=>{let Y={},G=this.table[g.Symbol.Columns];for(let J of Object.keys(X)){let H=X[J];Y[J]=L(H,p)?H:new e1(H,G[J])}return Y});return new B7(this.table,$,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(W){let $=typeof W==="function"?W(new R6):W;if(!L($,p)&&!_6(this.table[TY],$._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new B7(this.table,$,this.session,this.dialect,this.withList,!0)}}class B7 extends j1{constructor(W,$,X,Y,G,J,H){super();this.session=X,this.dialect=Y,this.config={table:W,values:$,withList:G,select:J,overridingSystemValue_:H}}static[D]="PgInsert";config;returning(W=this.config.table[g.Symbol.Columns]){return this.config.returningFields=W,this.config.returning=zW(W),this}onConflictDoNothing(W={}){if(W.target===void 0)this.config.onConflict=V`do nothing`;else{let $="";$=Array.isArray(W.target)?W.target.map((Y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target));let X=W.where?V` where ${W.where}`:void 0;this.config.onConflict=V`(${V.raw($)})${X} do nothing`}return this}onConflictDoUpdate(W){if(W.where&&(W.targetWhere||W.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 $=W.where?V` where ${W.where}`:void 0,X=W.targetWhere?V` where ${W.targetWhere}`:void 0,Y=W.setWhere?V` where ${W.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,UY(this.config.table,W.set)),J="";return J=Array.isArray(W.target)?W.target.map((H)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(H))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target)),this.config.onConflict=V`(${V.raw(J)})${X} do update set ${G}${$}${Y}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new n0({alias:w1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class R7 extends j1{constructor(W,$,X){super();this.session=$,this.dialect=X,this.config={view:W}}static[D]="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:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})}}class gY{constructor(W,$,X,Y){this.table=W,this.session=$,this.dialect=X,this.withList=Y}static[D]="PgUpdateBuilder";authToken;setToken(W){return this.authToken=W,this}set(W){return new zF(this.table,UY(this.table,W),this.session,this.dialect,this.withList).setToken(this.authToken)}}class zF extends j1{constructor(W,$,X,Y,G){super();this.session=X,this.dialect=Y,this.config={set:$,table:W,withList:G,joins:[]},this.tableName=G2(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[D]="PgUpdate";config;tableName;joinsNotNullableMap;from(W){let $=W,X=G2($);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=$,this}getTableLikeFields(W){if(L(W,V1))return W[g.Symbol.Columns];else if(L(W,H1))return W._.selectedFields;return W[f0].selectedFields}createJoin(W){return($,X)=>{let Y=G2($);if(typeof Y==="string"&&this.config.joins.some((G)=>G.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(typeof X==="function"){let G=this.config.from&&!L(this.config.from,p)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[g.Symbol.Columns],new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:$,joinType:W,alias:Y}),typeof Y==="string")switch(W){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[Y]=!0;break}case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[Y]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(W){return this.config.where=W,this}returning(W){if(!W){if(W=Object.assign({},this.config.table[g.Symbol.Columns]),this.config.from){let $=G2(this.config.from);if(typeof $==="string"&&this.config.from&&!L(this.config.from,p)){let X=this.getTableLikeFields(this.config.from);W[$]=X}for(let X of this.config.joins){let Y=G2(X.table);if(typeof Y==="string"&&!L(X.table,p)){let G=this.getTableLikeFields(X.table);W[Y]=G}}}}return this.config.returningFields=W,this.config.returning=zW(W),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){let $=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0);return $.joinsNotNullableMap=this.joinsNotNullableMap,$}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return this._prepare().execute(W,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new n0({alias:w1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class N6 extends p{constructor(W){super(N6.buildEmbeddedCount(W.source,W.filters).queryChunks);this.params=W,this.mapWith(Number),this.session=W.session,this.sql=N6.buildCount(W.source,W.filters)}sql;token;static[D]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(W,$){return V`(select count(*) from ${W}${V.raw(" where ").if($)}${$})`}static buildCount(W,$){return V`select count(*) as count from ${W}${V.raw(" where ").if($)}${$};`}setToken(W){return this.token=W,this}then(W,$){return Promise.resolve(this.session.count(this.sql,this.token)).then(W,$)}catch(W){return this.then(void 0,W)}finally(W){return this.then(($)=>{return W?.(),$},($)=>{throw W?.(),$})}}class Z7{constructor(W,$,X,Y,G,J,H){this.fullSchema=W,this.schema=$,this.tableNamesMap=X,this.table=Y,this.tableConfig=G,this.dialect=J,this.session=H}static[D]="PgRelationalQueryBuilder";findMany(W){return new N7(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?W:{},"many")}findFirst(W){return new N7(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?{...W,limit:1}:{limit:1},"first")}}class N7 extends j1{constructor(W,$,X,Y,G,J,H,Q,z){super();this.fullSchema=W,this.schema=$,this.tableNamesMap=X,this.table=Y,this.tableConfig=G,this.dialect=J,this.session=H,this.config=Q,this.mode=z}static[D]="PgRelationalQuery";_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:$,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,W,!0,(Y,G)=>{let J=Y.map((H)=>ZY(this.schema,this.tableConfig,H,$.selection,G));if(this.mode==="first")return J[0];return J})})}prepare(W){return this._prepare(W)}_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 W=this._getQuery(),$=this.dialect.sqlToQuery(W.sql);return{query:W,builtQuery:$}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(W){return this.authToken=W,this}execute(){return C0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class S7 extends j1{constructor(W,$,X,Y){super();this.execute=W,this.sql=$,this.query=X,this.mapBatchResult=Y}static[D]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(W,$){return $?this.mapBatchResult(W):W}_prepare(){return this}isResponseInArrayMode(){return!1}}class Z6{constructor(W,$,X){if(this.dialect=W,this.session=$,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:$}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:$},this.query={},this._.schema)for(let[Y,G]of Object.entries(this._.schema))this.query[Y]=new Z7(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[Y],G,W,$)}static[D]="PgDatabase";query;$with=(W,$)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new R6(X.dialect));return new Proxy(new Q6(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),W,!0),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(W,$){return new N6({source:W,filters:$,session:this.session})}with(...W){let $=this;function X(z){return new P1({fields:z??void 0,session:$.session,dialect:$.dialect,withList:W})}function Y(z){return new P1({fields:z??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:!0})}function G(z,T){return new P1({fields:T??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:{on:z}})}function J(z){return new gY(z,$.session,$.dialect,W)}function H(z){return new hY(z,$.session,$.dialect,W)}function Q(z){return new yY(z,$.session,$.dialect,W)}return{select:X,selectDistinct:Y,selectDistinctOn:G,update:J,insert:H,delete:Q}}select(W){return new P1({fields:W??void 0,session:this.session,dialect:this.dialect})}selectDistinct(W){return new P1({fields:W??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(W,$){return new P1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:{on:W}})}update(W){return new gY(W,this.session,this.dialect)}insert(W){return new hY(W,this.session,this.dialect)}delete(W){return new yY(W,this.session,this.dialect)}refreshMaterializedView(W){return new R7(W,this.session,this.dialect)}authToken;execute(W){let $=typeof W==="string"?V.raw(W):W.getSQL(),X=this.dialect.sqlToQuery($),Y=this.session.prepareQuery(X,void 0,void 0,!1);return new S7(()=>Y.execute(void 0,this.authToken),$,X,(G)=>Y.mapResult(G,!0))}transaction(W,$){return this.session.transaction(W,$)}}class TF{constructor(W,$){this.unique=W,this.name=$}static[D]="PgIndexBuilderOn";on(...W){return new mY(W.map(($)=>{if(L($,p))return $;$=$;let X=new J6($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...W){return new mY(W.map(($)=>{if(L($,p))return $;$=$;let X=new J6($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=$.defaultConfig,X}),this.unique,!0,this.name)}using(W,...$){return new mY($.map((X)=>{if(L(X,p))return X;X=X;let Y=new J6(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),Y}),this.unique,!0,this.name,W)}}class mY{static[D]="PgIndexBuilder";config;constructor(W,$,X,Y,G="btree"){this.config={name:Y,columns:W,unique:$,only:X,method:G}}concurrently(){return this.config.concurrently=!0,this}with(W){return this.config.with=W,this}where(W){return this.config.where=W,this}build(W){return new FF(this.config,W)}}class FF{static[D]="PgIndex";config;constructor(W,$){this.config={...W,table:$}}}function q7(W){return new TF(!0,W)}class C7{constructor(W){this.query=W}authToken;getQuery(){return this.query}mapResult(W,$){return W}setToken(W){return this.authToken=W,this}static[D]="PgPreparedQuery";joinsNotNullableMap}class k7{constructor(W){this.dialect=W}static[D]="PgSession";execute(W,$){return C0.startActiveSpan("drizzle.operation",()=>{return C0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(W),void 0,void 0,!1)}).setToken($).execute(void 0,$)})}all(W){return this.prepareQuery(this.dialect.sqlToQuery(W),void 0,void 0,!1).all()}async count(W,$){let X=await this.execute(W,$);return Number(X[0].count)}}class j7 extends Z6{constructor(W,$,X,Y=0){super(W,$,X);this.schema=X,this.nestedIndex=Y}static[D]="PgTransaction";rollback(){throw new r5}getTransactionConfigSQL(W){let $=[];if(W.isolationLevel)$.push(`isolation level ${W.isolationLevel}`);if(W.accessMode)$.push(W.accessMode);if(typeof W.deferrable==="boolean")$.push(W.deferrable?"deferrable":"not deferrable");return V.raw($.join(" "))}setTransaction(W){return this.session.execute(V`set transaction ${this.getTransactionConfigSQL(W)}`)}}class _F extends C7{constructor(W,$,X,Y,G,J,H){super({sql:$,params:X});this.client=W,this.queryString=$,this.params=X,this.logger=Y,this.fields=G,this._isResponseInArrayMode=J,this.customResultMapper=H}static[D]="PostgresJsPreparedQuery";async execute(W={}){return C0.startActiveSpan("drizzle.execute",async($)=>{let X=i5(this.params,W);$?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:Y,queryString:G,client:J,joinsNotNullableMap:H,customResultMapper:Q}=this;if(!Y&&!Q)return C0.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(G,X)});let z=await C0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),J.unsafe(G,X).values()});return C0.startActiveSpan("drizzle.mapResponse",()=>{return Q?Q(z):z.map((T)=>DQ(Y,T,H))})})}all(W={}){return C0.startActiveSpan("drizzle.execute",async($)=>{let X=i5(this.params,W);return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),C0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.client.unsafe(this.queryString,X)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class S6 extends k7{constructor(W,$,X,Y={}){super($);this.client=W,this.schema=X,this.options=Y,this.logger=Y.logger??new a5}static[D]="PostgresJsSession";logger;prepareQuery(W,$,X,Y,G){return new _F(this.client,W.sql,W.params,this.logger,$,Y,G)}query(W,$){return this.logger.logQuery(W,$),this.client.unsafe(W,$).values()}queryObjects(W,$){return this.client.unsafe(W,$)}transaction(W,$){return this.client.begin(async(X)=>{let Y=new S6(X,this.dialect,this.schema,this.options),G=new I7(this.dialect,Y,this.schema);if($)await G.setTransaction($);return W(G)})}}class I7 extends j7{constructor(W,$,X,Y=0){super(W,$,X,Y);this.session=$}static[D]="PostgresJsTransaction";transaction(W){return this.session.client.savepoint(($)=>{let X=new S6($,this.dialect,this.schema,this.session.options),Y=new I7(this.dialect,X,this.schema);return W(Y)})}}class wF extends Z6{static[D]="PostgresJsDatabase"}function B4(W,$={}){let X=(z)=>z;for(let z of["1184","1082","1083","1114","1182","1185","1115","1231"])W.options.parsers[z]=X,W.options.serializers[z]=X;W.options.serializers["114"]=X,W.options.serializers["3802"]=X;let Y=new N8({casing:$.casing}),G;if($.logger===!0)G=new t5;else if($.logger!==!1)G=$.logger;let J;if($.schema){let z=hT($.schema,mT);J={fullSchema:$.schema,schema:z.tables,tableNamesMap:z.tableNamesMap}}let H=new S6(W,Y,J,{logger:G}),Q=new wF(Y,H,J);return Q.$client=W,Q}function pY(...W){if(typeof W[0]==="string"){let $=E4(W[0]);return B4($,W[1])}if(OQ(W[0])){let{connection:$,client:X,...Y}=W[0];if(X)return B4(X,Y);if(typeof $==="object"&&$.url!==void 0){let{url:J,...H}=$,Q=E4(J,H);return B4(Q,Y)}let G=E4($);return B4(G,Y)}return B4(W[0],W[1])}((W)=>{function $(X){return B4({options:{parsers:{},serializers:{}}},X)}W.mock=$})(pY||(pY={}));function UF(W,$){if(W instanceof Promise)throw new Error($)}function XK(W,$){let X={},Y=[];for(let G in W){let J=W[G]["~standard"].validate($[G]);if(UF(J,`Validation must be synchronous, but ${G} returned a Promise.`),J.issues){Y.push(...J.issues.map((H)=>({...H,path:[G,...H.path??[]]})));continue}X[G]=J.value}if(Y.length)return{issues:Y};return{value:X}}function P7(W){let $=W.runtimeEnvStrict??W.runtimeEnv??process.env;if(W.emptyStringAsUndefined??!1){for(let[R,Z]of Object.entries($))if(Z==="")delete $[R]}if(!!W.skipValidation)return $;let G=typeof W.client==="object"?W.client:{},J=typeof W.server==="object"?W.server:{},H=typeof W.shared==="object"?W.shared:{},Q=W.isServer??(typeof window==="undefined"||("Deno"in window)),z=Q?{...J,...H,...G}:{...G,...H},T=W.createFinalSchema?.(z,Q)["~standard"].validate($)??XK(z,$);UF(T,"Validation must be synchronous");let F=W.onValidationError??((R)=>{throw console.error("\u274C Invalid environment variables:",R),new Error("Invalid environment variables")}),_=W.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(T.issues)return F(T.issues);let w=(R)=>{if(!W.clientPrefix)return!0;return!R.startsWith(W.clientPrefix)&&!(R in H)},O=(R)=>{return Q||!w(R)},M=(R)=>{return R==="__esModule"||R==="$$typeof"},A=(W.extends??[]).reduce((R,Z)=>{return Object.assign(R,Z)},{}),I=Object.assign(A,T.value);return new Proxy(I,{get(R,Z){if(typeof Z!=="string")return;if(M(Z))return;if(!O(Z))return _(Z);return Reflect.get(R,Z)}})}var g2=(W)=>Array.isArray(W)?W:[W],DF=(W,$)=>{let X=[[],[]];for(let Y of W)if($(Y))X[0].push(Y);else X[1].push(Y);return X},uY=Array,H2=(W,$)=>W.includes($),VF=(W,$=0)=>[...new Array(W)].map((X,Y)=>Y+$),D0=(W,$,X)=>{if(W===void 0)return $===void 0?[]:Array.isArray($)?$:[$];if(X?.prepend)if(Array.isArray($))W.unshift(...$);else W.unshift($);else if(Array.isArray($))W.push(...$);else W.push($);return W},Q2=(W,$)=>{if($===void 0||$===null)return W??[];if(W===void 0||W===null)return g2($);return W.concat($)},MF=(...W)=>W.reduce(Q2,[]),uW=(W,$,X)=>{if(W===void 0)return Array.isArray($)?$:[$];let Y=X?.isEqual??((G,J)=>G===J);for(let G of g2($))if(!W.some((J)=>Y(J,G)))W.push(G);return W},OF=(W,$)=>W.reduce((X,Y)=>{let G=Y[$];return X[G]=D0(X[G],Y),X},{}),z2=(W,$,X)=>W.length===$.length&&W.every(X?.isEqual?(Y,G)=>X.isEqual(Y,$[G]):(Y,G)=>Y===$[G]);var p1=(W,$)=>z1(W)===$,z1=(W)=>{let $=typeof W;return $==="object"?W===null?"null":"object":$==="function"?"object":$},u1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},KF={...u1,function:"a function"};class AF extends Error{}var K0=(W)=>Z8(W,AF),Z8=(W,$=Error)=>{throw new $(W)};class q6 extends Error{name="ParseError"}var E=(W)=>Z8(W,q6),SW=(W)=>` ${W}`;var Y0=(W,$)=>{let X={},Y=Array.isArray(W),G=!1;for(let[J,H]of Object.entries(W).entries()){let Q=Y?$(J,H[1]):$(...H,J);G||=typeof Q[0]==="number";let z=Array.isArray(Q[0])||Q.length===0?Q:[Q];for(let[T,F]of z)if(typeof T==="object")X[T.group]=D0(X[T.group],F);else X[T]=F}return G?Object.values(X):X};var f7=Object.entries;var T1=(W,$)=>(W in $),R4=(W,$)=>($ in W);class x7{constructor(W){Object.assign(this,W)}}var EF=class{};class C6 extends EF{}var YK=(W,$)=>{let X={},Y={},G;for(G in W)if(G in $)X[G]=W[G];else Y[G]=W[G];return[X,Y]};var LF=(W,$)=>YK(W,$)[1],cW=(W)=>Object.keys(W).length===0,S8=(W)=>[...Object.entries(W),...Object.getOwnPropertySymbols(W).map(($)=>[$,W[$]])],BF=(W,$)=>Object.defineProperties(W,Object.getOwnPropertyDescriptors($)),RF=(W)=>{let $=Object.keys(W).sort(),X={};for(let Y=0;Y<$.length;Y++)X[$[Y]]=W[$[Y]];return X};var $W=SW("represents an uninitialized value"),NF=(W)=>Object.values(W).filter(($)=>{if(typeof $==="number")return!0;return typeof W[$]!=="number"});var b7={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},v7=globalThis.File??Blob,y7={ArrayBuffer,Blob,File:v7,FormData,Headers,Request,Response,URL},GK={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},q8={...b7,...y7,...GK,String,Number,Boolean},k6=(W)=>{let $=Object.getPrototypeOf(W);while($?.constructor&&(!T1($.constructor.name,q8)||!(W instanceof q8[$.constructor.name])))$=Object.getPrototypeOf($);let X=$?.constructor?.name;if(X===void 0||X==="Object")return;return X},j6=(W)=>typeof W==="object"&&W!==null?k6(W)??"object":z1(W);var k0=Array.isArray,JK={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},HK={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},QK={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},ZF={...JK,...HK,...QK},I6=(W)=>{let $=Object(W).name??null;return $&&T1($,q8)&&q8[$]===W?$:null};var h7=(W,$)=>{let X=W.prototype;while(X!==null){if(X===$.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var SF=(W)=>qF(W,new Map),qF=(W,$)=>{if(typeof W!=="object"||W===null)return W;if($?.has(W))return $.get(W);let X=I6(W.constructor);if(X==="Date")return new Date(W.getTime());if(X&&X!=="Array")return W;let Y=Array.isArray(W)?W.slice():Object.create(Object.getPrototypeOf(W)),G=Object.getOwnPropertyDescriptors(W);if($){$.set(W,Y);for(let J in G){let H=G[J];if("get"in H||"set"in H)continue;H.value=qF(H.value,$)}}return Object.defineProperties(Y,G),Y};var zK=(W)=>{let $=$W;return()=>$===$W?$=W():$},m2=(W)=>typeof W==="function"&&W.length===0;var CF=class extends Function{constructor(...W){let $=W.slice(0,-1),X=W.at(-1);try{super(...$,X)}catch(Y){return K0(`Encountered an unexpected error while compiling your definition:
84
84
  Message: ${Y}
85
85
  Source: (${W.slice(0,-1)}) => {
86
86
  ${W.at(-1)}
87
- }`)}}};class SW{constructor(W,...[$]){return Object.assign(Object.setPrototypeOf(W.bind($?.bind??this),this.constructor.prototype),$?.attach)}}var qT=HK(()=>{try{return new Function("return false")()}catch{return!0}});var op=ZW("brand");var CT=ZW("arkInferred");var rp=ZW("args");class R1{constructor(){}}var QK=()=>{try{return((new Error().stack?.split(`
88
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},zK=globalThis.process?.env??{},kT={fileName:QK,env:zK};var jT=(W)=>W[0].toUpperCase()+W.slice(1);var y5=(W)=>new RegExp(FK(W),typeof W==="string"?"":W.flags);var FK=(W)=>{return`^(?:${typeof W==="string"?W:W.source})$`};var F2={negativeLookahead:(W)=>`(?!${W})`,nonCapturingGroup:(W)=>`(?:${W})`},j6="\\",h2={" ":1,"\n":1,"\t":1};var TK=/^-0\.?0*$/.source,fT=/[1-9]\d*/.source,UK=/\.\d+/.source,wK=/\.\d*[1-9]/.source,PT=(W)=>y5(F2.negativeLookahead(TK)+F2.nonCapturingGroup("-?"+F2.nonCapturingGroup(F2.nonCapturingGroup("0|"+fT)+F2.nonCapturingGroup(W.decimalPattern)+"?")+(W.allowDecimalOnly?"|"+W.decimalPattern:"")+"?")),IT=PT({decimalPattern:wK,allowDecimalOnly:!1}),_K=IT.test.bind(IT),cY=PT({decimalPattern:UK,allowDecimalOnly:!0}),Xu=cY.test.bind(cY),DK=/^-?\d*\.?\d*$/,MK=(W)=>W.length!==0&&DK.test(W),I6=y5(F2.negativeLookahead("^-0$")+"-?"+F2.nonCapturingGroup(F2.nonCapturingGroup("0|"+fT))),VK=I6.test.bind(I6),h5=/^-?\d+$/,OK=h5.test.bind(h5),xT={number:"a number",bigint:"a bigint",integer:"an integer"},vT=(W,$)=>`'${W}' was parsed as ${xT[$]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,KK=(W,$)=>$==="number"?_K(W):VK(W),AK=(W,$)=>$==="number"?Number(W):Number.parseInt(W),EK=(W,$)=>$==="number"?MK(W):OK(W),bT=(W,$)=>g5(W,"number",$),yT=(W,$)=>g5(W,"number",{...$,strict:!0}),hT=(W,$)=>g5(W,"integer",$),g5=(W,$,X)=>{let Y=AK(W,$);if(!Number.isNaN(Y)){if(EK(W,$)){if(X?.strict)return KK(W,$)?Y:A(vT(W,$));return Y}}return X?.errorOnFail?A(X?.errorOnFail===!0?`Failed to parse ${xT[$]} from '${W}'`:X?.errorOnFail):void 0},gT=(W)=>{if(W[W.length-1]!=="n")return;let $=W.slice(0,-1),X;try{X=BigInt($)}catch{return}if(I6.test($))return X;if(h5.test($))return A(vT(W,"bigint"))};var LK="0.46.0",BK={version:LK,filename:kT.fileName(),FileConstructor:x5},Z8=BK,mT=new Map,m5=Object.create(null),f6=(W)=>{let $=mT.get(W);if($)return $;let X=RK(W);if(m5[X])X=`${X}${m5[X]++}`;else m5[X]=1;return Z8[X]=W,mT.set(W,X),X},g2=(W)=>/^[$A-Z_a-z][\w$]*$/.test(W),RK=(W)=>{switch(typeof W){case"object":{if(W===null)break;let $=q6(W)??"object";return $[0].toLowerCase()+$.slice(1)}case"function":return g2(W.name)?W.name:"fn";case"symbol":return W.description&&g2(W.description)?W.description:"symbol"}return K0(`Unexpected attempt to register serializable value of type ${z1(W)}`)};var P6=(W)=>typeof W==="string"?JSON.stringify(W):typeof W==="bigint"?`${W}n`:`${W}`;var pT=(W,$={})=>x6(W,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...$},[]);var Y0=(W,$)=>{switch(z1(W)){case"object":let X=W,Y=X.constructor.name;return Y==="Object"||Y==="Array"?$?.quoteKeys===!1?dY(X,$?.indent??0,""):JSON.stringify(x6(X,B$,[]),null,$?.indent):dY(X,$?.indent??0,"");case"symbol":return B$.onSymbol(W);default:return P6(W)}},dY=(W,$,X)=>{if(typeof W==="function")return B$.onFunction(W);if(typeof W!=="object"||W===null)return P6(W);let Y=X+" ".repeat($);if(Array.isArray(W)){if(W.length===0)return"[]";let G=W.map((H)=>dY(H,$,Y)).join(`,
87
+ }`)}}};class qW{constructor(W,...[$]){return Object.assign(Object.setPrototypeOf(W.bind($?.bind??this),this.constructor.prototype),$?.attach)}}var kF=zK(()=>{try{return new Function("return false")()}catch{return!0}});var Tu=SW("brand");var jF=SW("arkInferred");var wu=SW("args");class R1{constructor(){}}var TK=()=>{try{return((new Error().stack?.split(`
88
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},FK=globalThis.process?.env??{},IF={fileName:TK,env:FK};var PF=(W)=>W[0].toUpperCase()+W.slice(1);var g7=(W)=>new RegExp(_K(W),typeof W==="string"?"":W.flags);var _K=(W)=>{return`^(?:${typeof W==="string"?W:W.source})$`};var T2={negativeLookahead:(W)=>`(?!${W})`,nonCapturingGroup:(W)=>`(?:${W})`},P6="\\",p2={" ":1,"\n":1,"\t":1};var wK=/^-0\.?0*$/.source,xF=/[1-9]\d*/.source,UK=/\.\d+/.source,DK=/\.\d*[1-9]/.source,bF=(W)=>g7(T2.negativeLookahead(wK)+T2.nonCapturingGroup("-?"+T2.nonCapturingGroup(T2.nonCapturingGroup("0|"+xF)+T2.nonCapturingGroup(W.decimalPattern)+"?")+(W.allowDecimalOnly?"|"+W.decimalPattern:"")+"?")),fF=bF({decimalPattern:DK,allowDecimalOnly:!1}),VK=fF.test.bind(fF),cY=bF({decimalPattern:UK,allowDecimalOnly:!0}),Au=cY.test.bind(cY),MK=/^-?\d*\.?\d*$/,OK=(W)=>W.length!==0&&MK.test(W),f6=g7(T2.negativeLookahead("^-0$")+"-?"+T2.nonCapturingGroup(T2.nonCapturingGroup("0|"+xF))),KK=f6.test.bind(f6),m7=/^-?\d+$/,AK=m7.test.bind(m7),vF={number:"a number",bigint:"a bigint",integer:"an integer"},yF=(W,$)=>`'${W}' was parsed as ${vF[$]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,EK=(W,$)=>$==="number"?VK(W):KK(W),LK=(W,$)=>$==="number"?Number(W):Number.parseInt(W),BK=(W,$)=>$==="number"?OK(W):AK(W),hF=(W,$)=>p7(W,"number",$),gF=(W,$)=>p7(W,"number",{...$,strict:!0}),mF=(W,$)=>p7(W,"integer",$),p7=(W,$,X)=>{let Y=LK(W,$);if(!Number.isNaN(Y)){if(BK(W,$)){if(X?.strict)return EK(W,$)?Y:E(yF(W,$));return Y}}return X?.errorOnFail?E(X?.errorOnFail===!0?`Failed to parse ${vF[$]} from '${W}'`:X?.errorOnFail):void 0},pF=(W)=>{if(W[W.length-1]!=="n")return;let $=W.slice(0,-1),X;try{X=BigInt($)}catch{return}if(f6.test($))return X;if(m7.test($))return E(yF(W,"bigint"))};var RK="0.46.0",NK={version:RK,filename:IF.fileName(),FileConstructor:v7},C8=NK,uF=new Map,u7=Object.create(null),x6=(W)=>{let $=uF.get(W);if($)return $;let X=ZK(W);if(u7[X])X=`${X}${u7[X]++}`;else u7[X]=1;return C8[X]=W,uF.set(W,X),X},u2=(W)=>/^[$A-Z_a-z][\w$]*$/.test(W),ZK=(W)=>{switch(typeof W){case"object":{if(W===null)break;let $=k6(W)??"object";return $[0].toLowerCase()+$.slice(1)}case"function":return u2(W.name)?W.name:"fn";case"symbol":return W.description&&u2(W.description)?W.description:"symbol"}return K0(`Unexpected attempt to register serializable value of type ${z1(W)}`)};var b6=(W)=>typeof W==="string"?JSON.stringify(W):typeof W==="bigint"?`${W}n`:`${W}`;var cF=(W,$={})=>v6(W,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...$},[]);var G0=(W,$)=>{switch(z1(W)){case"object":let X=W,Y=X.constructor.name;return Y==="Object"||Y==="Array"?$?.quoteKeys===!1?dY(X,$?.indent??0,""):JSON.stringify(v6(X,N4,[]),null,$?.indent):dY(X,$?.indent??0,"");case"symbol":return N4.onSymbol(W);default:return b6(W)}},dY=(W,$,X)=>{if(typeof W==="function")return N4.onFunction(W);if(typeof W!=="object"||W===null)return b6(W);let Y=X+" ".repeat($);if(Array.isArray(W)){if(W.length===0)return"[]";let J=W.map((H)=>dY(H,$,Y)).join(`,
89
89
  `+Y);return $?`[
90
- ${Y}${G}
91
- ${X}]`:`[${G}]`}let J=W.constructor.name;if(J==="Object"){let G=R8(W).map(([H,Q])=>{let z=typeof H==="symbol"?B$.onSymbol(H):g2(H)?H:JSON.stringify(H),F=dY(Q,$,Y);return`${Y}${z}: ${F}`});if(G.length===0)return"{}";return $?`{
92
- ${G.join(`,
90
+ ${Y}${J}
91
+ ${X}]`:`[${J}]`}let G=W.constructor.name;if(G==="Object"){let J=S8(W).map(([H,Q])=>{let z=typeof H==="symbol"?N4.onSymbol(H):u2(H)?H:JSON.stringify(H),T=dY(Q,$,Y);return`${Y}${z}: ${T}`});if(J.length===0)return"{}";return $?`{
92
+ ${J.join(`,
93
93
  `)}
94
- ${X}}`:`{${G.join(", ")}}`}if(W instanceof Date)return S8(W);if("expression"in W&&typeof W.expression==="string")return W.expression;return J},B$={onCycle:()=>"(cycle)",onSymbol:(W)=>`Symbol(${f6(W)})`,onFunction:(W)=>`Function(${f6(W)})`},x6=(W,$,X)=>{switch(z1(W)){case"object":{let Y=W;if("toJSON"in Y&&typeof Y.toJSON==="function")return Y.toJSON();if(typeof Y==="function")return B$.onFunction(Y);if(X.includes(Y))return"(cycle)";let J=[...X,Y];if(Array.isArray(Y))return Y.map((H)=>x6(H,$,J));if(Y instanceof Date)return Y.toDateString();let G={};for(let H in Y)G[H]=x6(Y[H],$,J);for(let H of Object.getOwnPropertySymbols(Y))G[$.onSymbol?.(H)??H.toString()]=x6(Y[H],$,J);return G}case"symbol":return B$.onSymbol(W);case"bigint":return $.onBigInt?.(W)??`${W}n`;case"undefined":return $.onUndefined??"undefined";case"string":return W.replaceAll("\\","\\\\");default:return W}},S8=(W)=>{let $=W.getFullYear(),X=W.getMonth(),Y=W.getDate(),J=W.getHours(),G=W.getMinutes(),H=W.getSeconds(),Q=W.getMilliseconds();if(X===0&&Y===1&&J===0&&G===0&&H===0&&Q===0)return`${$}`;let z=`${NK[X]} ${Y}, ${$}`;if(J===0&&G===0&&H===0&&Q===0)return z;let F=W.toLocaleTimeString(),T=F.endsWith(" AM")||F.endsWith(" PM")?F.slice(-3):"";if(T)F=F.slice(0,-T.length);if(Q)F+=`.${SK(Q,3)}`;else if(ZK.test(F))F=F.slice(0,-3);return`${F+T}, ${z}`},NK=["January","February","March","April","May","June","July","August","September","October","November","December"],ZK=/:\d\d:00$/,SK=(W,$)=>String(W).padStart($,"0");var uT=(W,$,...[X])=>{let Y=X?.stringifySymbol??Y0,J=W;switch(typeof $){case"string":J=g2($)?W===""?$:`${W}.${$}`:`${W}[${JSON.stringify($)}]`;break;case"number":J=`${W}[${$}]`;break;case"symbol":J=`${W}[${Y($)}]`;break;default:if(X?.stringifyNonKey)J=`${W}[${X.stringifyNonKey($)}]`;else A(`${Y0($)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return J},T2=(W,...$)=>W.reduce((X,Y)=>uT(X,Y,...$),"");class v6 extends uY{cache={};constructor(...W){super();this.push(...W)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let W=0;W<this.length;W++)this.cache.json.push(typeof this[W]==="symbol"?Y0(this[W]):this[W]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=T2(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let W="",$=[W];for(let X of this)W=uT(W,X),$.push(W);return this.cache.stringifyAncestors=$}}class p5{chars;i;def;constructor(W){this.def=W,this.chars=[...W],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(W){let $="";while(this.lookahead){if(W(this,$))if($[$.length-1]===j6)$=$.slice(0,-1);else break;$+=this.shift()}return $}shiftUntilLookahead(W){return typeof W==="string"?this.shiftUntil(($)=>$.lookahead===W):this.shiftUntil(($)=>($.lookahead in W))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in h2))}jumpToIndex(W){this.i=W<0?this.length+W:W}jumpForward(W){this.i+=W}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(W,$){return this.chars.slice(W,$).join("")}lookaheadIs(W){return this.lookahead===W}lookaheadIsIn(W){return this.lookahead in W}}var qu=ZW("implementedTraits");var u5="$ark",qK=2;while(u5 in globalThis)u5=`$ark${qK++}`;var cT=u5;globalThis[cT]=Z8;var N=Z8,CK=(W)=>`${cT}.${W}`,d0=(W)=>CK(f6(W));class lY extends S6{argNames;body="";constructor(...W){super();this.argNames=W;for(let $ of W){if($ in this)throw new Error(`Arg name '${$}' would overwrite an existing property on FunctionBody`);this[$]=$}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(W,$=!1){return c5(W,$)}index(W,$=!1){return dT(`${W}`,$)}line(W){return this.body+=`${" ".repeat(this.indentation)}${W}
94
+ ${X}}`:`{${J.join(", ")}}`}if(W instanceof Date)return k8(W);if("expression"in W&&typeof W.expression==="string")return W.expression;return G},N4={onCycle:()=>"(cycle)",onSymbol:(W)=>`Symbol(${x6(W)})`,onFunction:(W)=>`Function(${x6(W)})`},v6=(W,$,X)=>{switch(z1(W)){case"object":{let Y=W;if("toJSON"in Y&&typeof Y.toJSON==="function")return Y.toJSON();if(typeof Y==="function")return N4.onFunction(Y);if(X.includes(Y))return"(cycle)";let G=[...X,Y];if(Array.isArray(Y))return Y.map((H)=>v6(H,$,G));if(Y instanceof Date)return Y.toDateString();let J={};for(let H in Y)J[H]=v6(Y[H],$,G);for(let H of Object.getOwnPropertySymbols(Y))J[$.onSymbol?.(H)??H.toString()]=v6(Y[H],$,G);return J}case"symbol":return N4.onSymbol(W);case"bigint":return $.onBigInt?.(W)??`${W}n`;case"undefined":return $.onUndefined??"undefined";case"string":return W.replaceAll("\\","\\\\");default:return W}},k8=(W)=>{let $=W.getFullYear(),X=W.getMonth(),Y=W.getDate(),G=W.getHours(),J=W.getMinutes(),H=W.getSeconds(),Q=W.getMilliseconds();if(X===0&&Y===1&&G===0&&J===0&&H===0&&Q===0)return`${$}`;let z=`${SK[X]} ${Y}, ${$}`;if(G===0&&J===0&&H===0&&Q===0)return z;let T=W.toLocaleTimeString(),F=T.endsWith(" AM")||T.endsWith(" PM")?T.slice(-3):"";if(F)T=T.slice(0,-F.length);if(Q)T+=`.${CK(Q,3)}`;else if(qK.test(T))T=T.slice(0,-3);return`${T+F}, ${z}`},SK=["January","February","March","April","May","June","July","August","September","October","November","December"],qK=/:\d\d:00$/,CK=(W,$)=>String(W).padStart($,"0");var dF=(W,$,...[X])=>{let Y=X?.stringifySymbol??G0,G=W;switch(typeof $){case"string":G=u2($)?W===""?$:`${W}.${$}`:`${W}[${JSON.stringify($)}]`;break;case"number":G=`${W}[${$}]`;break;case"symbol":G=`${W}[${Y($)}]`;break;default:if(X?.stringifyNonKey)G=`${W}[${X.stringifyNonKey($)}]`;else E(`${G0($)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},F2=(W,...$)=>W.reduce((X,Y)=>dF(X,Y,...$),"");class y6 extends uY{cache={};constructor(...W){super();this.push(...W)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let W=0;W<this.length;W++)this.cache.json.push(typeof this[W]==="symbol"?G0(this[W]):this[W]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=F2(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let W="",$=[W];for(let X of this)W=dF(W,X),$.push(W);return this.cache.stringifyAncestors=$}}class c7{chars;i;def;constructor(W){this.def=W,this.chars=[...W],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(W){let $="";while(this.lookahead){if(W(this,$))if($[$.length-1]===P6)$=$.slice(0,-1);else break;$+=this.shift()}return $}shiftUntilLookahead(W){return typeof W==="string"?this.shiftUntil(($)=>$.lookahead===W):this.shiftUntil(($)=>($.lookahead in W))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in p2))}jumpToIndex(W){this.i=W<0?this.length+W:W}jumpForward(W){this.i+=W}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(W,$){return this.chars.slice(W,$).join("")}lookaheadIs(W){return this.lookahead===W}lookaheadIsIn(W){return this.lookahead in W}}var du=SW("implementedTraits");var d7="$ark",kK=2;while(d7 in globalThis)d7=`$ark${kK++}`;var lF=d7;globalThis[lF]=C8;var N=C8,jK=(W)=>`${lF}.${W}`,d0=(W)=>jK(x6(W));class lY extends C6{argNames;body="";constructor(...W){super();this.argNames=W;for(let $ of W){if($ in this)throw new Error(`Arg name '${$}' would overwrite an existing property on FunctionBody`);this[$]=$}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(W,$=!1){return l7(W,$)}index(W,$=!1){return oF(`${W}`,$)}line(W){return this.body+=`${" ".repeat(this.indentation)}${W}
95
95
  `,this}const(W,$){return this.line(`const ${W} = ${$}`),this}let(W,$){return this.line(`let ${W} = ${$}`)}set(W,$){return this.line(`${W} = ${$}`)}if(W,$){return this.block(`if (${W})`,$)}elseIf(W,$){return this.block(`else if (${W})`,$)}else(W){return this.block("else",W)}for(W,$,X=0){return this.block(`for (let i = ${X}; ${W}; i++)`,$)}forIn(W,$){return this.block(`for (const k in ${W})`,$)}block(W,$,X=""){return this.line(`${W} {`),this.indent(),$(this),this.dedent(),this.line(`}${X}`)}return(W=""){return this.line(`return ${W}`)}write(W="anonymous",$=0){return`${W}(${this.argNames.join(", ")}) { ${$?this.body.split(`
96
96
  `).map((X)=>" ".repeat($)+`${X}`).join(`
97
- `):this.body} }`}compile(){return new ST(...this.argNames,this.body)}}var U2=(W)=>m1(W,"object")||typeof W==="symbol"?d0(W):P6(W),c5=(W,$=!1)=>{if(typeof W==="string"&&g2(W))return`${$?"?":""}.${W}`;return dT(kK(W),$)},kK=(W)=>typeof W==="symbol"?d0(W):JSON.stringify(W),dT=(W,$=!1)=>`${$?"?.":""}[${W}]`;class b6 extends lY{traversalKind;optimistic;constructor(W){super("data","ctx");this.traversalKind=W.kind,this.optimistic=W.optimistic===!0}invoke(W,$){let X=$?.arg??this.data,Y=typeof W==="string"?!0:this.requiresContextFor(W),J=typeof W==="string"?W:W.id;if(Y)return`${this.referenceToId(J,$)}(${X}, ${this.ctx})`;return`${this.referenceToId(J,$)}(${X})`}referenceToId(W,$){let X=$?.kind??this.traversalKind,Y=`this.${W}${X}`;return $?.bind?`${Y}.bind(${$?.bind})`:Y}requiresContextFor(W){return this.traversalKind==="Apply"||W.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(W,$,X){let Y=this.requiresContextFor(X);if(Y)this.line(`${this.ctx}.path.push(${W})`);if(this.check(X,{arg:$}),Y)this.line(`${this.ctx}.path.pop()`);return this}check(W,$){return this.traversalKind==="Allows"?this.if(`!${this.invoke(W,$)}`,()=>this.return(!1)):this.line(this.invoke(W,$))}}var oY=(W)=>X0(W,($,X)=>[$,k0(X)?[...X]:X]),f1=ZW("arkKind"),d=(W,$)=>W?.[f1]===$,x0=(W)=>d(W,"root")||d(W,"constraint");var lT=["unit","proto","domain"],R$=["required","optional","index","sequence"],d5=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],iY=[...d5,...R$,"structure","predicate"],N$=["alias","union","morph","unit","intersection","proto","domain"],jK=[...N$,...iY],nY=X0(iY,(W,$)=>[$,1]),oT=X0([...R$,"undeclared"],(W,$)=>[$,1]),iT=X0(jK,(W,$)=>[$,W]),Z$=(W)=>typeof W==="string"&&(W in iT);var S$=(W)=>iT[W],rY=(W)=>N$.slice(S$(W)+1),Tc=[...rY("union"),"alias"],Uc=[...rY("morph"),"alias"],TW=(W)=>{if(typeof W==="string"||typeof W==="boolean"||W===null)return W;if(typeof W==="number"){if(Number.isNaN(W))return"NaN";if(W===Number.POSITIVE_INFINITY)return"Infinity";if(W===Number.NEGATIVE_INFINITY)return"-Infinity";return W}return U2(W)},m2=(W)=>{let $="{ ";for(let[X,Y]of Object.entries(W))$+=`${X}: ${U2(Y)}, `;return $+" }"},J0=(W)=>{let $=W;if($.hasAssociatedError)$.defaults.expected??=(X)=>("description"in X)?X.description:$.defaults.description(X),$.defaults.actual??=(X)=>Y0(X),$.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,$.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let Y=`${X.propString} ${X.problem}`;if(Y[0]==="[")return`value at ${Y}`;return Y};return $};class nT extends Error{name="ToJsonSchemaError";code;context;constructor(W,$){super(Y0($,{quoteKeys:!1,indent:4}));this.code=W,this.context=$}hasCode(W){return this.code===W}}var IK={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(W)=>h0.throw("arrayObject",W),arrayPostfix:(W)=>h0.throw("arrayPostfix",W),defaultValue:(W)=>h0.throw("defaultValue",W),domain:(W)=>h0.throw("domain",W),morph:(W)=>h0.throw("morph",W),patternIntersection:(W)=>h0.throw("patternIntersection",W),predicate:(W)=>h0.throw("predicate",W),proto:(W)=>h0.throw("proto",W),symbolKey:(W)=>h0.throw("symbolKey",W),unit:(W)=>h0.throw("unit",W),date:(W)=>h0.throw("date",W)}},h0={Error:nT,throw:(...W)=>{throw new h0.Error(...W)},throwInternalOperandError:(W,$)=>K0(`Unexpected JSON Schema input for ${W}: ${Y0($)}`),defaultConfig:IK};N.config??={};var y6=(W,$)=>{if(!$)return W;let X={...W},Y;for(Y in $){let J={...W.keywords};if(Y==="keywords"){for(let G in $[Y]){let H=$.keywords[G];if(H===void 0)continue;J[G]=typeof H==="string"?{description:H}:H}X.keywords=J}else if(Y==="toJsonSchema")X[Y]=l5(W.toJsonSchema,$.toJsonSchema);else if(Z$(Y))X[Y]={...W[Y],...$[Y]};else X[Y]=$[Y]}return X},l5=(W,$)=>{if(!W)return $??{};if(!$)return W;let X={...W},Y;for(Y in $)if(Y==="fallback")X.fallback=fK(W.fallback,$.fallback);else X[Y]=$[Y];return X},fK=(W,$)=>{W=rT(W),$=rT($);let X={},Y;for(Y in h0.defaultConfig.fallback)X[Y]=$[Y]??$.default??W[Y]??W.default??h0.defaultConfig.fallback[Y];return X},rT=(W)=>typeof W==="function"?{default:W}:W??{};class p2 extends S6{[f1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:W,relativePath:$,...X},Y){super();this.input=X,this.ctx=Y,ET(this,X);let J=Y.data;if(X.code==="union")X.errors=X.errors.flatMap((H)=>{let Q=H.hasCode("union")?H.errors:[H];if(!W&&!$)return Q;return Q.map((z)=>z.transform((F)=>({...F,path:DT(W,F.path,$)})))});this.nodeConfig=Y.config[this.code];let G=[...X.path??Y.path];if($)G.push(...$);if(W)G.unshift(...W);this.path=new v6(...G),this.data="data"in X?X.data:J}transform(W){return new p2(W({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(W){return this.code===W}get propString(){return T2(this.path)}get expected(){if(this.input.expected)return this.input.expected;let W=this.meta?.expected??this.nodeConfig.expected;return typeof W==="function"?W(this.input):W}get actual(){if(this.input.actual)return this.input.actual;let W=this.meta?.actual??this.nodeConfig.actual;return typeof W==="function"?W(this.data):W}get problem(){if(this.input.problem)return this.input.problem;let W=this.meta?.problem??this.nodeConfig.problem;return typeof W==="function"?W(this):W}get message(){if(this.input.message)return this.input.message;let W=this.meta?.message??this.nodeConfig.message;return typeof W==="function"?W(this):W}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class u1 extends uY{[f1]="errors";ctx;constructor(W){super();this.ctx=W}byPath=Object.create(null);get flatByPath(){return X0(this.byPath,(W,$)=>[W,$.flat])}get flatProblemsByPath(){return X0(this.byPath,(W,$)=>[W,$.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new o5(this)}add(W){if(this.includes(W))return;this._add(W)}transform(W){let $=new u1(this.ctx);for(let X of this)$.add(W(X));return $}merge(W){for(let $ of W){if(this.includes($))continue;this._add(new p2({...$,path:[...this.ctx.path,...$.path]},this.ctx))}}affectsPath(W){if(this.length===0)return!1;return W.stringifyAncestors().some(($)=>($ in this.byPath))||W.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((W)=>W.toJSON())]}toString(){return this.join(`
98
- `)}_add(W){let $=this.byPath[W.propString];if($){if($.hasCode("union")&&$.errors.length===0)return;let X=W.hasCode("union")&&W.errors.length===0?W:new p2({code:"intersection",errors:$.hasCode("intersection")?[...$.errors,W]:[$,W]},this.ctx),Y=this.indexOf($);this.mutable[Y===-1?this.length:Y]=X,this.byPath[W.propString]=X,this.addAncestorPaths(W)}else this.byPath[W.propString]=W,this.addAncestorPaths(W),this.mutable.push(W);this.count++}addAncestorPaths(W){for(let $ of W.path.stringifyAncestors())this.byAncestorPath[$]=D0(this.byAncestorPath[$],W)}}class o5 extends Error{name="TraversalError";constructor(W){if(W.length===1)super(W.summary);else super(`
99
- `+W.map(($)=>` \u2022 ${PK($)}`).join(`
100
- `));Object.defineProperty(this,"arkErrors",{value:W,enumerable:!1})}}var PK=(W)=>W.toString().split(`
97
+ `):this.body} }`}compile(){return new CF(...this.argNames,this.body)}}var _2=(W)=>p1(W,"object")||typeof W==="symbol"?d0(W):b6(W),l7=(W,$=!1)=>{if(typeof W==="string"&&u2(W))return`${$?"?":""}.${W}`;return oF(IK(W),$)},IK=(W)=>typeof W==="symbol"?d0(W):JSON.stringify(W),oF=(W,$=!1)=>`${$?"?.":""}[${W}]`;class h6 extends lY{traversalKind;optimistic;constructor(W){super("data","ctx");this.traversalKind=W.kind,this.optimistic=W.optimistic===!0}invoke(W,$){let X=$?.arg??this.data,Y=typeof W==="string"?!0:this.requiresContextFor(W),G=typeof W==="string"?W:W.id;if(Y)return`${this.referenceToId(G,$)}(${X}, ${this.ctx})`;return`${this.referenceToId(G,$)}(${X})`}referenceToId(W,$){let X=$?.kind??this.traversalKind,Y=`this.${W}${X}`;return $?.bind?`${Y}.bind(${$?.bind})`:Y}requiresContextFor(W){return this.traversalKind==="Apply"||W.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(W,$,X){let Y=this.requiresContextFor(X);if(Y)this.line(`${this.ctx}.path.push(${W})`);if(this.check(X,{arg:$}),Y)this.line(`${this.ctx}.path.pop()`);return this}check(W,$){return this.traversalKind==="Allows"?this.if(`!${this.invoke(W,$)}`,()=>this.return(!1)):this.line(this.invoke(W,$))}}var oY=(W)=>Y0(W,($,X)=>[$,k0(X)?[...X]:X]),f1=SW("arkKind"),d=(W,$)=>W?.[f1]===$,x0=(W)=>d(W,"root")||d(W,"constraint");var iF=["unit","proto","domain"],Z4=["required","optional","index","sequence"],o7=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],iY=[...o7,...Z4,"structure","predicate"],S4=["alias","union","morph","unit","intersection","proto","domain"],PK=[...S4,...iY],nY=Y0(iY,(W,$)=>[$,1]),nF=Y0([...Z4,"undeclared"],(W,$)=>[$,1]),rF=Y0(PK,(W,$)=>[$,W]),q4=(W)=>typeof W==="string"&&(W in rF);var C4=(W)=>rF[W],rY=(W)=>S4.slice(C4(W)+1),qc=[...rY("union"),"alias"],Cc=[...rY("morph"),"alias"],_W=(W)=>{if(typeof W==="string"||typeof W==="boolean"||W===null)return W;if(typeof W==="number"){if(Number.isNaN(W))return"NaN";if(W===Number.POSITIVE_INFINITY)return"Infinity";if(W===Number.NEGATIVE_INFINITY)return"-Infinity";return W}return _2(W)},c2=(W)=>{let $="{ ";for(let[X,Y]of Object.entries(W))$+=`${X}: ${_2(Y)}, `;return $+" }"},J0=(W)=>{let $=W;if($.hasAssociatedError)$.defaults.expected??=(X)=>("description"in X)?X.description:$.defaults.description(X),$.defaults.actual??=(X)=>G0(X),$.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,$.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let Y=`${X.propString} ${X.problem}`;if(Y[0]==="[")return`value at ${Y}`;return Y};return $};class tF extends Error{name="ToJsonSchemaError";code;context;constructor(W,$){super(G0($,{quoteKeys:!1,indent:4}));this.code=W,this.context=$}hasCode(W){return this.code===W}}var fK={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(W)=>h0.throw("arrayObject",W),arrayPostfix:(W)=>h0.throw("arrayPostfix",W),defaultValue:(W)=>h0.throw("defaultValue",W),domain:(W)=>h0.throw("domain",W),morph:(W)=>h0.throw("morph",W),patternIntersection:(W)=>h0.throw("patternIntersection",W),predicate:(W)=>h0.throw("predicate",W),proto:(W)=>h0.throw("proto",W),symbolKey:(W)=>h0.throw("symbolKey",W),unit:(W)=>h0.throw("unit",W),date:(W)=>h0.throw("date",W)}},h0={Error:tF,throw:(...W)=>{throw new h0.Error(...W)},throwInternalOperandError:(W,$)=>K0(`Unexpected JSON Schema input for ${W}: ${G0($)}`),defaultConfig:fK};N.config??={};var g6=(W,$)=>{if(!$)return W;let X={...W},Y;for(Y in $){let G={...W.keywords};if(Y==="keywords"){for(let J in $[Y]){let H=$.keywords[J];if(H===void 0)continue;G[J]=typeof H==="string"?{description:H}:H}X.keywords=G}else if(Y==="toJsonSchema")X[Y]=i7(W.toJsonSchema,$.toJsonSchema);else if(q4(Y))X[Y]={...W[Y],...$[Y]};else X[Y]=$[Y]}return X},i7=(W,$)=>{if(!W)return $??{};if(!$)return W;let X={...W},Y;for(Y in $)if(Y==="fallback")X.fallback=xK(W.fallback,$.fallback);else X[Y]=$[Y];return X},xK=(W,$)=>{W=aF(W),$=aF($);let X={},Y;for(Y in h0.defaultConfig.fallback)X[Y]=$[Y]??$.default??W[Y]??W.default??h0.defaultConfig.fallback[Y];return X},aF=(W)=>typeof W==="function"?{default:W}:W??{};class d2 extends C6{[f1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:W,relativePath:$,...X},Y){super();this.input=X,this.ctx=Y,BF(this,X);let G=Y.data;if(X.code==="union")X.errors=X.errors.flatMap((H)=>{let Q=H.hasCode("union")?H.errors:[H];if(!W&&!$)return Q;return Q.map((z)=>z.transform((T)=>({...T,path:MF(W,T.path,$)})))});this.nodeConfig=Y.config[this.code];let J=[...X.path??Y.path];if($)J.push(...$);if(W)J.unshift(...W);this.path=new y6(...J),this.data="data"in X?X.data:G}transform(W){return new d2(W({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(W){return this.code===W}get propString(){return F2(this.path)}get expected(){if(this.input.expected)return this.input.expected;let W=this.meta?.expected??this.nodeConfig.expected;return typeof W==="function"?W(this.input):W}get actual(){if(this.input.actual)return this.input.actual;let W=this.meta?.actual??this.nodeConfig.actual;return typeof W==="function"?W(this.data):W}get problem(){if(this.input.problem)return this.input.problem;let W=this.meta?.problem??this.nodeConfig.problem;return typeof W==="function"?W(this):W}get message(){if(this.input.message)return this.input.message;let W=this.meta?.message??this.nodeConfig.message;return typeof W==="function"?W(this):W}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class c1 extends uY{[f1]="errors";ctx;constructor(W){super();this.ctx=W}byPath=Object.create(null);get flatByPath(){return Y0(this.byPath,(W,$)=>[W,$.flat])}get flatProblemsByPath(){return Y0(this.byPath,(W,$)=>[W,$.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new n7(this)}add(W){if(this.includes(W))return;this._add(W)}transform(W){let $=new c1(this.ctx);for(let X of this)$.add(W(X));return $}merge(W){for(let $ of W){if(this.includes($))continue;this._add(new d2({...$,path:[...this.ctx.path,...$.path]},this.ctx))}}affectsPath(W){if(this.length===0)return!1;return W.stringifyAncestors().some(($)=>($ in this.byPath))||W.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((W)=>W.toJSON())]}toString(){return this.join(`
98
+ `)}_add(W){let $=this.byPath[W.propString];if($){if($.hasCode("union")&&$.errors.length===0)return;let X=W.hasCode("union")&&W.errors.length===0?W:new d2({code:"intersection",errors:$.hasCode("intersection")?[...$.errors,W]:[$,W]},this.ctx),Y=this.indexOf($);this.mutable[Y===-1?this.length:Y]=X,this.byPath[W.propString]=X,this.addAncestorPaths(W)}else this.byPath[W.propString]=W,this.addAncestorPaths(W),this.mutable.push(W);this.count++}addAncestorPaths(W){for(let $ of W.path.stringifyAncestors())this.byAncestorPath[$]=D0(this.byAncestorPath[$],W)}}class n7 extends Error{name="TraversalError";constructor(W){if(W.length===1)super(W.summary);else super(`
99
+ `+W.map(($)=>` \u2022 ${bK($)}`).join(`
100
+ `));Object.defineProperty(this,"arkErrors",{value:W,enumerable:!1})}}var bK=(W)=>W.toString().split(`
101
101
  `).join(`
102
- `);class qW{path=[];errors=new u1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(W,$){this.root=W,this.config=$}get data(){let W=this.root;for(let $ of this.path)W=W?.[$];return W}get propString(){return T2(this.path)}reject(W){return this.error(W),!1}mustBe(W){return this.error(W),!1}error(W){let $=typeof W==="object"?W.code?W:{...W,code:"predicate"}:{code:"predicate",expected:W};return this.errorFromContext($)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(W){let $={path:new v6(...this.path),morphs:W};if(this.currentBranch)this.currentBranch.queuedMorphs.push($);else this.queuedMorphs.push($)}finalize(W){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return W?W(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(W){return this.errorFromContext(W)}errorFromContext(W){let $=new p2(W,this);if(this.currentBranch)this.currentBranch.error=$;else this.errors.add($);return $}applyQueuedMorphs(){while(this.queuedMorphs.length){let W=this.queuedMorphs;this.queuedMorphs=[];for(let{path:$,morphs:X}of W){if(this.errors.affectsPath($))continue;this.applyMorphsAtPath($,X)}}}applyMorphsAtPath(W,$){let X=W.at(-1),Y;if(X!==void 0){Y=this.root;for(let J=0;J<W.length-1;J++)Y=Y[W[J]]}this.path=[...W];for(let J of $){let G=x0(J),H=J(Y===void 0?this.root:Y[X],this);if(H instanceof p2){this.errors.add(H);break}if(H instanceof u1){if(!G)this.errors.merge(H);break}if(Y===void 0)this.root=H;else Y[X]=H;this.applyQueuedMorphs()}}}var c1=(W,$,X)=>{if(!X)return $();X.path.push(W);let Y=$();return X.path.pop(),Y};class g6 extends SW{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(W,$){super((Y,J,G=this.onFail)=>{if(J)return this.traverseApply(Y,J),J.hasError()?J.errors:J.data;return this.rootApply(Y,G)},{attach:W});this.attachments=W,this.$=$,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((Y,J)=>yK(Y,J.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let Y=0;Y<this.children.length;Y++){if(this.includesTransform||=this.children[Y].includesTransform,this.includesContextualPredicate||=this.children[Y].includesContextualPredicate,this.isCyclic||=this.children[Y].isCyclic,!X){let J=this.children[Y].flatRefs;for(let G=0;G<J.length;G++){let H=J[G];if(!this.flatRefs.some((Q)=>aT(Q,H))){this.flatRefs.push(H);for(let Q of H.node.branches)if(Q.hasKind("morph")||Q.hasKind("intersection")&&Q.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:H.path,propString:H.propString,node:Q})}}}Object.assign(this.referencesById,this.children[Y].referencesById)}this.flatRefs.sort((Y,J)=>Y.path.length>J.path.length?1:Y.path.length<J.path.length?-1:Y.propString>J.propString?1:Y.propString<J.propString?-1:Y.node.expression<J.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((Y)=>Y.length===1||Y.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((Y)=>Y.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(Y)=>this.traverseAllows(Y,new qW(Y,this.$.resolvedConfig)):(Y)=>this.traverseAllows(Y)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return($,X)=>{if(this.allows($))return $;let Y=new qW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"contextual":return($,X)=>{let Y=new qW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let W=this.$.resolvedConfig.clone;return($,X)=>{if(this.allows($))return this.contextFreeMorph(W&&(typeof $==="object"&&$!==null||typeof $==="function")?W($):$);let Y=new qW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,K0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=bK(this.metaJson);cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=S$(this.kind);precompilation;assert=(W,$)=>this(W,$,(X)=>X.throw());traverse(W,$){return this(W,$,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(W){if(!this.includesTransform)return this;let $={};for(let[X,Y]of this.innerEntries){let J=this.impl.keys[X];if(J.reduceIo)J.reduceIo(W,$,Y);else if(J.child){let G=Y;$[X]=k0(G)?G.map((H)=>H[W]):G[W]}else $[X]=Y}return this.$.node(this.kind,$)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(W){let $=x0(W)?W:this.$.parseDefinition(W);return this.innerHash===$.innerHash}ifEquals(W){return this.equals(W)?this:void 0}hasKind(W){return this.kind===W}assertHasKind(W){if(this.kind!==W)B8(`${this.kind} node was not of asserted kind ${W}`);return this}hasKindIn(...W){return W.includes(this.kind)}assertHasKindIn(...W){if(!H2(W,this.kind))B8(`${this.kind} node was not one of asserted kinds ${W}`);return this}isBasis(){return H2(lT,this.kind)}isConstraint(){return H2(iY,this.kind)}isStructural(){return H2(R$,this.kind)}isRefinement(){return H2(d5,this.kind)}isRoot(){return H2(N$,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(W){return this.hasKind("unit")&&this.allows(W)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(W){let $=h6.normalize(W);return this._select($)}_select(W){let $=h6.applyBoundary[W.boundary??"references"](this);if(W.kind)$=$.filter((X)=>X.kind===W.kind);if(W.where)$=$.filter(W.where);return h6.applyMethod[W.method??"filter"]($,this,W)}transform(W,$){return this._transform(W,this._createTransformContext($))}_createTransformContext(W){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:W?.prereduced??!1},undeclaredKeyHandling:void 0,...W}}_transform(W,$){let X=$.bindScope??this.$;if($.seen[this.id])return this.$.lazilyResolve($.seen[this.id]);if($.shouldTransform?.(this,$)===!1)return this;let Y;if($.seen[this.id]=()=>Y,this.hasKind("structure")&&this.undeclared!==$.undeclaredKeyHandling)$={...$,undeclaredKeyHandling:this.undeclared};let J=X0(this.inner,(F,T)=>{if(!this.impl.keys[F].child)return[F,T];let U=T;if(!k0(U)){let V=U._transform(W,$);return V?[F,V]:[]}if(U.length===0)return[F,T];let _=U.flatMap((V)=>{return V._transform(W,$)??[]});return _.length?[F,_]:[]});delete $.seen[this.id];let G=Object.assign(J,{meta:this.meta}),H=$.selected&&!$.selected.includes(this)?G:W(this.kind,G,$);if(H===null)return null;if(x0(H))return Y=H;let Q=Object.keys(H);if((Q.length===0||Q.length===1&&Q[0]==="meta")&&!cW(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in H))return $.undeclaredKeyHandling?{...H,value:N.intrinsic.unknown}:null;if(this.kind==="morph")H.in??=N.intrinsic.unknown;return Y=X.node(this.kind,H,$.parseOptions)}configureReferences(W,$="references"){let X=h6.normalize($),Y=typeof W==="string"?(Q,z)=>({...z,meta:{...z.meta,description:W}}):typeof W==="function"?(Q,z)=>({...z,meta:W(z.meta)}):(Q,z)=>({...z,meta:{...z.meta,...W}});if(X.boundary==="self")return this.$.node(this.kind,Y(this.kind,{...this.inner,meta:this.meta}));let J=this._select(X),G=J&&b2(J),H=X.boundary==="child"?(Q,z)=>z.root.children.includes(Q):X.boundary==="shallow"?(Q)=>Q.kind!=="structure":()=>!0;return this.$.finalize(this.transform(Y,{shouldTransform:H,selected:G}))}}var h6={applyBoundary:{self:(W)=>[W],child:(W)=>[...W.children],shallow:(W)=>[...W.shallowReferences],references:(W)=>[...W.references]},applyMethod:{filter:(W)=>W,assertFilter:(W,$,X)=>{if(W.length===0)B8(tT($,X));return W},find:(W)=>W[0],assertFind:(W,$,X)=>{if(W.length===0)B8(tT($,X));return W[0]}},normalize:(W)=>typeof W==="function"?{boundary:"references",method:"filter",where:W}:typeof W==="string"?F1(W,h6.applyBoundary)?{method:"filter",boundary:W}:{boundary:"references",method:"filter",kind:W}:{boundary:"references",method:"filter",...W}},tT=(W,$)=>`${W} had no references matching ${Y0($)}.`,xK=(W)=>T2(W,{stringifyNonKey:($)=>$.expression}),vK=/"(\$ark\.[^"]+)"/g,bK=(W)=>JSON.stringify(W).replaceAll(vK,"$1"),CW=(W,$)=>({path:W,node:$,propString:xK(W)}),aT=(W,$)=>W.propString===$.propString&&W.node.equals($.node),i5=(W,$)=>uW(W,$,{isEqual:aT}),yK=(W,$)=>uW(W,$,{isEqual:(X,Y)=>X.equals(Y)});class P extends Array{static init(W,$,X,Y){return new P({kind:W,l:$,r:X,path:Y?.path??[],optional:Y?.optional??!1})}add(W,$,X,Y){return this.push({kind:W,l:$,r:X,path:Y?.path??[],optional:Y?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:W,l:$,r:X}=this[0],Y=T2(W);return r5(`Intersection${Y&&` at ${Y}`} of ${sT($,X)}`)}return`The following intersections result in unsatisfiable types:
103
- \u2022 ${this.map(({path:W,l:$,r:X})=>`${W}: ${sT($,X)}`).join(`
104
- \u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let W=this.map(($)=>({...$,l:$.r,r:$.l}));if(!(W instanceof P))return new P(...W);return W}withPrefixKey(W,$){return this.map((X)=>({...X,path:[W,...X.path],optional:X.optional||$==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var sT=(W,$)=>`${n5(W)} and ${n5($)}`,n5=(W)=>x0(W)?W.expression:k0(W)?W.map(n5).join(" | ")||"never":String(W),r5=(W)=>`${W} results in an unsatisfiable type`;var q$={},d1=(W,$,X)=>v0(W,$,{$:X,invert:!1,pipe:!1}),m6=(W,$,X)=>v0(W,$,{$:X,invert:!1,pipe:!0}),v0=(W,$,X)=>{let Y=X.pipe?"|>":"&",J=`${W.hash}${Y}${$.hash}`;if(q$[J]!==void 0)return q$[J];if(!X.pipe){let Q=`${$.hash}${Y}${W.hash}`;if(q$[Q]!==void 0){let z=q$[Q],F=z instanceof P?z.invert():z;return q$[J]=F,F}}let G=!X.pipe||!W.includesTransform&&!$.includesTransform;if(G&&W.equals($))return W;let H=G?t5(W,$,X):W.hasKindIn(...N$)?hK(W,$,X):t5(W,$,X);if(x0(H)){if(W.equals(H))H=W;else if($.equals(H))H=$}return q$[J]=H,H},t5=(W,$,X)=>{let Y=W.precedence<$.precedence?W.kind:$.kind,J=W.impl.intersections[$.kind]??$.impl.intersections[W.kind];if(J===void 0)return null;else if(Y===W.kind)return J(W,$,X);else{let G=J($,W,{...X,invert:!X.invert});if(G instanceof P)G=G.invert();return G}},hK=(W,$,X)=>W.includesTransform||$.includesTransform?X.invert?eT($,W,X):eT(W,$,X):t5(W,$,X),eT=(W,$,X)=>W.distribute((Y)=>gK(Y,$,X),(Y)=>{let J=Y.filter(x0);if(J.length===0)return P.init("union",W.branches,$.branches);if(J.length<W.branches.length||!W.branches.every((Q,z)=>Q.in.equals(J[z].in)))return X.$.parseSchema(J);let G;if(J.length===1){let Q=J[0];if(!G)return Q;return X.$.node("morph",{...Q.inner,in:Q.in.configure(G,"self")})}let H={branches:J};if(G)H.meta=G;return X.$.parseSchema(H)}),gK=(W,$,X)=>{if(W.hasKind("morph")){let J=[...W.morphs];if(W.lastMorphIfNode){let G=v0(W.lastMorphIfNode,$,X);if(G instanceof P)return G;J[J.length-1]=G}else J.push($);return X.$.node("morph",{morphs:J,in:W.inner.in})}if($.hasKind("morph")){let J=v0(W,$.in,X);if(J instanceof P)return J;return X.$.node("morph",{morphs:[$],in:J})}return X.$.node("morph",{morphs:[$],in:W})};class UW extends g6{constructor(W,$){super(W,$);Object.defineProperty(this,f1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(W){return d1(this,W,this.$)}}class w2 extends UW{traverseApply=(W,$)=>{if(!this.traverseAllows(W,$))$.errorFromNodeContext(this.errorContext)};compile(W){if(W.traversalKind==="Allows")W.return(this.compiledCondition);else W.if(this.compiledNegation,()=>W.line(`${W.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return m2(this.errorContext)}}var N1=(W)=>($,X)=>{if(k0($)){if($.length===0)return;let J=$.map((G)=>X.$.node(W,G));if(W==="predicate")return J;return J.sort((G,H)=>G.hash<H.hash?-1:1)}let Y=X.$.node(W,$);return Y.hasOpenIntersection()?[Y]:Y},C$=(W)=>{let $=W.r.shift();if(!$){let Y=W.l.length===0&&W.kind==="structure"?N.intrinsic.unknown.internal:W.ctx.$.node(W.kind,Object.assign(W.baseInner,mK(W.l)),{prereduced:!0});for(let J of W.roots){if(Y instanceof P)return Y;Y=v0(J,Y,W.ctx)}return Y}let X=!1;for(let Y=0;Y<W.l.length;Y++){let J=v0(W.l[Y],$,W.ctx);if(J===null)continue;if(J instanceof P)return J;if(!X){if(J.isRoot())return W.roots.push(J),W.l.splice(Y),C$(W);W.l[Y]=J,X=!0}else if(!W.l.includes(J))return K0(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!X)W.l.push($);if(W.kind==="intersection"){if($.impliedSiblings)for(let Y of $.impliedSiblings)uW(W.r,Y)}return C$(W)},k$=(W)=>{return Object.entries(W).flatMap(([X,Y])=>(X in nY)?Y:[]).sort((X,Y)=>X.precedence<Y.precedence?-1:X.precedence>Y.precedence?1:X.kind==="predicate"&&Y.kind==="predicate"?0:X.hash<Y.hash?-1:1)},mK=(W)=>{let $={};for(let X of W)if(X.hasOpenIntersection())$[X.kind]=D0($[X.kind],X);else{if($[X.kind])return K0(`Unexpected intersection of closed refinements of kind ${X.kind}`);$[X.kind]=X}return $},WU=(...W)=>A($U(...W)),$U=(W,$,X)=>{let Y=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude($).defaultShortDescription;return`${jT(W)} operand must be ${$.description} (was ${Y})`};var XU=(W,$,X)=>new u2(W,$,X,X,null);class tY extends SW{}class u2 extends SW{[f1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(W,$,X,Y,J){super((...G)=>{let H=X0(this.names,(Q,z)=>{let F=this.arg$.parse(G[Q]);if(!F.extends(this.constraints[Q]))A(pK(z,this.constraints[Q].expression,F.expression));return[z,F]});if(this.defIsLazy()){let Q=this.bodyDef(H);return this.$.parse(Q)}return this.$.parse($,{args:H})});this.paramDefs=W,this.bodyDef=$,this.$=X,this.arg$=Y,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof tY}cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get json(){return this.cacheGetter("json",{params:this.params.map((W)=>W[1].isUnknown()?W[0]:[W[0],W[1].json]),body:pT(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((W)=>typeof W==="string"?[W,N.intrinsic.unknown]:[W[0],this.$.parse(W[1])]))}get names(){return this.cacheGetter("names",this.params.map((W)=>W[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((W)=>W[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var pK=(W,$,X)=>`${W} must be assignable to ${$} (was ${X})`;var uK=J0({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(W)=>typeof W==="function"?{predicate:W}:W,defaults:{description:(W)=>`valid according to ${W.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class YU extends UW{serializedPredicate=d0(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=m2(this.errorContext);traverseApply=(W,$)=>{if(!this.predicate(W,$.external)&&!$.hasError())$.errorFromNodeContext(this.errorContext)};compile(W){if(W.traversalKind==="Allows"){W.return(this.compiledCondition);return}W.if(`${this.compiledNegation} && !ctx.hasError()`,()=>W.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(W,$){return $.fallback.predicate({code:"predicate",base:W,predicate:this.predicate})}}var a5={implementation:uK,Node:YU};var cK=J0({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(W)=>Number.isInteger(W)?W:A(dK(W))}},normalize:(W)=>typeof W==="number"?{rule:W}:W,hasAssociatedError:!0,defaults:{description:(W)=>W.rule===1?"an integer":W.rule===2?"even":`a multiple of ${W.rule}`},intersections:{divisor:(W,$,X)=>X.$.node("divisor",{rule:Math.abs(W.rule*$.rule/lK(W.rule,$.rule))})},obviatesBasisDescription:!0});class JU extends w2{traverseAllows=(W)=>W%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(W){if(W.type="integer",this.rule===1)return W;return W.multipleOf=this.rule,W}}var s5={implementation:cK,Node:JU};var dK=(W)=>`divisor must be an integer (was ${W})`,lK=(W,$)=>{let X,Y=W,J=$;while(J!==0)X=J,J=Y%J,Y=X;return Y};class $W extends w2{boundOperandKind=rK[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=tK(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${oK[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?aK(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(W){return(this.limitKind==="upper"?this.numericLimit<W.numericLimit:this.numericLimit>W.numericLimit)||this.numericLimit===W.numericLimit&&this.exclusive===!0&&!W.exclusive}overlapsRange(W){if(this.isStricterThan(W))return!1;if(this.numericLimit===W.numericLimit&&(this.exclusive||W.exclusive))return!1;return!0}overlapIsUnit(W){return this.numericLimit===W.numericLimit&&!this.exclusive&&!W.exclusive}}var oK={"<":">=","<=":">",">":"<=",">=":"<"},iK={min:"max",minLength:"maxLength",after:"before"},aY={parse:(W)=>W||void 0},sY=(W)=>($)=>{if(typeof $==="number")return{rule:$};let{exclusive:X,...Y}=$;return X?{...Y,rule:W==="minLength"?Y.rule+1:Y.rule-1}:Y},eY=(W)=>($)=>{if(typeof $==="number"||typeof $==="string"||$ instanceof Date)return{rule:$};let{exclusive:X,...Y}=$;if(!X)return Y;let J=typeof Y.rule==="number"?Y.rule:typeof Y.rule==="string"?new Date(Y.rule).valueOf():Y.rule.valueOf();return X?{...Y,rule:W==="after"?J+1:J-1}:Y},W9=(W)=>typeof W==="string"||typeof W==="number"?new Date(W):W,nK=(W,$)=>`${W} bound must be a positive integer (was ${$})`,j$=(W)=>($)=>{if(!Number.isInteger($)||$<0)A(nK(W,$));return $},rK={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},tK=(W,$)=>`${F1(W,iK)?">":"<"}${$?"":"="}`,aK=(W)=>typeof W==="string"?W:new Date(W).toLocaleString(),GU=(W)=>`Bounded expression ${W} must be exactly one of number, string, Array, or Date`;var sK=J0({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:W9,serialize:(W)=>W.toISOString()}},normalize:eY("after"),defaults:{description:(W)=>`${W.collapsibleLimitString} or later`,actual:S8},intersections:{after:(W,$)=>W.isStricterThan($)?W:$}});class HU extends $W{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=S8(this.rule);traverseAllows=(W)=>W>=this.rule;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,after:this.rule})}}var e5={implementation:sK,Node:HU};var eK=J0({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:W9,serialize:(W)=>W.toISOString()}},normalize:eY("before"),defaults:{description:(W)=>`${W.collapsibleLimitString} or earlier`,actual:S8},intersections:{before:(W,$)=>W.isStricterThan($)?W:$,after:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("unit",{unit:W.rule}):null:P.init("range",W,$)}});class QU extends $W{collapsibleLimitString=S8(this.rule);traverseAllows=(W)=>W<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,before:this.rule})}}var W7={implementation:eK,Node:QU};var WA=J0({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:j$("exactLength")}},normalize:(W)=>typeof W==="number"?{rule:W}:W,hasAssociatedError:!0,defaults:{description:(W)=>`exactly length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{exactLength:(W,$,X)=>P.init("unit",X.$.node("unit",{unit:W.rule}),X.$.node("unit",{unit:$.rule}),{path:["length"]}),minLength:(W,$)=>W.rule>=$.rule?W:P.init("range",W,$),maxLength:(W,$)=>W.rule<=$.rule?W:P.init("range",W,$)}});class zU extends w2{traverseAllows=(W)=>W.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(W){switch(W.type){case"string":return W.minLength=this.rule,W.maxLength=this.rule,W;case"array":return W.minItems=this.rule,W.maxItems=this.rule,W;default:return h0.throwInternalOperandError("exactLength",W)}}}var $7={implementation:WA,Node:zU};var $A=J0({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:aY},normalize:(W)=>typeof W==="number"?{rule:W}:W,defaults:{description:(W)=>{if(W.rule===0)return W.exclusive?"negative":"non-positive";return`${W.exclusive?"less than":"at most"} ${W.rule}`}},intersections:{max:(W,$)=>W.isStricterThan($)?W:$,min:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("unit",{unit:W.rule}):null:P.init("range",W,$)},obviatesBasisDescription:!0});class FU extends $W{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(W)=>W<this.rule:(W)=>W<=this.rule;reduceJsonSchema(W){if(this.exclusive)W.exclusiveMaximum=this.rule;else W.maximum=this.rule;return W}}var X7={implementation:$A,Node:FU};var XA=J0({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:j$("maxLength")}},reduce:(W,$)=>W.rule===0?$.node("exactLength",W):void 0,normalize:sY("maxLength"),defaults:{description:(W)=>`at most length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{maxLength:(W,$)=>W.isStricterThan($)?W:$,minLength:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("exactLength",{rule:W.rule}):null:P.init("range",W,$)}});class TU extends $W{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(W)=>W.length<=this.rule;reduceJsonSchema(W){switch(W.type){case"string":return W.maxLength=this.rule,W;case"array":return W.maxItems=this.rule,W;default:return h0.throwInternalOperandError("maxLength",W)}}}var Y7={implementation:XA,Node:TU};var YA=J0({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:aY},normalize:(W)=>typeof W==="number"?{rule:W}:W,defaults:{description:(W)=>{if(W.rule===0)return W.exclusive?"positive":"non-negative";return`${W.exclusive?"more than":"at least"} ${W.rule}`}},intersections:{min:(W,$)=>W.isStricterThan($)?W:$},obviatesBasisDescription:!0});class UU extends $W{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(W)=>W>this.rule:(W)=>W>=this.rule;reduceJsonSchema(W){if(this.exclusive)W.exclusiveMinimum=this.rule;else W.minimum=this.rule;return W}}var J7={implementation:YA,Node:UU};var JA=J0({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:j$("minLength")}},reduce:(W)=>W.rule===0?N.intrinsic.unknown:void 0,normalize:sY("minLength"),defaults:{description:(W)=>W.rule===1?"non-empty":`at least length ${W.rule}`,actual:(W)=>W.length===0?"":`${W.length}`},intersections:{minLength:(W,$)=>W.isStricterThan($)?W:$}});class wU extends $W{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(W)=>W.length>=this.rule;reduceJsonSchema(W){switch(W.type){case"string":return W.minLength=this.rule,W;case"array":return W.minItems=this.rule,W;default:return h0.throwInternalOperandError("minLength",W)}}}var G7={implementation:JA,Node:wU};var _U={min:J7.implementation,max:X7.implementation,minLength:G7.implementation,maxLength:Y7.implementation,exactLength:$7.implementation,after:e5.implementation,before:W7.implementation},DU={min:J7.Node,max:X7.Node,minLength:G7.Node,maxLength:Y7.Node,exactLength:$7.Node,after:e5.Node,before:W7.Node};var GA=J0({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(W)=>typeof W==="string"?{rule:W}:W instanceof RegExp?W.flags?{rule:W.source,flags:W.flags}:{rule:W.source}:W,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(W)=>`matched by ${W.rule}`},intersections:{pattern:()=>null}});class MU extends w2{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=N.intrinsic.string.internal;reduceJsonSchema(W,$){if(W.pattern)return $.fallback.patternIntersection({code:"patternIntersection",base:W,pattern:this.rule});return W.pattern=this.rule,W}}var H7={implementation:GA,Node:MU};var p6=(W,$)=>{let X=HA(W);if($&&!$.includes(X))return A(`Root of kind ${X} should be one of ${$}`);return X},HA=(W)=>{if(d(W,"root"))return W.kind;if(typeof W==="string")return W[0]==="$"?"alias":(W in p1)?"domain":"proto";if(typeof W==="function")return"proto";if(typeof W!=="object"||W===null)return A(VU(W));if("morphs"in W)return"morph";if("branches"in W||k0(W))return"union";if("unit"in W)return"unit";if("reference"in W)return"alias";let $=Object.keys(W);if($.length===0||$.some((X)=>(X in nY)))return"intersection";if("proto"in W)return"proto";if("domain"in W)return"domain";return A(VU(W))},VU=(W)=>`${Y0(W)} is not a valid type schema`,OU={},QA=(W)=>k0(W)?W.map(($)=>$.collapsibleJson):W.collapsibleJson,P1={};N.nodesByRegisteredId=P1;var Q7=(W)=>{return OU[W]??=0,`${W}${++OU[W]}`},z7=(W)=>{let $=I$[W.kind],X=$.applyConfig?.(W.def,W.$.resolvedConfig)??W.def,Y={},{meta:J,...G}=X,H=J===void 0?{}:typeof J==="string"?{description:J}:J,Q=I5(G).sort(([F],[T])=>Z$(F)?Z$(T)?S$(F)-S$(T):1:Z$(T)?-1:F<T?-1:1).filter(([F,T])=>{if(F.startsWith("meta.")){let U=F.slice(5);return H[U]=T,!1}return!0});for(let F of Q){let T=F[0],U=$.keys[T];if(!U)return A(`Key ${T} is not valid on ${W.kind} schema`);let _=U.parse?U.parse(F[1],W):F[1];if(_!==WW&&(_!==void 0||U.preserveUndefined))Y[T]=_}if($.reduce&&!W.prereduced){let F=$.reduce(Y,W.$);if(F){if(F instanceof P)return F.throw();return zA(F,H)}}return F7({id:W.id,kind:W.kind,inner:Y,meta:H,$:W.$})},F7=({id:W,kind:$,inner:X,meta:Y,$:J,ignoreCache:G})=>{let H=I$[$],Q=I5(X),z=[],F={};for(let[C,R]of Q){let q=H.keys[C],m=q.serialize??(q.child?QA:TW);if(F[C]=m(R),q.child===!0){let c=R;if(k0(c))z.push(...c);else z.push(c)}else if(typeof q.child==="function")z.push(...q.child(R))}if(H.finalizeInnerJson)F=H.finalizeInnerJson(F);let T={...F},U={};if(!cW(Y))U=X0(Y,(C,R)=>[C,C==="examples"?R:TW(R)]),T.meta=$9(U,"description",!0);F=$9(F,H.collapsibleKey,!1);let _=JSON.stringify({kind:$,...F});T=$9(T,H.collapsibleKey,!1);let V=$9(T,H.collapsibleKey,!0),K=JSON.stringify({kind:$,...T});if(J.nodesByHash[K]&&!G)return J.nodesByHash[K];let B={id:W,kind:$,impl:H,inner:X,innerEntries:Q,innerJson:F,innerHash:_,meta:Y,metaJson:U,json:T,hash:K,collapsibleJson:V,children:z};if($!=="intersection"){for(let C in X)if(C!=="in"&&C!=="out")B[C]=X[C]}let I=new AU[$](B,J);return J.nodesByHash[K]=I},KU=(W,$)=>{if(W.id===$)return W;if(x0(P1[$]))K0(`Unexpected attempt to overwrite node id ${$}`);return F7({id:$,kind:W.kind,inner:W.inner,meta:W.meta,$:W.$,ignoreCache:!0})},zA=(W,$,X)=>{if(X&&x0(P1[X]))K0(`Unexpected attempt to overwrite node id ${X}`);return F7({id:X??Q7($.alias??W.kind),kind:W.kind,inner:W.inner,meta:$,$:W.$})},$9=(W,$,X)=>{let Y=Object.keys(W);if(Y.length===1&&Y[0]===$){let J=W[$];if(X)return J;if(m1(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return W};var u6=(W,$,X)=>{if(W.key!==$.key)return null;let Y=W.key,J=v0(W.value,$.value,X),G=W.required||$.required?"required":"optional";if(J instanceof P)if(G==="optional")J=N.intrinsic.never.internal;else return J.withPrefixKey(W.key,W.required&&$.required?"required":"optional");if(G==="required")return X.$.node("required",{key:Y,value:J});let H=W.hasDefault()?$.hasDefault()?W.default===$.default?W.default:A(T7(W.default,$.default)):W.default:$.hasDefault()?$.default:WW;return X.$.node("optional",{key:Y,value:J,default:H})};class c6 extends UW{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=U2(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=D0(this.value.flatRefs.map((W)=>CW([this.key,...W.path],W.node)),CW([this.key],this.value));_transform(W,$){$.path.push(this.key);let X=super._transform(W,$);return $.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(W,$)=>{if(this.key in W)return c1(this.key,()=>this.value.traverseAllows(W[this.key],$),$);return this.optional};traverseApply=(W,$)=>{if(this.key in W)c1(this.key,()=>this.value.traverseApply(W[this.key],$),$);else if(this.hasKind("required"))$.errorFromNodeContext(this.errorContext)};compile(W){if(W.if(`${this.serializedKey} in data`,()=>W.traverseKey(this.serializedKey,`data${W.prop(this.key)}`,this.value)),this.hasKind("required"))W.else(()=>W.traversalKind==="Apply"?W.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):W.return(!1));if(W.traversalKind==="Allows")W.return(!0)}}var T7=(W,$)=>`Invalid intersection of default values ${Y0(W)} & ${Y0($)}`;var FA=J0({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)},default:{preserveUndefined:!0}},normalize:(W)=>W,reduce:(W,$)=>{if($.resolvedConfig.exactOptionalPropertyTypes===!1){if(!W.value.allows(void 0))return $.node("optional",{...W,value:W.value.or(r.undefined)},{prereduced:!0})}},defaults:{description:(W)=>`${W.compiledKey}?: ${W.value.description}`},intersections:{optional:u6}});class EU extends c6{constructor(...W){super(...W);if("default"in this.inner)l6(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:W,...$}=this.inner;return this.cacheGetter("outProp",this.$.node("required",$,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${Y0(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=UA(this);defaultValueMorphRef=this.defaultValueMorph&&d0(this.defaultValueMorph)}var d6={implementation:FA,Node:EU},TA={},UA=(W)=>{if(!W.hasDefault())return;let $=`{${W.compiledKey}: ${W.value.id} = ${TW(W.default)}}`;return TA[$]??=U7(W.key,W.value,W.default)},U7=(W,$,X)=>{if(typeof X==="function")return $.includesTransform?(J,G)=>{return c1(W,()=>$(J[W]=X(),G),G),J}:(J)=>{return J[W]=X(),J};let Y=$.includesTransform?$.assert(X):X;return m1(Y,"object")?(J,G)=>{return c1(W,()=>$(J[W]=X,G),G),J}:(J)=>{return J[W]=Y,J}},l6=(W,$,X)=>{let Y=y2($);if(m1($,"object")&&!Y)A(wA(X));let J=W.in(Y?$():$);if(J instanceof u1){if(X===null)A(`Default ${J.summary}`);let G=J.transform((H)=>H.transform((Q)=>({...Q,prefixPath:[X]})));A(`Default for ${G.summary}`)}return $},wA=(W)=>{return`Non-primitive default ${W===null?"":typeof W==="number"?`for value at [${W}] `:`for ${U2(W)} `}must be specified as a function like () => ({my: 'object'})`};class wW extends g6{constructor(W,$){super(W,$);Object.defineProperty(this,f1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(W)=>{let $=this(W);if($ instanceof u1)return $;return{value:$}}}}as(){return this}brand(W){if(W==="")return A(_A);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(W,$){let X=this.branches.map(W);return $?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(W={}){let $=l5(this.$.resolvedConfig.toJsonSchema,W);$.useRefs||=this.isCyclic;let X=typeof $.dialect==="string"?{$schema:$.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse($)),$.useRefs)X.$defs=X0(this.references,(Y,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema($)]:[]);return X}toJsonSchemaRecurse(W){if(W.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(W)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(W){let $=this.innerToJsonSchema(W);return Object.assign($,this.metaJson)}intersect(W){let $=this.$.parseDefinition(W),X=this.rawIntersect($);if(X instanceof P)return X;return this.$.finalize(X)}rawIntersect(W){return d1(this,W,this.$)}toNeverIfDisjoint(){return this}and(W){let $=this.intersect(W);return $ instanceof P?$.throw():$}rawAnd(W){let $=this.rawIntersect(W);return $ instanceof P?$.throw():$}or(W){let $=this.$.parseDefinition(W);return this.$.finalize(this.rawOr($))}rawOr(W){let $=[...this.branches,...W.branches];return this.$.node("union",$)}map(W){return this.$.schema(this.applyStructuralOperation("map",[W]))}pick(...W){return this.$.schema(this.applyStructuralOperation("pick",W))}omit(...W){return this.$.schema(this.applyStructuralOperation("omit",W))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let W=this.applyStructuralOperation("keyof",[]).reduce(($,X)=>$.intersect(X).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(W.branches.length===0)A(r5(`keyof ${this.expression}`));return this._keyof=this.$.finalize(W)}get props(){if(this.branches.length!==1)return A(DA(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(W){let $=this.$.parseDefinition(W);return this.$.schema($.distribute((X)=>this.applyStructuralOperation("merge",[LU(X)??A(BU("merge",X.expression))])))}applyStructuralOperation(W,$){return this.distribute((X)=>{if(X.equals(N.intrinsic.object)&&W!=="merge")return X;let Y=LU(X);if(!Y)A(BU(W,X.expression));if(W==="keyof")return Y.keyof();if(W==="get")return Y.get(...$);if(W==="props")return Y.props;let J=W==="required"?"require":W==="partial"?"optionalize":W;return this.$.node("intersection",{...X.inner,structure:Y[J](...$)})})}get(...W){if(W[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",W))}extract(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((X)=>X.extends($)))}exclude(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((X)=>!X.extends($)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(W){return!(this.intersect(W)instanceof P)}extends(W){let $=this.intersect(W);return!($ instanceof P)&&this.equals($)}ifExtends(W){return this.extends(W)?this:void 0}subsumes(W){return this.$.parseDefinition(W).extends(this)}configure(W,$="shallow"){return this.configureReferences(W,$)}describe(W,$="shallow"){return this.configure({description:W},$)}optional(){return[this,"?"]}default(W){return l6(this,W,null),[this,"=",W]}from(W){return this.assert(W)}_pipe(...W){let $=W.reduce((X,Y)=>X.rawPipeOnce(Y),this);return this.$.finalize($)}tryPipe(...W){let $=W.reduce((X,Y)=>X.rawPipeOnce(d(Y,"root")?Y:(J,G)=>{try{return Y(J,G)}catch(H){return G.error({code:"predicate",predicate:Y,actual:`aborted due to error:
102
+ `);class CW{path=[];errors=new c1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(W,$){this.root=W,this.config=$}get data(){let W=this.root;for(let $ of this.path)W=W?.[$];return W}get propString(){return F2(this.path)}reject(W){return this.error(W),!1}mustBe(W){return this.error(W),!1}error(W){let $=typeof W==="object"?W.code?W:{...W,code:"predicate"}:{code:"predicate",expected:W};return this.errorFromContext($)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(W){let $={path:new y6(...this.path),morphs:W};if(this.currentBranch)this.currentBranch.queuedMorphs.push($);else this.queuedMorphs.push($)}finalize(W){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return W?W(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(W){return this.errorFromContext(W)}errorFromContext(W){let $=new d2(W,this);if(this.currentBranch)this.currentBranch.error=$;else this.errors.add($);return $}applyQueuedMorphs(){while(this.queuedMorphs.length){let W=this.queuedMorphs;this.queuedMorphs=[];for(let{path:$,morphs:X}of W){if(this.errors.affectsPath($))continue;this.applyMorphsAtPath($,X)}}}applyMorphsAtPath(W,$){let X=W.at(-1),Y;if(X!==void 0){Y=this.root;for(let G=0;G<W.length-1;G++)Y=Y[W[G]]}this.path=[...W];for(let G of $){let J=x0(G),H=G(Y===void 0?this.root:Y[X],this);if(H instanceof d2){this.errors.add(H);break}if(H instanceof c1){if(!J)this.errors.merge(H);break}if(Y===void 0)this.root=H;else Y[X]=H;this.applyQueuedMorphs()}}}var d1=(W,$,X)=>{if(!X)return $();X.path.push(W);let Y=$();return X.path.pop(),Y};class p6 extends qW{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(W,$){super((Y,G,J=this.onFail)=>{if(G)return this.traverseApply(Y,G),G.hasError()?G.errors:G.data;return this.rootApply(Y,J)},{attach:W});this.attachments=W,this.$=$,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((Y,G)=>gK(Y,G.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let Y=0;Y<this.children.length;Y++){if(this.includesTransform||=this.children[Y].includesTransform,this.includesContextualPredicate||=this.children[Y].includesContextualPredicate,this.isCyclic||=this.children[Y].isCyclic,!X){let G=this.children[Y].flatRefs;for(let J=0;J<G.length;J++){let H=G[J];if(!this.flatRefs.some((Q)=>eF(Q,H))){this.flatRefs.push(H);for(let Q of H.node.branches)if(Q.hasKind("morph")||Q.hasKind("intersection")&&Q.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:H.path,propString:H.propString,node:Q})}}}Object.assign(this.referencesById,this.children[Y].referencesById)}this.flatRefs.sort((Y,G)=>Y.path.length>G.path.length?1:Y.path.length<G.path.length?-1:Y.propString>G.propString?1:Y.propString<G.propString?-1:Y.node.expression<G.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((Y)=>Y.length===1||Y.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((Y)=>Y.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(Y)=>this.traverseAllows(Y,new CW(Y,this.$.resolvedConfig)):(Y)=>this.traverseAllows(Y)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return($,X)=>{if(this.allows($))return $;let Y=new CW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"contextual":return($,X)=>{let Y=new CW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let W=this.$.resolvedConfig.clone;return($,X)=>{if(this.allows($))return this.contextFreeMorph(W&&(typeof $==="object"&&$!==null||typeof $==="function")?W($):$);let Y=new CW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,K0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=hK(this.metaJson);cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=C4(this.kind);precompilation;assert=(W,$)=>this(W,$,(X)=>X.throw());traverse(W,$){return this(W,$,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(W){if(!this.includesTransform)return this;let $={};for(let[X,Y]of this.innerEntries){let G=this.impl.keys[X];if(G.reduceIo)G.reduceIo(W,$,Y);else if(G.child){let J=Y;$[X]=k0(J)?J.map((H)=>H[W]):J[W]}else $[X]=Y}return this.$.node(this.kind,$)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(W){let $=x0(W)?W:this.$.parseDefinition(W);return this.innerHash===$.innerHash}ifEquals(W){return this.equals(W)?this:void 0}hasKind(W){return this.kind===W}assertHasKind(W){if(this.kind!==W)Z8(`${this.kind} node was not of asserted kind ${W}`);return this}hasKindIn(...W){return W.includes(this.kind)}assertHasKindIn(...W){if(!H2(W,this.kind))Z8(`${this.kind} node was not one of asserted kinds ${W}`);return this}isBasis(){return H2(iF,this.kind)}isConstraint(){return H2(iY,this.kind)}isStructural(){return H2(Z4,this.kind)}isRefinement(){return H2(o7,this.kind)}isRoot(){return H2(S4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(W){return this.hasKind("unit")&&this.allows(W)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(W){let $=m6.normalize(W);return this._select($)}_select(W){let $=m6.applyBoundary[W.boundary??"references"](this);if(W.kind)$=$.filter((X)=>X.kind===W.kind);if(W.where)$=$.filter(W.where);return m6.applyMethod[W.method??"filter"]($,this,W)}transform(W,$){return this._transform(W,this._createTransformContext($))}_createTransformContext(W){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:W?.prereduced??!1},undeclaredKeyHandling:void 0,...W}}_transform(W,$){let X=$.bindScope??this.$;if($.seen[this.id])return this.$.lazilyResolve($.seen[this.id]);if($.shouldTransform?.(this,$)===!1)return this;let Y;if($.seen[this.id]=()=>Y,this.hasKind("structure")&&this.undeclared!==$.undeclaredKeyHandling)$={...$,undeclaredKeyHandling:this.undeclared};let G=Y0(this.inner,(T,F)=>{if(!this.impl.keys[T].child)return[T,F];let _=F;if(!k0(_)){let O=_._transform(W,$);return O?[T,O]:[]}if(_.length===0)return[T,F];let w=_.flatMap((O)=>{return O._transform(W,$)??[]});return w.length?[T,w]:[]});delete $.seen[this.id];let J=Object.assign(G,{meta:this.meta}),H=$.selected&&!$.selected.includes(this)?J:W(this.kind,J,$);if(H===null)return null;if(x0(H))return Y=H;let Q=Object.keys(H);if((Q.length===0||Q.length===1&&Q[0]==="meta")&&!cW(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in H))return $.undeclaredKeyHandling?{...H,value:N.intrinsic.unknown}:null;if(this.kind==="morph")H.in??=N.intrinsic.unknown;return Y=X.node(this.kind,H,$.parseOptions)}configureReferences(W,$="references"){let X=m6.normalize($),Y=typeof W==="string"?(Q,z)=>({...z,meta:{...z.meta,description:W}}):typeof W==="function"?(Q,z)=>({...z,meta:W(z.meta)}):(Q,z)=>({...z,meta:{...z.meta,...W}});if(X.boundary==="self")return this.$.node(this.kind,Y(this.kind,{...this.inner,meta:this.meta}));let G=this._select(X),J=G&&g2(G),H=X.boundary==="child"?(Q,z)=>z.root.children.includes(Q):X.boundary==="shallow"?(Q)=>Q.kind!=="structure":()=>!0;return this.$.finalize(this.transform(Y,{shouldTransform:H,selected:J}))}}var m6={applyBoundary:{self:(W)=>[W],child:(W)=>[...W.children],shallow:(W)=>[...W.shallowReferences],references:(W)=>[...W.references]},applyMethod:{filter:(W)=>W,assertFilter:(W,$,X)=>{if(W.length===0)Z8(sF($,X));return W},find:(W)=>W[0],assertFind:(W,$,X)=>{if(W.length===0)Z8(sF($,X));return W[0]}},normalize:(W)=>typeof W==="function"?{boundary:"references",method:"filter",where:W}:typeof W==="string"?T1(W,m6.applyBoundary)?{method:"filter",boundary:W}:{boundary:"references",method:"filter",kind:W}:{boundary:"references",method:"filter",...W}},sF=(W,$)=>`${W} had no references matching ${G0($)}.`,vK=(W)=>F2(W,{stringifyNonKey:($)=>$.expression}),yK=/"(\$ark\.[^"]+)"/g,hK=(W)=>JSON.stringify(W).replaceAll(yK,"$1"),kW=(W,$)=>({path:W,node:$,propString:vK(W)}),eF=(W,$)=>W.propString===$.propString&&W.node.equals($.node),r7=(W,$)=>uW(W,$,{isEqual:eF}),gK=(W,$)=>uW(W,$,{isEqual:(X,Y)=>X.equals(Y)});class b extends Array{static init(W,$,X,Y){return new b({kind:W,l:$,r:X,path:Y?.path??[],optional:Y?.optional??!1})}add(W,$,X,Y){return this.push({kind:W,l:$,r:X,path:Y?.path??[],optional:Y?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:W,l:$,r:X}=this[0],Y=F2(W);return a7(`Intersection${Y&&` at ${Y}`} of ${W_($,X)}`)}return`The following intersections result in unsatisfiable types:
103
+ \u2022 ${this.map(({path:W,l:$,r:X})=>`${W}: ${W_($,X)}`).join(`
104
+ \u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let W=this.map(($)=>({...$,l:$.r,r:$.l}));if(!(W instanceof b))return new b(...W);return W}withPrefixKey(W,$){return this.map((X)=>({...X,path:[W,...X.path],optional:X.optional||$==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var W_=(W,$)=>`${t7(W)} and ${t7($)}`,t7=(W)=>x0(W)?W.expression:k0(W)?W.map(t7).join(" | ")||"never":String(W),a7=(W)=>`${W} results in an unsatisfiable type`;var k4={},l1=(W,$,X)=>b0(W,$,{$:X,invert:!1,pipe:!1}),u6=(W,$,X)=>b0(W,$,{$:X,invert:!1,pipe:!0}),b0=(W,$,X)=>{let Y=X.pipe?"|>":"&",G=`${W.hash}${Y}${$.hash}`;if(k4[G]!==void 0)return k4[G];if(!X.pipe){let Q=`${$.hash}${Y}${W.hash}`;if(k4[Q]!==void 0){let z=k4[Q],T=z instanceof b?z.invert():z;return k4[G]=T,T}}let J=!X.pipe||!W.includesTransform&&!$.includesTransform;if(J&&W.equals($))return W;let H=J?s7(W,$,X):W.hasKindIn(...S4)?mK(W,$,X):s7(W,$,X);if(x0(H)){if(W.equals(H))H=W;else if($.equals(H))H=$}return k4[G]=H,H},s7=(W,$,X)=>{let Y=W.precedence<$.precedence?W.kind:$.kind,G=W.impl.intersections[$.kind]??$.impl.intersections[W.kind];if(G===void 0)return null;else if(Y===W.kind)return G(W,$,X);else{let J=G($,W,{...X,invert:!X.invert});if(J instanceof b)J=J.invert();return J}},mK=(W,$,X)=>W.includesTransform||$.includesTransform?X.invert?$_($,W,X):$_(W,$,X):s7(W,$,X),$_=(W,$,X)=>W.distribute((Y)=>pK(Y,$,X),(Y)=>{let G=Y.filter(x0);if(G.length===0)return b.init("union",W.branches,$.branches);if(G.length<W.branches.length||!W.branches.every((Q,z)=>Q.in.equals(G[z].in)))return X.$.parseSchema(G);let J;if(G.length===1){let Q=G[0];if(!J)return Q;return X.$.node("morph",{...Q.inner,in:Q.in.configure(J,"self")})}let H={branches:G};if(J)H.meta=J;return X.$.parseSchema(H)}),pK=(W,$,X)=>{if(W.hasKind("morph")){let G=[...W.morphs];if(W.lastMorphIfNode){let J=b0(W.lastMorphIfNode,$,X);if(J instanceof b)return J;G[G.length-1]=J}else G.push($);return X.$.node("morph",{morphs:G,in:W.inner.in})}if($.hasKind("morph")){let G=b0(W,$.in,X);if(G instanceof b)return G;return X.$.node("morph",{morphs:[$],in:G})}return X.$.node("morph",{morphs:[$],in:W})};class wW extends p6{constructor(W,$){super(W,$);Object.defineProperty(this,f1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(W){return l1(this,W,this.$)}}class w2 extends wW{traverseApply=(W,$)=>{if(!this.traverseAllows(W,$))$.errorFromNodeContext(this.errorContext)};compile(W){if(W.traversalKind==="Allows")W.return(this.compiledCondition);else W.if(this.compiledNegation,()=>W.line(`${W.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return c2(this.errorContext)}}var N1=(W)=>($,X)=>{if(k0($)){if($.length===0)return;let G=$.map((J)=>X.$.node(W,J));if(W==="predicate")return G;return G.sort((J,H)=>J.hash<H.hash?-1:1)}let Y=X.$.node(W,$);return Y.hasOpenIntersection()?[Y]:Y},j4=(W)=>{let $=W.r.shift();if(!$){let Y=W.l.length===0&&W.kind==="structure"?N.intrinsic.unknown.internal:W.ctx.$.node(W.kind,Object.assign(W.baseInner,uK(W.l)),{prereduced:!0});for(let G of W.roots){if(Y instanceof b)return Y;Y=b0(G,Y,W.ctx)}return Y}let X=!1;for(let Y=0;Y<W.l.length;Y++){let G=b0(W.l[Y],$,W.ctx);if(G===null)continue;if(G instanceof b)return G;if(!X){if(G.isRoot())return W.roots.push(G),W.l.splice(Y),j4(W);W.l[Y]=G,X=!0}else if(!W.l.includes(G))return K0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!X)W.l.push($);if(W.kind==="intersection"){if($.impliedSiblings)for(let Y of $.impliedSiblings)uW(W.r,Y)}return j4(W)},I4=(W)=>{return Object.entries(W).flatMap(([X,Y])=>(X in nY)?Y:[]).sort((X,Y)=>X.precedence<Y.precedence?-1:X.precedence>Y.precedence?1:X.kind==="predicate"&&Y.kind==="predicate"?0:X.hash<Y.hash?-1:1)},uK=(W)=>{let $={};for(let X of W)if(X.hasOpenIntersection())$[X.kind]=D0($[X.kind],X);else{if($[X.kind])return K0(`Unexpected intersection of closed refinements of kind ${X.kind}`);$[X.kind]=X}return $},X_=(...W)=>E(Y_(...W)),Y_=(W,$,X)=>{let Y=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude($).defaultShortDescription;return`${PF(W)} operand must be ${$.description} (was ${Y})`};var G_=(W,$,X)=>new l2(W,$,X,X,null);class tY extends qW{}class l2 extends qW{[f1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(W,$,X,Y,G){super((...J)=>{let H=Y0(this.names,(Q,z)=>{let T=this.arg$.parse(J[Q]);if(!T.extends(this.constraints[Q]))E(cK(z,this.constraints[Q].expression,T.expression));return[z,T]});if(this.defIsLazy()){let Q=this.bodyDef(H);return this.$.parse(Q)}return this.$.parse($,{args:H})});this.paramDefs=W,this.bodyDef=$,this.$=X,this.arg$=Y,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof tY}cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get json(){return this.cacheGetter("json",{params:this.params.map((W)=>W[1].isUnknown()?W[0]:[W[0],W[1].json]),body:cF(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((W)=>typeof W==="string"?[W,N.intrinsic.unknown]:[W[0],this.$.parse(W[1])]))}get names(){return this.cacheGetter("names",this.params.map((W)=>W[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((W)=>W[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var cK=(W,$,X)=>`${W} must be assignable to ${$} (was ${X})`;var dK=J0({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(W)=>typeof W==="function"?{predicate:W}:W,defaults:{description:(W)=>`valid according to ${W.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class J_ extends wW{serializedPredicate=d0(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=c2(this.errorContext);traverseApply=(W,$)=>{if(!this.predicate(W,$.external)&&!$.hasError())$.errorFromNodeContext(this.errorContext)};compile(W){if(W.traversalKind==="Allows"){W.return(this.compiledCondition);return}W.if(`${this.compiledNegation} && !ctx.hasError()`,()=>W.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(W,$){return $.fallback.predicate({code:"predicate",base:W,predicate:this.predicate})}}var e7={implementation:dK,Node:J_};var lK=J0({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(W)=>Number.isInteger(W)?W:E(oK(W))}},normalize:(W)=>typeof W==="number"?{rule:W}:W,hasAssociatedError:!0,defaults:{description:(W)=>W.rule===1?"an integer":W.rule===2?"even":`a multiple of ${W.rule}`},intersections:{divisor:(W,$,X)=>X.$.node("divisor",{rule:Math.abs(W.rule*$.rule/iK(W.rule,$.rule))})},obviatesBasisDescription:!0});class H_ extends w2{traverseAllows=(W)=>W%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(W){if(W.type="integer",this.rule===1)return W;return W.multipleOf=this.rule,W}}var WG={implementation:lK,Node:H_};var oK=(W)=>`divisor must be an integer (was ${W})`,iK=(W,$)=>{let X,Y=W,G=$;while(G!==0)X=G,G=Y%G,Y=X;return Y};class XW extends w2{boundOperandKind=aK[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=sK(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${nK[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?eK(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(W){return(this.limitKind==="upper"?this.numericLimit<W.numericLimit:this.numericLimit>W.numericLimit)||this.numericLimit===W.numericLimit&&this.exclusive===!0&&!W.exclusive}overlapsRange(W){if(this.isStricterThan(W))return!1;if(this.numericLimit===W.numericLimit&&(this.exclusive||W.exclusive))return!1;return!0}overlapIsUnit(W){return this.numericLimit===W.numericLimit&&!this.exclusive&&!W.exclusive}}var nK={"<":">=","<=":">",">":"<=",">=":"<"},rK={min:"max",minLength:"maxLength",after:"before"},aY={parse:(W)=>W||void 0},sY=(W)=>($)=>{if(typeof $==="number")return{rule:$};let{exclusive:X,...Y}=$;return X?{...Y,rule:W==="minLength"?Y.rule+1:Y.rule-1}:Y},eY=(W)=>($)=>{if(typeof $==="number"||typeof $==="string"||$ instanceof Date)return{rule:$};let{exclusive:X,...Y}=$;if(!X)return Y;let G=typeof Y.rule==="number"?Y.rule:typeof Y.rule==="string"?new Date(Y.rule).valueOf():Y.rule.valueOf();return X?{...Y,rule:W==="after"?G+1:G-1}:Y},W9=(W)=>typeof W==="string"||typeof W==="number"?new Date(W):W,tK=(W,$)=>`${W} bound must be a positive integer (was ${$})`,P4=(W)=>($)=>{if(!Number.isInteger($)||$<0)E(tK(W,$));return $},aK={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},sK=(W,$)=>`${T1(W,rK)?">":"<"}${$?"":"="}`,eK=(W)=>typeof W==="string"?W:new Date(W).toLocaleString(),Q_=(W)=>`Bounded expression ${W} must be exactly one of number, string, Array, or Date`;var WA=J0({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:W9,serialize:(W)=>W.toISOString()}},normalize:eY("after"),defaults:{description:(W)=>`${W.collapsibleLimitString} or later`,actual:k8},intersections:{after:(W,$)=>W.isStricterThan($)?W:$}});class z_ extends XW{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=k8(this.rule);traverseAllows=(W)=>W>=this.rule;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,after:this.rule})}}var $G={implementation:WA,Node:z_};var $A=J0({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:W9,serialize:(W)=>W.toISOString()}},normalize:eY("before"),defaults:{description:(W)=>`${W.collapsibleLimitString} or earlier`,actual:k8},intersections:{before:(W,$)=>W.isStricterThan($)?W:$,after:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("unit",{unit:W.rule}):null:b.init("range",W,$)}});class T_ extends XW{collapsibleLimitString=k8(this.rule);traverseAllows=(W)=>W<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,before:this.rule})}}var XG={implementation:$A,Node:T_};var XA=J0({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:P4("exactLength")}},normalize:(W)=>typeof W==="number"?{rule:W}:W,hasAssociatedError:!0,defaults:{description:(W)=>`exactly length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{exactLength:(W,$,X)=>b.init("unit",X.$.node("unit",{unit:W.rule}),X.$.node("unit",{unit:$.rule}),{path:["length"]}),minLength:(W,$)=>W.rule>=$.rule?W:b.init("range",W,$),maxLength:(W,$)=>W.rule<=$.rule?W:b.init("range",W,$)}});class F_ extends w2{traverseAllows=(W)=>W.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(W){switch(W.type){case"string":return W.minLength=this.rule,W.maxLength=this.rule,W;case"array":return W.minItems=this.rule,W.maxItems=this.rule,W;default:return h0.throwInternalOperandError("exactLength",W)}}}var YG={implementation:XA,Node:F_};var YA=J0({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:aY},normalize:(W)=>typeof W==="number"?{rule:W}:W,defaults:{description:(W)=>{if(W.rule===0)return W.exclusive?"negative":"non-positive";return`${W.exclusive?"less than":"at most"} ${W.rule}`}},intersections:{max:(W,$)=>W.isStricterThan($)?W:$,min:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("unit",{unit:W.rule}):null:b.init("range",W,$)},obviatesBasisDescription:!0});class __ extends XW{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(W)=>W<this.rule:(W)=>W<=this.rule;reduceJsonSchema(W){if(this.exclusive)W.exclusiveMaximum=this.rule;else W.maximum=this.rule;return W}}var GG={implementation:YA,Node:__};var GA=J0({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:P4("maxLength")}},reduce:(W,$)=>W.rule===0?$.node("exactLength",W):void 0,normalize:sY("maxLength"),defaults:{description:(W)=>`at most length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{maxLength:(W,$)=>W.isStricterThan($)?W:$,minLength:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("exactLength",{rule:W.rule}):null:b.init("range",W,$)}});class w_ extends XW{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(W)=>W.length<=this.rule;reduceJsonSchema(W){switch(W.type){case"string":return W.maxLength=this.rule,W;case"array":return W.maxItems=this.rule,W;default:return h0.throwInternalOperandError("maxLength",W)}}}var JG={implementation:GA,Node:w_};var JA=J0({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:aY},normalize:(W)=>typeof W==="number"?{rule:W}:W,defaults:{description:(W)=>{if(W.rule===0)return W.exclusive?"positive":"non-negative";return`${W.exclusive?"more than":"at least"} ${W.rule}`}},intersections:{min:(W,$)=>W.isStricterThan($)?W:$},obviatesBasisDescription:!0});class U_ extends XW{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(W)=>W>this.rule:(W)=>W>=this.rule;reduceJsonSchema(W){if(this.exclusive)W.exclusiveMinimum=this.rule;else W.minimum=this.rule;return W}}var HG={implementation:JA,Node:U_};var HA=J0({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:P4("minLength")}},reduce:(W)=>W.rule===0?N.intrinsic.unknown:void 0,normalize:sY("minLength"),defaults:{description:(W)=>W.rule===1?"non-empty":`at least length ${W.rule}`,actual:(W)=>W.length===0?"":`${W.length}`},intersections:{minLength:(W,$)=>W.isStricterThan($)?W:$}});class D_ extends XW{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(W)=>W.length>=this.rule;reduceJsonSchema(W){switch(W.type){case"string":return W.minLength=this.rule,W;case"array":return W.minItems=this.rule,W;default:return h0.throwInternalOperandError("minLength",W)}}}var QG={implementation:HA,Node:D_};var V_={min:HG.implementation,max:GG.implementation,minLength:QG.implementation,maxLength:JG.implementation,exactLength:YG.implementation,after:$G.implementation,before:XG.implementation},M_={min:HG.Node,max:GG.Node,minLength:QG.Node,maxLength:JG.Node,exactLength:YG.Node,after:$G.Node,before:XG.Node};var QA=J0({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(W)=>typeof W==="string"?{rule:W}:W instanceof RegExp?W.flags?{rule:W.source,flags:W.flags}:{rule:W.source}:W,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(W)=>`matched by ${W.rule}`},intersections:{pattern:()=>null}});class O_ extends w2{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=N.intrinsic.string.internal;reduceJsonSchema(W,$){if(W.pattern)return $.fallback.patternIntersection({code:"patternIntersection",base:W,pattern:this.rule});return W.pattern=this.rule,W}}var zG={implementation:QA,Node:O_};var c6=(W,$)=>{let X=zA(W);if($&&!$.includes(X))return E(`Root of kind ${X} should be one of ${$}`);return X},zA=(W)=>{if(d(W,"root"))return W.kind;if(typeof W==="string")return W[0]==="$"?"alias":(W in u1)?"domain":"proto";if(typeof W==="function")return"proto";if(typeof W!=="object"||W===null)return E(K_(W));if("morphs"in W)return"morph";if("branches"in W||k0(W))return"union";if("unit"in W)return"unit";if("reference"in W)return"alias";let $=Object.keys(W);if($.length===0||$.some((X)=>(X in nY)))return"intersection";if("proto"in W)return"proto";if("domain"in W)return"domain";return E(K_(W))},K_=(W)=>`${G0(W)} is not a valid type schema`,A_={},TA=(W)=>k0(W)?W.map(($)=>$.collapsibleJson):W.collapsibleJson,x1={};N.nodesByRegisteredId=x1;var TG=(W)=>{return A_[W]??=0,`${W}${++A_[W]}`},FG=(W)=>{let $=f4[W.kind],X=$.applyConfig?.(W.def,W.$.resolvedConfig)??W.def,Y={},{meta:G,...J}=X,H=G===void 0?{}:typeof G==="string"?{description:G}:G,Q=f7(J).sort(([T],[F])=>q4(T)?q4(F)?C4(T)-C4(F):1:q4(F)?-1:T<F?-1:1).filter(([T,F])=>{if(T.startsWith("meta.")){let _=T.slice(5);return H[_]=F,!1}return!0});for(let T of Q){let F=T[0],_=$.keys[F];if(!_)return E(`Key ${F} is not valid on ${W.kind} schema`);let w=_.parse?_.parse(T[1],W):T[1];if(w!==$W&&(w!==void 0||_.preserveUndefined))Y[F]=w}if($.reduce&&!W.prereduced){let T=$.reduce(Y,W.$);if(T){if(T instanceof b)return T.throw();return FA(T,H)}}return _G({id:W.id,kind:W.kind,inner:Y,meta:H,$:W.$})},_G=({id:W,kind:$,inner:X,meta:Y,$:G,ignoreCache:J})=>{let H=f4[$],Q=f7(X),z=[],T={};for(let[j,R]of Q){let Z=H.keys[j],P=Z.serialize??(Z.child?TA:_W);if(T[j]=P(R),Z.child===!0){let h=R;if(k0(h))z.push(...h);else z.push(h)}else if(typeof Z.child==="function")z.push(...Z.child(R))}if(H.finalizeInnerJson)T=H.finalizeInnerJson(T);let F={...T},_={};if(!cW(Y))_=Y0(Y,(j,R)=>[j,j==="examples"?R:_W(R)]),F.meta=$9(_,"description",!0);T=$9(T,H.collapsibleKey,!1);let w=JSON.stringify({kind:$,...T});F=$9(F,H.collapsibleKey,!1);let O=$9(F,H.collapsibleKey,!0),M=JSON.stringify({kind:$,...F});if(G.nodesByHash[M]&&!J)return G.nodesByHash[M];let A={id:W,kind:$,impl:H,inner:X,innerEntries:Q,innerJson:T,innerHash:w,meta:Y,metaJson:_,json:F,hash:M,collapsibleJson:O,children:z};if($!=="intersection"){for(let j in X)if(j!=="in"&&j!=="out")A[j]=X[j]}let I=new L_[$](A,G);return G.nodesByHash[M]=I},E_=(W,$)=>{if(W.id===$)return W;if(x0(x1[$]))K0(`Unexpected attempt to overwrite node id ${$}`);return _G({id:$,kind:W.kind,inner:W.inner,meta:W.meta,$:W.$,ignoreCache:!0})},FA=(W,$,X)=>{if(X&&x0(x1[X]))K0(`Unexpected attempt to overwrite node id ${X}`);return _G({id:X??TG($.alias??W.kind),kind:W.kind,inner:W.inner,meta:$,$:W.$})},$9=(W,$,X)=>{let Y=Object.keys(W);if(Y.length===1&&Y[0]===$){let G=W[$];if(X)return G;if(p1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return W};var d6=(W,$,X)=>{if(W.key!==$.key)return null;let Y=W.key,G=b0(W.value,$.value,X),J=W.required||$.required?"required":"optional";if(G instanceof b)if(J==="optional")G=N.intrinsic.never.internal;else return G.withPrefixKey(W.key,W.required&&$.required?"required":"optional");if(J==="required")return X.$.node("required",{key:Y,value:G});let H=W.hasDefault()?$.hasDefault()?W.default===$.default?W.default:E(wG(W.default,$.default)):W.default:$.hasDefault()?$.default:$W;return X.$.node("optional",{key:Y,value:G,default:H})};class l6 extends wW{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=_2(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=D0(this.value.flatRefs.map((W)=>kW([this.key,...W.path],W.node)),kW([this.key],this.value));_transform(W,$){$.path.push(this.key);let X=super._transform(W,$);return $.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(W,$)=>{if(this.key in W)return d1(this.key,()=>this.value.traverseAllows(W[this.key],$),$);return this.optional};traverseApply=(W,$)=>{if(this.key in W)d1(this.key,()=>this.value.traverseApply(W[this.key],$),$);else if(this.hasKind("required"))$.errorFromNodeContext(this.errorContext)};compile(W){if(W.if(`${this.serializedKey} in data`,()=>W.traverseKey(this.serializedKey,`data${W.prop(this.key)}`,this.value)),this.hasKind("required"))W.else(()=>W.traversalKind==="Apply"?W.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):W.return(!1));if(W.traversalKind==="Allows")W.return(!0)}}var wG=(W,$)=>`Invalid intersection of default values ${G0(W)} & ${G0($)}`;var _A=J0({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)},default:{preserveUndefined:!0}},normalize:(W)=>W,reduce:(W,$)=>{if($.resolvedConfig.exactOptionalPropertyTypes===!1){if(!W.value.allows(void 0))return $.node("optional",{...W,value:W.value.or(r.undefined)},{prereduced:!0})}},defaults:{description:(W)=>`${W.compiledKey}?: ${W.value.description}`},intersections:{optional:d6}});class B_ extends l6{constructor(...W){super(...W);if("default"in this.inner)i6(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:W,...$}=this.inner;return this.cacheGetter("outProp",this.$.node("required",$,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${G0(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=UA(this);defaultValueMorphRef=this.defaultValueMorph&&d0(this.defaultValueMorph)}var o6={implementation:_A,Node:B_},wA={},UA=(W)=>{if(!W.hasDefault())return;let $=`{${W.compiledKey}: ${W.value.id} = ${_W(W.default)}}`;return wA[$]??=UG(W.key,W.value,W.default)},UG=(W,$,X)=>{if(typeof X==="function")return $.includesTransform?(G,J)=>{return d1(W,()=>$(G[W]=X(),J),J),G}:(G)=>{return G[W]=X(),G};let Y=$.includesTransform?$.assert(X):X;return p1(Y,"object")?(G,J)=>{return d1(W,()=>$(G[W]=X,J),J),G}:(G)=>{return G[W]=Y,G}},i6=(W,$,X)=>{let Y=m2($);if(p1($,"object")&&!Y)E(DA(X));let G=W.in(Y?$():$);if(G instanceof c1){if(X===null)E(`Default ${G.summary}`);let J=G.transform((H)=>H.transform((Q)=>({...Q,prefixPath:[X]})));E(`Default for ${J.summary}`)}return $},DA=(W)=>{return`Non-primitive default ${W===null?"":typeof W==="number"?`for value at [${W}] `:`for ${_2(W)} `}must be specified as a function like () => ({my: 'object'})`};class UW extends p6{constructor(W,$){super(W,$);Object.defineProperty(this,f1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(W)=>{let $=this(W);if($ instanceof c1)return $;return{value:$}}}}as(){return this}brand(W){if(W==="")return E(VA);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(W,$){let X=this.branches.map(W);return $?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(W={}){let $=i7(this.$.resolvedConfig.toJsonSchema,W);$.useRefs||=this.isCyclic;let X=typeof $.dialect==="string"?{$schema:$.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse($)),$.useRefs)X.$defs=Y0(this.references,(Y,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema($)]:[]);return X}toJsonSchemaRecurse(W){if(W.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(W)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(W){let $=this.innerToJsonSchema(W);return Object.assign($,this.metaJson)}intersect(W){let $=this.$.parseDefinition(W),X=this.rawIntersect($);if(X instanceof b)return X;return this.$.finalize(X)}rawIntersect(W){return l1(this,W,this.$)}toNeverIfDisjoint(){return this}and(W){let $=this.intersect(W);return $ instanceof b?$.throw():$}rawAnd(W){let $=this.rawIntersect(W);return $ instanceof b?$.throw():$}or(W){let $=this.$.parseDefinition(W);return this.$.finalize(this.rawOr($))}rawOr(W){let $=[...this.branches,...W.branches];return this.$.node("union",$)}map(W){return this.$.schema(this.applyStructuralOperation("map",[W]))}pick(...W){return this.$.schema(this.applyStructuralOperation("pick",W))}omit(...W){return this.$.schema(this.applyStructuralOperation("omit",W))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let W=this.applyStructuralOperation("keyof",[]).reduce(($,X)=>$.intersect(X).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(W.branches.length===0)E(a7(`keyof ${this.expression}`));return this._keyof=this.$.finalize(W)}get props(){if(this.branches.length!==1)return E(MA(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(W){let $=this.$.parseDefinition(W);return this.$.schema($.distribute((X)=>this.applyStructuralOperation("merge",[R_(X)??E(N_("merge",X.expression))])))}applyStructuralOperation(W,$){return this.distribute((X)=>{if(X.equals(N.intrinsic.object)&&W!=="merge")return X;let Y=R_(X);if(!Y)E(N_(W,X.expression));if(W==="keyof")return Y.keyof();if(W==="get")return Y.get(...$);if(W==="props")return Y.props;let G=W==="required"?"require":W==="partial"?"optionalize":W;return this.$.node("intersection",{...X.inner,structure:Y[G](...$)})})}get(...W){if(W[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",W))}extract(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((X)=>X.extends($)))}exclude(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((X)=>!X.extends($)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(W){return!(this.intersect(W)instanceof b)}extends(W){let $=this.intersect(W);return!($ instanceof b)&&this.equals($)}ifExtends(W){return this.extends(W)?this:void 0}subsumes(W){return this.$.parseDefinition(W).extends(this)}configure(W,$="shallow"){return this.configureReferences(W,$)}describe(W,$="shallow"){return this.configure({description:W},$)}optional(){return[this,"?"]}default(W){return i6(this,W,null),[this,"=",W]}from(W){return this.assert(W)}_pipe(...W){let $=W.reduce((X,Y)=>X.rawPipeOnce(Y),this);return this.$.finalize($)}tryPipe(...W){let $=W.reduce((X,Y)=>X.rawPipeOnce(d(Y,"root")?Y:(G,J)=>{try{return Y(G,J)}catch(H){return J.error({code:"predicate",predicate:Y,actual:`aborted due to error:
105
105
  ${H}
106
- `})}}),this);return this.$.finalize($)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(W){return this.$.finalize(this.toNode(this.$.parseDefinition(W)))}toNode(W){let $=m6(this,W,this.$);if($ instanceof P)return $.throw();return $}rawPipeOnce(W){if(d(W,"root"))return this.toNode(W);return this.distribute(($)=>$.hasKind("morph")?this.$.node("morph",{in:$.inner.in,morphs:[...$.morphs,W]}):this.$.node("morph",{in:$,morphs:[W]}),this.$.parseSchema)}narrow(W){return this.constrainOut("predicate",W)}constrain(W,$){return this._constrain("root",W,$)}constrainIn(W,$){return this._constrain("in",W,$)}constrainOut(W,$){return this._constrain("out",W,$)}_constrain(W,$,X){let Y=this.$.node($,X);if(Y.isRoot())return Y.isUnknown()?this:K0(`Unexpected constraint node ${Y}`);let J=W==="root"?this:this[W];if(J.hasKind("morph")||Y.impliedBasis&&!J.extends(Y.impliedBasis))return WU($,Y.impliedBasis,this);let G=this.$.node("intersection",{[Y.kind]:Y}),H=W==="out"?m6(this,G,this.$):d1(this,G,this.$);if(H instanceof P)H.throw();return this.$.finalize(H)}onUndeclaredKey(W){let $=typeof W==="string"?W:W.rule,X=typeof W==="string"?!1:W.deep;return this.$.finalize(this.transform((Y,J)=>Y==="structure"?$==="ignore"?AT(J,{undeclared:1}):{...J,undeclared:$}:J,X?void 0:{shouldTransform:(Y)=>!H2(R$,Y.kind)}))}hasEqualMorphs(W){if(!this.includesTransform&&!W.includesTransform)return!0;if(!z2(this.shallowMorphs,W.shallowMorphs))return!1;if(!z2(this.flatMorphs,W.flatMorphs,{isEqual:($,X)=>$.propString===X.propString&&($.node.hasKind("morph")&&X.node.hasKind("morph")?$.node.hasEqualMorphs(X.node):$.node.hasKind("intersection")&&X.node.hasKind("intersection")?$.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(W){return this.onUndeclaredKey({rule:W,deep:!0})}filter(W){return this.constrainIn("predicate",W)}divisibleBy(W){return this.constrain("divisor",W)}matching(W){return this.constrain("pattern",W)}atLeast(W){return this.constrain("min",W)}atMost(W){return this.constrain("max",W)}moreThan(W){return this.constrain("min",f$(W))}lessThan(W){return this.constrain("max",f$(W))}atLeastLength(W){return this.constrain("minLength",W)}atMostLength(W){return this.constrain("maxLength",W)}moreThanLength(W){return this.constrain("minLength",f$(W))}lessThanLength(W){return this.constrain("maxLength",f$(W))}exactlyLength(W){return this.constrain("exactLength",W)}atOrAfter(W){return this.constrain("after",W)}atOrBefore(W){return this.constrain("before",W)}laterThan(W){return this.constrain("after",f$(W))}earlierThan(W){return this.constrain("before",f$(W))}}var _A="Expected a non-empty brand name after #",f$=(W)=>typeof W==="object"&&!(W instanceof Date)?{...W,exclusive:!0}:{rule:W,exclusive:!0},o6=(W,$)=>d($,"root")?d(W,"root")?W.extends($):$.allows(W):d(W,"root")?W.hasUnit($):$===W,LU=(W)=>{if(W.hasKind("morph"))return null;if(W.hasKind("intersection"))return W.inner.structure??(W.basis?.domain==="object"?W.$.bindReference(N.intrinsic.emptyStructure):null);if(W.isBasis()&&W.domain==="object")return W.$.bindReference(N.intrinsic.emptyStructure);return null},DA=(W)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
107
- ${W}`,BU=(W,$)=>`${W} operand must be an object (was ${$})`;var dW=(W,$)=>X0(rY(W),(X,Y)=>[Y,$]);var MA=(W)=>typeof W==="string"?{reference:W}:W,RU=(W)=>W instanceof P?N.intrinsic.never.internal:W,VA=J0({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(W)=>W.startsWith("$")?W:`$ark.${W}`},resolve:{}},normalize:MA,defaults:{description:(W)=>W.reference},intersections:{alias:(W,$,X)=>X.$.lazilyResolve(()=>RU(v0(W.resolution,$.resolution,X)),`${W.reference}${X.pipe?"=>":"&"}${$.reference}`),...dW("alias",(W,$,X)=>{if($.isUnknown())return W;if($.isNever())return $;if($.isBasis()&&!$.overlaps(N.intrinsic.object))return P.init("assignability",N.intrinsic.object,$);return X.$.lazilyResolve(()=>RU(v0(W.resolution,$,X)),`${W.reference}${X.pipe?"=>":"&"}${$.id}`)})}});class NU extends wW{expression=this.reference;structure=void 0;get resolution(){let W=this._resolve();return P1[this.id]=W}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let W=this.reference,$=P1[W],X=[];while(d($,"context")){if(X.includes($.id))return A(OA($.id,X));X.push($.id),$=P1[$.id]}if(!d($,"root"))return K0(`Unexpected resolution for reference ${this.reference}
106
+ `})}}),this);return this.$.finalize($)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(W){return this.$.finalize(this.toNode(this.$.parseDefinition(W)))}toNode(W){let $=u6(this,W,this.$);if($ instanceof b)return $.throw();return $}rawPipeOnce(W){if(d(W,"root"))return this.toNode(W);return this.distribute(($)=>$.hasKind("morph")?this.$.node("morph",{in:$.inner.in,morphs:[...$.morphs,W]}):this.$.node("morph",{in:$,morphs:[W]}),this.$.parseSchema)}narrow(W){return this.constrainOut("predicate",W)}constrain(W,$){return this._constrain("root",W,$)}constrainIn(W,$){return this._constrain("in",W,$)}constrainOut(W,$){return this._constrain("out",W,$)}_constrain(W,$,X){let Y=this.$.node($,X);if(Y.isRoot())return Y.isUnknown()?this:K0(`Unexpected constraint node ${Y}`);let G=W==="root"?this:this[W];if(G.hasKind("morph")||Y.impliedBasis&&!G.extends(Y.impliedBasis))return X_($,Y.impliedBasis,this);let J=this.$.node("intersection",{[Y.kind]:Y}),H=W==="out"?u6(this,J,this.$):l1(this,J,this.$);if(H instanceof b)H.throw();return this.$.finalize(H)}onUndeclaredKey(W){let $=typeof W==="string"?W:W.rule,X=typeof W==="string"?!1:W.deep;return this.$.finalize(this.transform((Y,G)=>Y==="structure"?$==="ignore"?LF(G,{undeclared:1}):{...G,undeclared:$}:G,X?void 0:{shouldTransform:(Y)=>!H2(Z4,Y.kind)}))}hasEqualMorphs(W){if(!this.includesTransform&&!W.includesTransform)return!0;if(!z2(this.shallowMorphs,W.shallowMorphs))return!1;if(!z2(this.flatMorphs,W.flatMorphs,{isEqual:($,X)=>$.propString===X.propString&&($.node.hasKind("morph")&&X.node.hasKind("morph")?$.node.hasEqualMorphs(X.node):$.node.hasKind("intersection")&&X.node.hasKind("intersection")?$.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(W){return this.onUndeclaredKey({rule:W,deep:!0})}filter(W){return this.constrainIn("predicate",W)}divisibleBy(W){return this.constrain("divisor",W)}matching(W){return this.constrain("pattern",W)}atLeast(W){return this.constrain("min",W)}atMost(W){return this.constrain("max",W)}moreThan(W){return this.constrain("min",x4(W))}lessThan(W){return this.constrain("max",x4(W))}atLeastLength(W){return this.constrain("minLength",W)}atMostLength(W){return this.constrain("maxLength",W)}moreThanLength(W){return this.constrain("minLength",x4(W))}lessThanLength(W){return this.constrain("maxLength",x4(W))}exactlyLength(W){return this.constrain("exactLength",W)}atOrAfter(W){return this.constrain("after",W)}atOrBefore(W){return this.constrain("before",W)}laterThan(W){return this.constrain("after",x4(W))}earlierThan(W){return this.constrain("before",x4(W))}}var VA="Expected a non-empty brand name after #",x4=(W)=>typeof W==="object"&&!(W instanceof Date)?{...W,exclusive:!0}:{rule:W,exclusive:!0},n6=(W,$)=>d($,"root")?d(W,"root")?W.extends($):$.allows(W):d(W,"root")?W.hasUnit($):$===W,R_=(W)=>{if(W.hasKind("morph"))return null;if(W.hasKind("intersection"))return W.inner.structure??(W.basis?.domain==="object"?W.$.bindReference(N.intrinsic.emptyStructure):null);if(W.isBasis()&&W.domain==="object")return W.$.bindReference(N.intrinsic.emptyStructure);return null},MA=(W)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
107
+ ${W}`,N_=(W,$)=>`${W} operand must be an object (was ${$})`;var dW=(W,$)=>Y0(rY(W),(X,Y)=>[Y,$]);var OA=(W)=>typeof W==="string"?{reference:W}:W,Z_=(W)=>W instanceof b?N.intrinsic.never.internal:W,KA=J0({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(W)=>W.startsWith("$")?W:`$ark.${W}`},resolve:{}},normalize:OA,defaults:{description:(W)=>W.reference},intersections:{alias:(W,$,X)=>X.$.lazilyResolve(()=>Z_(b0(W.resolution,$.resolution,X)),`${W.reference}${X.pipe?"=>":"&"}${$.reference}`),...dW("alias",(W,$,X)=>{if($.isUnknown())return W;if($.isNever())return $;if($.isBasis()&&!$.overlaps(N.intrinsic.object))return b.init("assignability",N.intrinsic.object,$);return X.$.lazilyResolve(()=>Z_(b0(W.resolution,$,X)),`${W.reference}${X.pipe?"=>":"&"}${$.id}`)})}});class S_ extends UW{expression=this.reference;structure=void 0;get resolution(){let W=this._resolve();return x1[this.id]=W}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let W=this.reference,$=x1[W],X=[];while(d($,"context")){if(X.includes($.id))return E(AA($.id,X));X.push($.id),$=x1[$.id]}if(!d($,"root"))return K0(`Unexpected resolution for reference ${this.reference}
108
108
  Seen: [${X.join("->")}]
109
- Resolution: ${Y0($)}`);return $}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let W=this.reference.slice(1),$=this.$.resolutions[W];if(typeof $==="string")return $;if(d($,"root"))return $.id;return K0(`Unexpected resolution for reference ${this.reference}: ${Y0($)}`)}get defaultShortDescription(){return p1.object}innerToJsonSchema(W){return this.resolution.toJsonSchemaRecurse(W)}traverseAllows=(W,$)=>{let X=$.seen[this.reference];if(X?.includes(W))return!0;return $.seen[this.reference]=D0(X,W),this.resolution.traverseAllows(W,$)};traverseApply=(W,$)=>{let X=$.seen[this.reference];if(X?.includes(W))return;$.seen[this.reference]=D0(X,W),this.resolution.traverseApply(W,$)};compile(W){let $=this.resolutionId;W.if(`ctx.seen.${$} && ctx.seen.${$}.includes(data)`,()=>W.return(!0)),W.if(`!ctx.seen.${$}`,()=>W.line(`ctx.seen.${$} = []`)),W.line(`ctx.seen.${$}.push(data)`),W.return(W.invoke($))}}var OA=(W,$)=>`Alias '${W}' has a shallow resolution cycle: ${[...$,W].join("->")}`,i6={implementation:VA,Node:NU};class q8 extends wW{traverseApply=(W,$)=>{if(!this.traverseAllows(W,$))$.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return m2(this.errorContext)}compile(W){if(W.traversalKind==="Allows")W.return(this.compiledCondition);else W.if(this.compiledNegation,()=>W.line(`${W.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var KA=J0({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(W)=>typeof W==="string"?{domain:W}:L$(W,"numberAllowsNaN")&&W.domain!=="number"?A(X9.writeBadAllowNanMessage(W.domain)):W,applyConfig:(W,$)=>W.numberAllowsNaN===void 0&&W.domain==="number"&&$.numberAllowsNaN?{...W,numberAllowsNaN:!0}:W,defaults:{description:(W)=>p1[W.domain],actual:(W)=>Number.isNaN(W)?"NaN":p1[z1(W)]},intersections:{domain:(W,$)=>W.domain==="number"&&$.domain==="number"?W.numberAllowsNaN?$:W:P.init("domain",W,$)}});class ZU extends q8{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(W)=>typeof W==="number"&&!Number.isNaN(W):(W)=>z1(W)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return p1[this.domain]}innerToJsonSchema(W){if(this.domain==="bigint"||this.domain==="symbol")return W.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var X9={implementation:KA,Node:ZU,writeBadAllowNanMessage:(W)=>`numberAllowsNaN may only be specified with domain "number" (was ${W})`};var AA=J0({kind:"intersection",hasAssociatedError:!0,normalize:(W)=>{if(x0(W))return W;let{structure:$,...X}=W,Y=!!$,J=$??{},G=X0(X,(H,Q)=>{if(F1(H,oT)){if(Y)A(`Flattened structure key ${H} cannot be specified alongside a root 'structure' key.`);return J[H]=Q,[]}return[H,Q]});if(d(J,"constraint")||!cW(J))G.structure=J;return G},finalizeInnerJson:({structure:W,...$})=>m1(W,"object")?{...W,...$}:$,keys:{domain:{child:!0,parse:(W,$)=>$.$.node("domain",W)},proto:{child:!0,parse:(W,$)=>$.$.node("proto",W)},structure:{child:!0,parse:(W,$)=>$.$.node("structure",W),serialize:(W)=>{if(!W.sequence?.minLength)return W.collapsibleJson;let{sequence:$,...X}=W.collapsibleJson,{minVariadicLength:Y,...J}=$,G=J.variadic&&Object.keys(J).length===1?J.variadic:J;return{...X,sequence:G}}},divisor:{child:!0,parse:N1("divisor")},max:{child:!0,parse:N1("max")},min:{child:!0,parse:N1("min")},maxLength:{child:!0,parse:N1("maxLength")},minLength:{child:!0,parse:N1("minLength")},exactLength:{child:!0,parse:N1("exactLength")},before:{child:!0,parse:N1("before")},after:{child:!0,parse:N1("after")},pattern:{child:!0,parse:N1("pattern")},predicate:{child:!0,parse:N1("predicate")}},reduce:(W,$)=>SU({},W,{$,invert:!1,pipe:!1}),defaults:{description:(W)=>{if(W.children.length===0)return"unknown";if(W.structure)return W.structure.description;let $=[];if(W.basis&&!W.refinements.some((X)=>X.impl.obviatesBasisDescription))$.push(W.basis.description);if(W.refinements.length){let X=W.refinements.toSorted((Y,J)=>Y.kind==="min"&&J.kind==="max"?-1:0).map((Y)=>Y.description);$.push(...X)}if(W.inner.predicate)$.push(...W.inner.predicate.map((X)=>X.description));return $.join(" and ")},expected:(W)=>` \u25E6 ${W.errors.map(($)=>$.expected).join(`
109
+ Resolution: ${G0($)}`);return $}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let W=this.reference.slice(1),$=this.$.resolutions[W];if(typeof $==="string")return $;if(d($,"root"))return $.id;return K0(`Unexpected resolution for reference ${this.reference}: ${G0($)}`)}get defaultShortDescription(){return u1.object}innerToJsonSchema(W){return this.resolution.toJsonSchemaRecurse(W)}traverseAllows=(W,$)=>{let X=$.seen[this.reference];if(X?.includes(W))return!0;return $.seen[this.reference]=D0(X,W),this.resolution.traverseAllows(W,$)};traverseApply=(W,$)=>{let X=$.seen[this.reference];if(X?.includes(W))return;$.seen[this.reference]=D0(X,W),this.resolution.traverseApply(W,$)};compile(W){let $=this.resolutionId;W.if(`ctx.seen.${$} && ctx.seen.${$}.includes(data)`,()=>W.return(!0)),W.if(`!ctx.seen.${$}`,()=>W.line(`ctx.seen.${$} = []`)),W.line(`ctx.seen.${$}.push(data)`),W.return(W.invoke($))}}var AA=(W,$)=>`Alias '${W}' has a shallow resolution cycle: ${[...$,W].join("->")}`,r6={implementation:KA,Node:S_};class j8 extends UW{traverseApply=(W,$)=>{if(!this.traverseAllows(W,$))$.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return c2(this.errorContext)}compile(W){if(W.traversalKind==="Allows")W.return(this.compiledCondition);else W.if(this.compiledNegation,()=>W.line(`${W.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var EA=J0({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(W)=>typeof W==="string"?{domain:W}:R4(W,"numberAllowsNaN")&&W.domain!=="number"?E(X9.writeBadAllowNanMessage(W.domain)):W,applyConfig:(W,$)=>W.numberAllowsNaN===void 0&&W.domain==="number"&&$.numberAllowsNaN?{...W,numberAllowsNaN:!0}:W,defaults:{description:(W)=>u1[W.domain],actual:(W)=>Number.isNaN(W)?"NaN":u1[z1(W)]},intersections:{domain:(W,$)=>W.domain==="number"&&$.domain==="number"?W.numberAllowsNaN?$:W:b.init("domain",W,$)}});class q_ extends j8{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(W)=>typeof W==="number"&&!Number.isNaN(W):(W)=>z1(W)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return u1[this.domain]}innerToJsonSchema(W){if(this.domain==="bigint"||this.domain==="symbol")return W.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var X9={implementation:EA,Node:q_,writeBadAllowNanMessage:(W)=>`numberAllowsNaN may only be specified with domain "number" (was ${W})`};var LA=J0({kind:"intersection",hasAssociatedError:!0,normalize:(W)=>{if(x0(W))return W;let{structure:$,...X}=W,Y=!!$,G=$??{},J=Y0(X,(H,Q)=>{if(T1(H,nF)){if(Y)E(`Flattened structure key ${H} cannot be specified alongside a root 'structure' key.`);return G[H]=Q,[]}return[H,Q]});if(d(G,"constraint")||!cW(G))J.structure=G;return J},finalizeInnerJson:({structure:W,...$})=>p1(W,"object")?{...W,...$}:$,keys:{domain:{child:!0,parse:(W,$)=>$.$.node("domain",W)},proto:{child:!0,parse:(W,$)=>$.$.node("proto",W)},structure:{child:!0,parse:(W,$)=>$.$.node("structure",W),serialize:(W)=>{if(!W.sequence?.minLength)return W.collapsibleJson;let{sequence:$,...X}=W.collapsibleJson,{minVariadicLength:Y,...G}=$,J=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:J}}},divisor:{child:!0,parse:N1("divisor")},max:{child:!0,parse:N1("max")},min:{child:!0,parse:N1("min")},maxLength:{child:!0,parse:N1("maxLength")},minLength:{child:!0,parse:N1("minLength")},exactLength:{child:!0,parse:N1("exactLength")},before:{child:!0,parse:N1("before")},after:{child:!0,parse:N1("after")},pattern:{child:!0,parse:N1("pattern")},predicate:{child:!0,parse:N1("predicate")}},reduce:(W,$)=>C_({},W,{$,invert:!1,pipe:!1}),defaults:{description:(W)=>{if(W.children.length===0)return"unknown";if(W.structure)return W.structure.description;let $=[];if(W.basis&&!W.refinements.some((X)=>X.impl.obviatesBasisDescription))$.push(W.basis.description);if(W.refinements.length){let X=W.refinements.toSorted((Y,G)=>Y.kind==="min"&&G.kind==="max"?-1:0).map((Y)=>Y.description);$.push(...X)}if(W.inner.predicate)$.push(...W.inner.predicate.map((X)=>X.description));return $.join(" and ")},expected:(W)=>` \u25E6 ${W.errors.map(($)=>$.expected).join(`
110
110
  \u25E6 `)}`,problem:(W)=>`(${W.actual}) must be...
111
- ${W.expected}`},intersections:{intersection:(W,$,X)=>SU(W.inner,$.inner,X),...dW("intersection",(W,$,X)=>{if(W.children.length===0)return $;let{domain:Y,proto:J,...G}=W.inner,H=J??Y,Q=H?v0(H,$,X):$;return Q instanceof P?Q:W?.basis?.equals(Q)?W:W.$.node("intersection",{...G,[Q.kind]:Q},{prereduced:!0})})}});class qU extends wW{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((W)=>W.isRefinement());structure=this.inner.structure;expression=EA(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(W){return this.children.reduce(($,X)=>X.isBasis()?X.toJsonSchemaRecurse(W):X.reduceJsonSchema($,W),{})}traverseAllows=(W,$)=>this.children.every((X)=>X.traverseAllows(W,$));traverseApply=(W,$)=>{let X=$.currentErrorCount;if(this.basis){if(this.basis.traverseApply(W,$),$.currentErrorCount>X)return}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)if(this.refinements[Y].traverseApply(W,$),$.failFast&&$.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(W,$),$.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(W,$),$.currentErrorCount>X)return}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)if(this.inner.predicate[Y].traverseApply(W,$),$.failFast&&$.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(W,$)}};compile(W){if(W.traversalKind==="Allows"){for(let $ of this.children)W.check($);W.return(!0);return}if(W.initializeErrorCount(),this.basis){if(W.check(this.basis),this.children.length>1)W.returnIfFail()}if(this.refinements.length){for(let $=0;$<this.refinements.length-1;$++)W.check(this.refinements[$]),W.returnIfFailFast();if(W.check(this.refinements.at(-1)),this.structure||this.inner.predicate)W.returnIfFail()}if(this.structure){if(W.check(this.structure),this.inner.predicate)W.returnIfFail()}if(this.inner.predicate){for(let $=0;$<this.inner.predicate.length-1;$++)W.check(this.inner.predicate[$]),W.returnIfFail();W.check(this.inner.predicate.at(-1))}}}var w7={implementation:AA,Node:qU},EA=(W)=>{let $=W.structure?.expression||`${W.basis&&!W.refinements.some((X)=>X.impl.obviatesBasisExpression)?W.basis.nestableExpression+" ":""}${W.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if($==="Array == 0")$="[]";return $},SU=(W,$,X)=>{let Y={},J=W.proto??W.domain,G=$.proto??$.domain,H=J?G?v0(J,G,X):J:G;if(H instanceof P)return H;if(H)Y[H.kind]=H;return C$({kind:"intersection",baseInner:Y,l:k$(W),r:k$($),roots:[],ctx:X})};var LA=J0({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(W,$)=>$.$.parseSchema(W)},morphs:{parse:b2,serialize:(W)=>W.map(($)=>d($,"root")?$.json:d0($))},declaredIn:{child:!1,serialize:(W)=>W.json},declaredOut:{child:!1,serialize:(W)=>W.json}},normalize:(W)=>W,defaults:{description:(W)=>`a morph from ${W.in.description} to ${W.out?.description??"unknown"}`},intersections:{morph:(W,$,X)=>{if(!W.hasEqualMorphs($))return A(BA(W.expression,$.expression));let Y=v0(W.in,$.in,X);if(Y instanceof P)return Y;let J={morphs:W.morphs};if(W.declaredIn||$.declaredIn){let G=v0(W.in,$.in,X);if(G instanceof P)return G.throw();else J.declaredIn=G}if(W.declaredOut||$.declaredOut){let G=v0(W.out,$.out,X);if(G instanceof P)return G.throw();else J.declaredOut=G}return Y.distribute((G)=>X.$.node("morph",{...J,in:G}),X.$.parseSchema)},...dW("morph",(W,$,X)=>{let Y=W.inner.in?v0(W.inner.in,$,X):$;return Y instanceof P?Y:Y.equals(W.inner.in)?W:X.$.node("morph",{...W.inner,in:Y})})}});class CU extends wW{serializedMorphs=this.morphs.map(d0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=d(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??N.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(W){return this.$.node("morph",{...this.inner,declaredIn:W})}declareOut(W){return this.$.node("morph",{...this.inner,declaredOut:W})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(W){return W.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(W),out:this.introspectableOut?.toJsonSchemaRecurse(W)??null})}compile(W){if(W.traversalKind==="Allows"){if(!this.introspectableIn)return;W.return(W.invoke(this.introspectableIn));return}if(this.introspectableIn)W.line(W.invoke(this.introspectableIn));W.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(W,$)=>!this.introspectableIn||this.introspectableIn.traverseAllows(W,$);traverseApply=(W,$)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(W,$);$.queueMorphs(this.morphs)};hasEqualMorphs(W){return z2(this.morphs,W.morphs,{isEqual:($,X)=>$===X||d($,"root")&&d(X,"root")&&$.equals(X)})}}var _7={implementation:LA,Node:CU},BA=(W,$)=>`The intersection of distinct morphs at a single path is indeterminate:
111
+ ${W.expected}`},intersections:{intersection:(W,$,X)=>C_(W.inner,$.inner,X),...dW("intersection",(W,$,X)=>{if(W.children.length===0)return $;let{domain:Y,proto:G,...J}=W.inner,H=G??Y,Q=H?b0(H,$,X):$;return Q instanceof b?Q:W?.basis?.equals(Q)?W:W.$.node("intersection",{...J,[Q.kind]:Q},{prereduced:!0})})}});class k_ extends UW{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((W)=>W.isRefinement());structure=this.inner.structure;expression=BA(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(W){return this.children.reduce(($,X)=>X.isBasis()?X.toJsonSchemaRecurse(W):X.reduceJsonSchema($,W),{})}traverseAllows=(W,$)=>this.children.every((X)=>X.traverseAllows(W,$));traverseApply=(W,$)=>{let X=$.currentErrorCount;if(this.basis){if(this.basis.traverseApply(W,$),$.currentErrorCount>X)return}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)if(this.refinements[Y].traverseApply(W,$),$.failFast&&$.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(W,$),$.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(W,$),$.currentErrorCount>X)return}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)if(this.inner.predicate[Y].traverseApply(W,$),$.failFast&&$.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(W,$)}};compile(W){if(W.traversalKind==="Allows"){for(let $ of this.children)W.check($);W.return(!0);return}if(W.initializeErrorCount(),this.basis){if(W.check(this.basis),this.children.length>1)W.returnIfFail()}if(this.refinements.length){for(let $=0;$<this.refinements.length-1;$++)W.check(this.refinements[$]),W.returnIfFailFast();if(W.check(this.refinements.at(-1)),this.structure||this.inner.predicate)W.returnIfFail()}if(this.structure){if(W.check(this.structure),this.inner.predicate)W.returnIfFail()}if(this.inner.predicate){for(let $=0;$<this.inner.predicate.length-1;$++)W.check(this.inner.predicate[$]),W.returnIfFail();W.check(this.inner.predicate.at(-1))}}}var DG={implementation:LA,Node:k_},BA=(W)=>{let $=W.structure?.expression||`${W.basis&&!W.refinements.some((X)=>X.impl.obviatesBasisExpression)?W.basis.nestableExpression+" ":""}${W.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if($==="Array == 0")$="[]";return $},C_=(W,$,X)=>{let Y={},G=W.proto??W.domain,J=$.proto??$.domain,H=G?J?b0(G,J,X):G:J;if(H instanceof b)return H;if(H)Y[H.kind]=H;return j4({kind:"intersection",baseInner:Y,l:I4(W),r:I4($),roots:[],ctx:X})};var RA=J0({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(W,$)=>$.$.parseSchema(W)},morphs:{parse:g2,serialize:(W)=>W.map(($)=>d($,"root")?$.json:d0($))},declaredIn:{child:!1,serialize:(W)=>W.json},declaredOut:{child:!1,serialize:(W)=>W.json}},normalize:(W)=>W,defaults:{description:(W)=>`a morph from ${W.in.description} to ${W.out?.description??"unknown"}`},intersections:{morph:(W,$,X)=>{if(!W.hasEqualMorphs($))return E(NA(W.expression,$.expression));let Y=b0(W.in,$.in,X);if(Y instanceof b)return Y;let G={morphs:W.morphs};if(W.declaredIn||$.declaredIn){let J=b0(W.in,$.in,X);if(J instanceof b)return J.throw();else G.declaredIn=J}if(W.declaredOut||$.declaredOut){let J=b0(W.out,$.out,X);if(J instanceof b)return J.throw();else G.declaredOut=J}return Y.distribute((J)=>X.$.node("morph",{...G,in:J}),X.$.parseSchema)},...dW("morph",(W,$,X)=>{let Y=W.inner.in?b0(W.inner.in,$,X):$;return Y instanceof b?Y:Y.equals(W.inner.in)?W:X.$.node("morph",{...W.inner,in:Y})})}});class j_ extends UW{serializedMorphs=this.morphs.map(d0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=d(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??N.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(W){return this.$.node("morph",{...this.inner,declaredIn:W})}declareOut(W){return this.$.node("morph",{...this.inner,declaredOut:W})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(W){return W.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(W),out:this.introspectableOut?.toJsonSchemaRecurse(W)??null})}compile(W){if(W.traversalKind==="Allows"){if(!this.introspectableIn)return;W.return(W.invoke(this.introspectableIn));return}if(this.introspectableIn)W.line(W.invoke(this.introspectableIn));W.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(W,$)=>!this.introspectableIn||this.introspectableIn.traverseAllows(W,$);traverseApply=(W,$)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(W,$);$.queueMorphs(this.morphs)};hasEqualMorphs(W){return z2(this.morphs,W.morphs,{isEqual:($,X)=>$===X||d($,"root")&&d(X,"root")&&$.equals(X)})}}var VG={implementation:RA,Node:j_},NA=(W,$)=>`The intersection of distinct morphs at a single path is indeterminate:
112
112
  Left: ${W}
113
- Right: ${$}`;var RA=J0({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(W)=>k6(W)??TW(W)},dateAllowsInvalid:{}},normalize:(W)=>{let $=typeof W==="string"?{proto:N8[W]}:typeof W==="function"?x0(W)?W:{proto:W}:typeof W.proto==="string"?{...W,proto:N8[W.proto]}:W;if(typeof $.proto!=="function")A(n6.writeInvalidSchemaMessage($.proto));if(L$($,"dateAllowsInvalid")&&$.proto!==Date)A(n6.writeBadInvalidDateMessage($.proto));return $},applyConfig:(W,$)=>{if(W.dateAllowsInvalid===void 0&&W.proto===Date&&$.dateAllowsInvalid)return{...W,dateAllowsInvalid:!0};return W},defaults:{description:(W)=>W.builtinName?RT[W.builtinName]:`an instance of ${W.proto.name}`,actual:(W)=>W instanceof Date&&W.toString()==="Invalid Date"?"an invalid Date":C6(W)},intersections:{proto:(W,$)=>W.proto===Date&&$.proto===Date?W.dateAllowsInvalid?$:W:b5(W.proto,$.proto)?W:b5($.proto,W.proto)?$:P.init("proto",W,$),domain:(W,$)=>$.domain==="object"?W:P.init("domain",N.intrinsic.object.internal,$)}});class kU extends q8{builtinName=k6(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(W)=>W instanceof Date&&W.toString()!=="Invalid Date":(W)=>W instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(W){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return W.fallback.date?.({code:"date",base:{}})??W.fallback.proto({code:"proto",base:{},proto:this.proto});default:return W.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var n6={implementation:RA,Node:kU,writeBadInvalidDateMessage:(W)=>`dateAllowsInvalid may only be specified with constructor Date (was ${W.name})`,writeInvalidSchemaMessage:(W)=>`instanceOf operand must be a function (was ${z1(W)})`};var NA=J0({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(W,$)=>{let X=[];for(let Y of W){let J=d(Y,"root")?Y.branches:$.$.parseSchema(Y).branches;for(let G of J)if(G.hasKind("morph")){let H=X.findIndex((Q)=>Q.hasKind("morph")&&Q.hasEqualMorphs(G));if(H===-1)X.push(G);else{let Q=X[H];X[H]=$.$.node("morph",{...Q.inner,in:Q.in.rawOr(G.in)})}}else X.push(G)}if(!$.def.ordered)X.sort((Y,J)=>Y.hash<J.hash?-1:1);return X}}},normalize:(W)=>k0(W)?{branches:W}:W,reduce:(W,$)=>{let X=xA(W);if(X.length===1)return X[0];if(X.length===W.branches.length)return;return $.node("union",{...W,branches:X},{prereduced:!0})},defaults:{description:(W)=>W.distribute(($)=>$.description,P$),expected:(W)=>{let $=MT(W.errors,"propString"),X=Object.entries($).map(([Y,J])=>{let G=[];for(let z of J)uW(G,z.expected);let H=P$(G),Q=J.every((z)=>z.actual===J[0].actual)?J[0].actual:Y0(J[0].data);return`${Y&&`${Y} `}must be ${H}${Q&&` (was ${Q})`}`});return P$(X)},problem:(W)=>W.expected,message:(W)=>W.problem},intersections:{union:(W,$,X)=>{if(W.isNever!==$.isNever)return P.init("presence",W,$);let Y;if(W.ordered){if($.ordered)A(bA(W.expression,$.expression));if(Y=D7($.branches,W.branches,X),Y instanceof P)Y.invert()}else Y=D7(W.branches,$.branches,X);if(Y instanceof P)return Y;return X.$.parseSchema(W.ordered||$.ordered?{branches:Y,ordered:!0}:{branches:Y})},...dW("union",(W,$,X)=>{let Y=D7(W.branches,[$],X);if(Y instanceof P)return Y;if(Y.length===1)return Y[0];return X.$.parseSchema(W.ordered?{branches:Y,ordered:!0}:{branches:Y})})}});class fU extends wW{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let W=[],$=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if($===-1)$=W.length,W.push(X);else W[$]=N.intrinsic.boolean;continue}W.push(X)}return W}unitBranches=this.branches.filter((W)=>W.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?IA(this.discriminant):null;expression=this.distribute((W)=>W.nestableExpression,PA);createBranchedOptimisticRootApply(){return(W,$)=>{let X=this.traverseOptimistic(W);if(X!==WW)return X;let Y=new qW(W,this.$.resolvedConfig);return this.traverseApply(W,Y),Y.finalize($)}}get shallowMorphs(){return this.branches.reduce((W,$)=>uW(W,$.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((W)=>W.defaultShortDescription,P$)}innerToJsonSchema(W){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let $=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(W));if($.every((X)=>Object.keys(X).length===1&&L$(X,"const")))return{enum:$.map((X)=>X.const)};return{anyOf:$}}traverseAllows=(W,$)=>this.branches.some((X)=>X.traverseAllows(W,$));traverseApply=(W,$)=>{let X=[];for(let Y=0;Y<this.branches.length;Y++){if($.pushBranch(),this.branches[Y].traverseApply(W,$),!$.hasError()){if(this.branches[Y].includesTransform)return $.queuedMorphs.push(...$.popBranch().queuedMorphs);return $.popBranch()}X.push($.popBranch().error)}$.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(W)=>{for(let $=0;$<this.branches.length;$++){let X=this.branches[$];if(X.traverseAllows(W)){if(X.contextFreeMorph)return X.contextFreeMorph(W);return W}}return WW};compile(W){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(W);let $=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")$=`typeof ${$} === "object" ? ${$} === null ? "null" : "object" : typeof ${$} === "function" ? "object" : typeof ${$}`;let X=this.discriminant.cases,Y=Object.keys(X),{optimistic:J}=W;if(W.optimistic=!1,W.block(`switch(${$})`,()=>{for(let F in X){let T=X[F],U=F==="default"?F:`case ${F}`;W.line(`${U}: return ${T===!0?J?W.data:T:J?`${W.invoke(T)} ? ${T.contextFreeMorph?`${d0(T.contextFreeMorph)}(${W.data})`:W.data} : "${WW}"`:W.invoke(T)}`)}return W}),W.traversalKind==="Allows"){W.return(J?`"${WW}"`:!1);return}let G=P$(this.discriminant.kind==="domain"?Y.map((F)=>{let T=F.slice(1,-1);return T==="function"?p1.object:p1[T]}):Y),H=this.discriminant.path.map((F)=>typeof F==="symbol"?d0(F):JSON.stringify(F)),Q=JSON.stringify(G),z=this.discriminant.kind==="domain"?`${kA}[${$}]`:`${jA}(${$})`;W.line(`ctx.errorFromNodeContext({
113
+ Right: ${$}`;var ZA=J0({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(W)=>I6(W)??_W(W)},dateAllowsInvalid:{}},normalize:(W)=>{let $=typeof W==="string"?{proto:q8[W]}:typeof W==="function"?x0(W)?W:{proto:W}:typeof W.proto==="string"?{...W,proto:q8[W.proto]}:W;if(typeof $.proto!=="function")E(t6.writeInvalidSchemaMessage($.proto));if(R4($,"dateAllowsInvalid")&&$.proto!==Date)E(t6.writeBadInvalidDateMessage($.proto));return $},applyConfig:(W,$)=>{if(W.dateAllowsInvalid===void 0&&W.proto===Date&&$.dateAllowsInvalid)return{...W,dateAllowsInvalid:!0};return W},defaults:{description:(W)=>W.builtinName?ZF[W.builtinName]:`an instance of ${W.proto.name}`,actual:(W)=>W instanceof Date&&W.toString()==="Invalid Date"?"an invalid Date":j6(W)},intersections:{proto:(W,$)=>W.proto===Date&&$.proto===Date?W.dateAllowsInvalid?$:W:h7(W.proto,$.proto)?W:h7($.proto,W.proto)?$:b.init("proto",W,$),domain:(W,$)=>$.domain==="object"?W:b.init("domain",N.intrinsic.object.internal,$)}});class I_ extends j8{builtinName=I6(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(W)=>W instanceof Date&&W.toString()!=="Invalid Date":(W)=>W instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(W){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return W.fallback.date?.({code:"date",base:{}})??W.fallback.proto({code:"proto",base:{},proto:this.proto});default:return W.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var t6={implementation:ZA,Node:I_,writeBadInvalidDateMessage:(W)=>`dateAllowsInvalid may only be specified with constructor Date (was ${W.name})`,writeInvalidSchemaMessage:(W)=>`instanceOf operand must be a function (was ${z1(W)})`};var SA=J0({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(W,$)=>{let X=[];for(let Y of W){let G=d(Y,"root")?Y.branches:$.$.parseSchema(Y).branches;for(let J of G)if(J.hasKind("morph")){let H=X.findIndex((Q)=>Q.hasKind("morph")&&Q.hasEqualMorphs(J));if(H===-1)X.push(J);else{let Q=X[H];X[H]=$.$.node("morph",{...Q.inner,in:Q.in.rawOr(J.in)})}}else X.push(J)}if(!$.def.ordered)X.sort((Y,G)=>Y.hash<G.hash?-1:1);return X}}},normalize:(W)=>k0(W)?{branches:W}:W,reduce:(W,$)=>{let X=vA(W);if(X.length===1)return X[0];if(X.length===W.branches.length)return;return $.node("union",{...W,branches:X},{prereduced:!0})},defaults:{description:(W)=>W.distribute(($)=>$.description,b4),expected:(W)=>{let $=OF(W.errors,"propString"),X=Object.entries($).map(([Y,G])=>{let J=[];for(let z of G)uW(J,z.expected);let H=b4(J),Q=G.every((z)=>z.actual===G[0].actual)?G[0].actual:G0(G[0].data);return`${Y&&`${Y} `}must be ${H}${Q&&` (was ${Q})`}`});return b4(X)},problem:(W)=>W.expected,message:(W)=>W.problem},intersections:{union:(W,$,X)=>{if(W.isNever!==$.isNever)return b.init("presence",W,$);let Y;if(W.ordered){if($.ordered)E(hA(W.expression,$.expression));if(Y=MG($.branches,W.branches,X),Y instanceof b)Y.invert()}else Y=MG(W.branches,$.branches,X);if(Y instanceof b)return Y;return X.$.parseSchema(W.ordered||$.ordered?{branches:Y,ordered:!0}:{branches:Y})},...dW("union",(W,$,X)=>{let Y=MG(W.branches,[$],X);if(Y instanceof b)return Y;if(Y.length===1)return Y[0];return X.$.parseSchema(W.ordered?{branches:Y,ordered:!0}:{branches:Y})})}});class x_ extends UW{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let W=[],$=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if($===-1)$=W.length,W.push(X);else W[$]=N.intrinsic.boolean;continue}W.push(X)}return W}unitBranches=this.branches.filter((W)=>W.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?fA(this.discriminant):null;expression=this.distribute((W)=>W.nestableExpression,bA);createBranchedOptimisticRootApply(){return(W,$)=>{let X=this.traverseOptimistic(W);if(X!==$W)return X;let Y=new CW(W,this.$.resolvedConfig);return this.traverseApply(W,Y),Y.finalize($)}}get shallowMorphs(){return this.branches.reduce((W,$)=>uW(W,$.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((W)=>W.defaultShortDescription,b4)}innerToJsonSchema(W){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let $=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(W));if($.every((X)=>Object.keys(X).length===1&&R4(X,"const")))return{enum:$.map((X)=>X.const)};return{anyOf:$}}traverseAllows=(W,$)=>this.branches.some((X)=>X.traverseAllows(W,$));traverseApply=(W,$)=>{let X=[];for(let Y=0;Y<this.branches.length;Y++){if($.pushBranch(),this.branches[Y].traverseApply(W,$),!$.hasError()){if(this.branches[Y].includesTransform)return $.queuedMorphs.push(...$.popBranch().queuedMorphs);return $.popBranch()}X.push($.popBranch().error)}$.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(W)=>{for(let $=0;$<this.branches.length;$++){let X=this.branches[$];if(X.traverseAllows(W)){if(X.contextFreeMorph)return X.contextFreeMorph(W);return W}}return $W};compile(W){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(W);let $=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")$=`typeof ${$} === "object" ? ${$} === null ? "null" : "object" : typeof ${$} === "function" ? "object" : typeof ${$}`;let X=this.discriminant.cases,Y=Object.keys(X),{optimistic:G}=W;if(W.optimistic=!1,W.block(`switch(${$})`,()=>{for(let T in X){let F=X[T],_=T==="default"?T:`case ${T}`;W.line(`${_}: return ${F===!0?G?W.data:F:G?`${W.invoke(F)} ? ${F.contextFreeMorph?`${d0(F.contextFreeMorph)}(${W.data})`:W.data} : "${$W}"`:W.invoke(F)}`)}return W}),W.traversalKind==="Allows"){W.return(G?`"${$W}"`:!1);return}let J=b4(this.discriminant.kind==="domain"?Y.map((T)=>{let F=T.slice(1,-1);return F==="function"?u1.object:u1[F]}):Y),H=this.discriminant.path.map((T)=>typeof T==="symbol"?d0(T):JSON.stringify(T)),Q=JSON.stringify(J),z=this.discriminant.kind==="domain"?`${IA}[${$}]`:`${PA}(${$})`;W.line(`ctx.errorFromNodeContext({
114
114
  code: "predicate",
115
115
  expected: ${Q},
116
116
  actual: ${z},
117
117
  relativePath: [${H}],
118
118
  meta: ${this.compiledMeta}
119
- })`)}compileIndiscriminable(W){if(W.traversalKind==="Apply"){W.const("errors","[]");for(let $ of this.branches)W.line("ctx.pushBranch()").line(W.invoke($)).if("!ctx.hasError()",()=>W.return($.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");W.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:$}=W;W.optimistic=!1;for(let X of this.branches)W.if(`${W.invoke(X)}`,()=>W.return($?X.contextFreeMorph?`${d0(X.contextFreeMorph)}(${W.data})`:W.data:!0));W.return($?`"${WW}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let J=X0(this.unitBranches,(G,H)=>[`${H.in.serializedValue}`,H.hasKind("morph")?H:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:J}}let W=[];for(let J=0;J<this.branches.length-1;J++){let G=this.branches[J];for(let H=J+1;H<this.branches.length;H++){let Q=this.branches[H],z=d1(G.in,Q.in,G.$);if(!(z instanceof P))continue;for(let F of z){if(!F.kind||F.optional)continue;let T,U;if(F.kind==="domain"){let{l:V,r:K}=F;T=`"${typeof V==="string"?V:V.domain}"`,U=`"${typeof K==="string"?K:K.domain}"`}else if(F.kind==="unit")T=F.l.serializedValue,U=F.r.serializedValue;else continue;let _=W.find((V)=>z2(V.path,F.path)&&V.kind===F.kind);if(!_)W.push({kind:F.kind,cases:{[T]:{branchIndices:[J],condition:F.l},[U]:{branchIndices:[H],condition:F.r}},path:F.path});else{if(_.cases[T])_.cases[T].branchIndices=uW(_.cases[T].branchIndices,J);else _.cases[T]??={branchIndices:[J],condition:F.l};if(_.cases[U])_.cases[U].branchIndices=uW(_.cases[U].branchIndices,H);else _.cases[U]??={branchIndices:[H],condition:F.r}}}}}let $=this.ordered?qA(W,this.branches):W;if(!$.length)return null;let X=ZA($,this),Y={};for(let J in X.best.cases){let G=SA(X,J);if(G===null){Y[J]=!0;continue}if(G.length===this.branches.length)return null;if(this.ordered)G.sort((z,F)=>z.originalIndex-F.originalIndex);let H=G.map((z)=>z.branch),Q=H.length===1?H[0]:this.$.node("union",this.ordered?{branches:H,ordered:!0}:H);Object.assign(this.referencesById,Q.referencesById),Y[J]=Q}if(X.defaultEntries.length){let J=X.defaultEntries.map((G)=>G.branch);Y.default=this.$.node("union",this.ordered?{branches:J,ordered:!0}:J,{prereduced:!0}),Object.assign(this.referencesById,Y.default.referencesById)}return Object.assign(X.location,{cases:Y})}}var ZA=(W,$)=>{let X=W.sort((G,H)=>Object.keys(H.cases).length-Object.keys(G.cases).length)[0],Y={kind:X.kind,path:X.path,optionallyChainedPropString:PU(X.path)},J=$.branches.map((G,H)=>({originalIndex:H,branch:G}));return{best:X,location:Y,defaultEntries:J,node:$}},SA=(W,$)=>{let X=W.best.cases[$],Y=CA(X.condition,W.location.path,W.node.$),J=[],G=[];for(let H=0;H<W.defaultEntries.length;H++){let Q=W.defaultEntries[H];if(X.branchIndices.includes(Q.originalIndex)){let z=jU(W.node.branches[Q.originalIndex],W.location);if(z===null)J=null;else J?.push({originalIndex:Q.originalIndex,branch:z})}else if(Q.branch.hasKind("alias")&&Y.hasKind("domain")&&Y.domain==="object")J?.push(Q);else{if(Q.branch.in.overlaps(Y)){let z=jU(Q.branch,W.location);J?.push({originalIndex:Q.originalIndex,branch:z})}G.push(Q)}}return W.defaultEntries=G,J},qA=(W,$)=>{return W.filter((Y)=>{let J=Object.values(Y.cases).map((G)=>G.branchIndices);for(let G=0;G<J.length-1;G++){let H=J[G];for(let Q=G+1;Q<J.length;Q++){let z=J[Q];for(let F of H)for(let T of z)if(F>T){if($[F].overlaps($[T]))return!1}}}return!0})},CA=(W,$,X)=>{let Y=W==="undefined"?X.node("unit",{unit:void 0}):W==="null"?X.node("unit",{unit:null}):W==="boolean"?X.units([!0,!1]):W;for(let J=$.length-1;J>=0;J--){let G=$[J];Y=X.node("intersection",typeof G==="number"?{proto:"Array",sequence:[..._T(G).map((H)=>({})),Y]}:{domain:"object",required:[{key:G,value:Y}]})}return Y},PU=(W)=>W.reduce(($,X)=>$+c5(X,!0),"data"),kA=d0(VT),jA=d0(Y0),M7={implementation:NA,Node:fU},IA=(W)=>({kind:W.kind,path:W.path.map(($)=>typeof $==="string"?$:U2($)),cases:X0(W.cases,($,X)=>[$,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),fA={delimiter:" | ",finalDelimiter:" | "},PA=(W)=>P$(W,fA),P$=(W,$)=>{let X=$?.delimiter??", ",Y=$?.finalDelimiter??" or ";if(W.length===0)return"never";if(W.length===1)return W[0];if(W.length===2&&W[0]==="false"&&W[1]==="true"||W[0]==="true"&&W[1]==="false")return"boolean";let J={},G=W.filter((Q)=>J[Q]?!1:J[Q]=!0),H=G.pop();return`${G.join(X)}${G.length?Y:""}${H}`},D7=(W,$,X)=>{let Y=$.map(()=>[]);for(let G=0;G<W.length;G++){let H={};for(let Q=0;Q<$.length;Q++){if(Y[Q]===null)continue;if(W[G].equals($[Q])){Y[Q]=null,H={};break}let z=v0(W[G],$[Q],X);if(z instanceof P)continue;if(z.equals(W[G])){Y[Q].push(W[G]),H={};break}if(z.equals($[Q]))Y[Q]=null;else H[Q]=z}for(let Q in H)Y[Q][G]=H[Q]}let J=Y.flatMap((G,H)=>G?.flatMap((Q)=>Q.branches)??$[H]);return J.length===0?P.init("union",W,$):J},xA=({branches:W,ordered:$})=>{if(W.length<2)return W;let X=W.map(()=>!0);for(let Y=0;Y<W.length;Y++)for(let J=Y+1;J<W.length&&X[Y]&&X[J];J++){if(W[Y].equals(W[J])){X[J]=!1;continue}let G=d1(W[Y].in,W[J].in,W[0].$);if(G instanceof P)continue;if(!$)vA(W[Y],W[J]);if(G.equals(W[Y].in))X[Y]=!!$;else if(G.equals(W[J].in))X[J]=!1}return W.filter((Y,J)=>X[J])},vA=(W,$)=>{if(!W.includesTransform&&!$.includesTransform)return;if(!z2(W.shallowMorphs,$.shallowMorphs))A(IU(W.expression,$.expression));if(!z2(W.flatMorphs,$.flatMorphs,{isEqual:(X,Y)=>X.propString===Y.propString&&(X.node.hasKind("morph")&&Y.node.hasKind("morph")?X.node.hasEqualMorphs(Y.node):X.node.hasKind("intersection")&&Y.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Y.node.structure?.structuralMorphRef:!1)}))A(IU(W.expression,$.expression))},jU=(W,$)=>W.transform((X,Y)=>{if(X==="domain"||X==="unit")return null;return Y},{shouldTransform:(X,Y)=>{let J=PU(Y.path);if(!$.optionallyChainedPropString.startsWith(J))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||$.kind==="unit")&&J===$.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),IU=(W,$)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
119
+ })`)}compileIndiscriminable(W){if(W.traversalKind==="Apply"){W.const("errors","[]");for(let $ of this.branches)W.line("ctx.pushBranch()").line(W.invoke($)).if("!ctx.hasError()",()=>W.return($.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");W.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:$}=W;W.optimistic=!1;for(let X of this.branches)W.if(`${W.invoke(X)}`,()=>W.return($?X.contextFreeMorph?`${d0(X.contextFreeMorph)}(${W.data})`:W.data:!0));W.return($?`"${$W}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let G=Y0(this.unitBranches,(J,H)=>[`${H.in.serializedValue}`,H.hasKind("morph")?H:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let W=[];for(let G=0;G<this.branches.length-1;G++){let J=this.branches[G];for(let H=G+1;H<this.branches.length;H++){let Q=this.branches[H],z=l1(J.in,Q.in,J.$);if(!(z instanceof b))continue;for(let T of z){if(!T.kind||T.optional)continue;let F,_;if(T.kind==="domain"){let{l:O,r:M}=T;F=`"${typeof O==="string"?O:O.domain}"`,_=`"${typeof M==="string"?M:M.domain}"`}else if(T.kind==="unit")F=T.l.serializedValue,_=T.r.serializedValue;else continue;let w=W.find((O)=>z2(O.path,T.path)&&O.kind===T.kind);if(!w)W.push({kind:T.kind,cases:{[F]:{branchIndices:[G],condition:T.l},[_]:{branchIndices:[H],condition:T.r}},path:T.path});else{if(w.cases[F])w.cases[F].branchIndices=uW(w.cases[F].branchIndices,G);else w.cases[F]??={branchIndices:[G],condition:T.l};if(w.cases[_])w.cases[_].branchIndices=uW(w.cases[_].branchIndices,H);else w.cases[_]??={branchIndices:[H],condition:T.r}}}}}let $=this.ordered?kA(W,this.branches):W;if(!$.length)return null;let X=qA($,this),Y={};for(let G in X.best.cases){let J=CA(X,G);if(J===null){Y[G]=!0;continue}if(J.length===this.branches.length)return null;if(this.ordered)J.sort((z,T)=>z.originalIndex-T.originalIndex);let H=J.map((z)=>z.branch),Q=H.length===1?H[0]:this.$.node("union",this.ordered?{branches:H,ordered:!0}:H);Object.assign(this.referencesById,Q.referencesById),Y[G]=Q}if(X.defaultEntries.length){let G=X.defaultEntries.map((J)=>J.branch);Y.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,Y.default.referencesById)}return Object.assign(X.location,{cases:Y})}}var qA=(W,$)=>{let X=W.sort((J,H)=>Object.keys(H.cases).length-Object.keys(J.cases).length)[0],Y={kind:X.kind,path:X.path,optionallyChainedPropString:b_(X.path)},G=$.branches.map((J,H)=>({originalIndex:H,branch:J}));return{best:X,location:Y,defaultEntries:G,node:$}},CA=(W,$)=>{let X=W.best.cases[$],Y=jA(X.condition,W.location.path,W.node.$),G=[],J=[];for(let H=0;H<W.defaultEntries.length;H++){let Q=W.defaultEntries[H];if(X.branchIndices.includes(Q.originalIndex)){let z=P_(W.node.branches[Q.originalIndex],W.location);if(z===null)G=null;else G?.push({originalIndex:Q.originalIndex,branch:z})}else if(Q.branch.hasKind("alias")&&Y.hasKind("domain")&&Y.domain==="object")G?.push(Q);else{if(Q.branch.in.overlaps(Y)){let z=P_(Q.branch,W.location);G?.push({originalIndex:Q.originalIndex,branch:z})}J.push(Q)}}return W.defaultEntries=J,G},kA=(W,$)=>{return W.filter((Y)=>{let G=Object.values(Y.cases).map((J)=>J.branchIndices);for(let J=0;J<G.length-1;J++){let H=G[J];for(let Q=J+1;Q<G.length;Q++){let z=G[Q];for(let T of H)for(let F of z)if(T>F){if($[T].overlaps($[F]))return!1}}}return!0})},jA=(W,$,X)=>{let Y=W==="undefined"?X.node("unit",{unit:void 0}):W==="null"?X.node("unit",{unit:null}):W==="boolean"?X.units([!0,!1]):W;for(let G=$.length-1;G>=0;G--){let J=$[G];Y=X.node("intersection",typeof J==="number"?{proto:"Array",sequence:[...VF(J).map((H)=>({})),Y]}:{domain:"object",required:[{key:J,value:Y}]})}return Y},b_=(W)=>W.reduce(($,X)=>$+l7(X,!0),"data"),IA=d0(KF),PA=d0(G0),OG={implementation:SA,Node:x_},fA=(W)=>({kind:W.kind,path:W.path.map(($)=>typeof $==="string"?$:_2($)),cases:Y0(W.cases,($,X)=>[$,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),xA={delimiter:" | ",finalDelimiter:" | "},bA=(W)=>b4(W,xA),b4=(W,$)=>{let X=$?.delimiter??", ",Y=$?.finalDelimiter??" or ";if(W.length===0)return"never";if(W.length===1)return W[0];if(W.length===2&&W[0]==="false"&&W[1]==="true"||W[0]==="true"&&W[1]==="false")return"boolean";let G={},J=W.filter((Q)=>G[Q]?!1:G[Q]=!0),H=J.pop();return`${J.join(X)}${J.length?Y:""}${H}`},MG=(W,$,X)=>{let Y=$.map(()=>[]);for(let J=0;J<W.length;J++){let H={};for(let Q=0;Q<$.length;Q++){if(Y[Q]===null)continue;if(W[J].equals($[Q])){Y[Q]=null,H={};break}let z=b0(W[J],$[Q],X);if(z instanceof b)continue;if(z.equals(W[J])){Y[Q].push(W[J]),H={};break}if(z.equals($[Q]))Y[Q]=null;else H[Q]=z}for(let Q in H)Y[Q][J]=H[Q]}let G=Y.flatMap((J,H)=>J?.flatMap((Q)=>Q.branches)??$[H]);return G.length===0?b.init("union",W,$):G},vA=({branches:W,ordered:$})=>{if(W.length<2)return W;let X=W.map(()=>!0);for(let Y=0;Y<W.length;Y++)for(let G=Y+1;G<W.length&&X[Y]&&X[G];G++){if(W[Y].equals(W[G])){X[G]=!1;continue}let J=l1(W[Y].in,W[G].in,W[0].$);if(J instanceof b)continue;if(!$)yA(W[Y],W[G]);if(J.equals(W[Y].in))X[Y]=!!$;else if(J.equals(W[G].in))X[G]=!1}return W.filter((Y,G)=>X[G])},yA=(W,$)=>{if(!W.includesTransform&&!$.includesTransform)return;if(!z2(W.shallowMorphs,$.shallowMorphs))E(f_(W.expression,$.expression));if(!z2(W.flatMorphs,$.flatMorphs,{isEqual:(X,Y)=>X.propString===Y.propString&&(X.node.hasKind("morph")&&Y.node.hasKind("morph")?X.node.hasEqualMorphs(Y.node):X.node.hasKind("intersection")&&Y.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Y.node.structure?.structuralMorphRef:!1)}))E(f_(W.expression,$.expression))},P_=(W,$)=>W.transform((X,Y)=>{if(X==="domain"||X==="unit")return null;return Y},{shouldTransform:(X,Y)=>{let G=b_(Y.path);if(!$.optionallyChainedPropString.startsWith(G))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||$.kind==="unit")&&G===$.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),f_=(W,$)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
120
120
  Left: ${W}
121
- Right: ${$}`,bA=(W,$)=>`The intersection of two ordered unions is indeterminate:
121
+ Right: ${$}`,hA=(W,$)=>`The intersection of two ordered unions is indeterminate:
122
122
  Left: ${W}
123
- Right: ${$}`;var yA=J0({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(W)=>W instanceof Date?W.toISOString():TW(W)}},normalize:(W)=>W,defaults:{description:(W)=>Y0(W.unit),problem:({expected:W,actual:$})=>`${W===$?`must be reference equal to ${W} (serialized to the same value)`:`must be ${W} (was ${$})`}`},intersections:{unit:(W,$)=>P.init("unit",W,$),...dW("unit",(W,$)=>{if($.allows(W.unit))return W;let X=$.hasKind("intersection")?$.basis:$;if(X){let Y=X.hasKind("domain")?X:N.intrinsic.object;if(W.domain!==Y.domain){let J=W.domain==="undefined"||W.domain==="null"||W.domain==="boolean"?W.domain:N.intrinsic[W.domain];return P.init("domain",J,Y)}}return P.init("assignability",W,$.hasKind("intersection")?$.children.find((Y)=>!Y.allows(W.unit)):$)})}});class vU extends q8{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=xU(this.unit,this.serializedValue);compiledNegation=xU(this.unit,this.serializedValue,"negated");expression=Y0(this.unit);domain=z1(this.unit);get defaultShortDescription(){return this.domain==="object"?p1.object:this.description}innerToJsonSchema(W){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:W.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(W)=>W instanceof Date&&W.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(W)=>Number.isNaN(W):(W)=>W===this.unit}var V7={implementation:yA,Node:vU},xU=(W,$,X)=>{if(W instanceof Date){let Y=`data instanceof Date && data.toISOString() === ${$}`;return X?`!(${Y})`:Y}if(Number.isNaN(W))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${$}`};var hA=J0({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(W,$)=>{let X=$.$.parseSchema(W);if(!X.extends(N.intrinsic.key))return A(mA(X.expression));let Y=X.branches.filter((J)=>J.hasKind("unit"));if(Y.length)return A(gA(Y.map((J)=>Y0(J.unit))));return X}},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`[${W.signature.expression}]: ${W.value.description}`},intersections:{index:(W,$,X)=>{if(W.signature.equals($.signature)){let Y=v0(W.value,$.value,X),J=Y instanceof P?N.intrinsic.never.internal:Y;return X.$.node("index",{signature:W.signature,value:J})}if(W.signature.extends($.signature)&&W.value.subsumes($.value))return $;if($.signature.extends(W.signature)&&$.value.subsumes(W.value))return W;return null}}});class bU extends UW{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=D0(this.value.flatRefs.map((W)=>CW([this.signature,...W.path],W.node)),CW([this.signature],this.value));traverseAllows=(W,$)=>R8(W).every((X)=>{if(this.signature.traverseAllows(X[0],$))return c1(X[0],()=>this.value.traverseAllows(X[1],$),$);return!0});traverseApply=(W,$)=>{for(let X of R8(W))if(this.signature.traverseAllows(X[0],$))c1(X[0],()=>this.value.traverseApply(X[1],$),$)};_transform(W,$){$.path.push(this.signature);let X=super._transform(W,$);return $.path.pop(),X}compile(){}}var O7={implementation:hA,Node:bU},gA=(W)=>`Index keys ${W.join(", ")} should be specified as named props.`,mA=(W)=>`Indexed key definition '${W}' must be a string or symbol`;var pA=J0({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`${W.compiledKey}: ${W.value.description}`,expected:(W)=>W.missingValueDescription,actual:()=>"missing"},intersections:{required:u6,optional:u6}});class yU extends c6{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=m2(this.errorContext)}var K7={implementation:pA,Node:yU};var uA=J0({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}},optionals:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}},defaultables:{child:(W)=>W.map(($)=>$[0]),parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>{let Y=$.$.parseSchema(X[0]);return l6(Y,X[1],null),[Y,X[1]]})},serialize:(W)=>W.map(($)=>[$[0].collapsibleJson,TW($[1])])},variadic:{child:!0,parse:(W,$)=>$.$.parseSchema(W,$)},minVariadicLength:{parse:(W)=>W===0?void 0:W},postfix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}}},normalize:(W)=>{if(typeof W==="string")return{variadic:W};if("variadic"in W||"prefix"in W||"defaultables"in W||"optionals"in W||"postfix"in W||"minVariadicLength"in W){if(W.postfix?.length){if(!W.variadic)return A(oA);if(W.optionals?.length||W.defaultables?.length)return A(E7)}if(W.minVariadicLength&&!W.variadic)return A("minVariadicLength may not be specified without a variadic element");return W}return{variadic:W}},reduce:(W,$)=>{let X=W.minVariadicLength??0,Y=W.prefix?.slice()??[],J=W.defaultables?.slice()??[],G=W.optionals?.slice()??[],H=W.postfix?.slice()??[];if(W.variadic){while(G.at(-1)?.equals(W.variadic))G.pop();if(G.length===0&&J.length===0)while(Y.at(-1)?.equals(W.variadic))Y.pop(),X++;while(H[0]?.equals(W.variadic))H.shift(),X++}else if(G.length===0&&J.length===0)Y.push(...H.splice(0));if(X!==W.minVariadicLength||W.prefix&&W.prefix.length!==Y.length)return $.node("sequence",{...W,prefix:Y,defaultables:J,optionals:G,postfix:H,minVariadicLength:X},{prereduced:!0})},defaults:{description:(W)=>{if(W.isVariadicOnly)return`${W.variadic.nestableExpression}[]`;return`[${W.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${Y0(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(W,$,X)=>{let Y=r6({l:W.tuple,r:$.tuple,disjoint:new P,result:[],fixedVariants:[],ctx:X}),J=Y.disjoint.length===0?[Y,...Y.fixedVariants]:Y.fixedVariants;return J.length===0?Y.disjoint:J.length===1?X.$.node("sequence",hU(J[0].result)):X.$.node("union",J.map((G)=>({proto:Array,sequence:hU(G.result)})))}}});class gU extends UW{impliedBasis=N.intrinsic.Array.internal;tuple=lA(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((W)=>{if(W.kind==="defaultables"||W.kind==="optionals")return this.defaultablesAndOptionals.push(W.node),!0;return W.kind==="prefix"});variadicOrPostfix=Q2(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return i5(this.flatRefs,this.prevariadic.flatMap((W,$)=>D0(W.node.flatRefs.map((X)=>CW([`${$}`,...X.path],X.node)),CW([`${$}`],W.node)))),i5(this.flatRefs,this.variadicOrPostfix.flatMap((W)=>D0(W.flatRefs.map(($)=>CW([N.intrinsic.nonNegativeIntegerString.internal,...$.path],$.node)),CW([N.intrinsic.nonNegativeIntegerString.internal],W)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=dA(this);defaultValueMorphsReference=this.defaultValueMorphs.length?d0(this.defaultValueMorphs):void 0;elementAtIndex(W,$){if($<this.prevariadic.length)return this.tuple[$];let X=W.length-this.postfixLength;if($>=X)return{kind:"postfix",node:this.postfix[$-X]};return{kind:"variadic",node:this.variadic??K0(`Unexpected attempt to access index ${$} on ${this}`)}}traverseAllows=(W,$)=>{for(let X=0;X<W.length;X++)if(!this.elementAtIndex(W,X).node.traverseAllows(W[X],$))return!1;return!0};traverseApply=(W,$)=>{let X=0;for(;X<W.length;X++)c1(X,()=>this.elementAtIndex(W,X).node.traverseApply(W[X],$),$)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(W){if(this.prefix)for(let[$,X]of this.prefix.entries())W.traverseKey(`${$}`,`data[${$}]`,X);for(let[$,X]of this.defaultablesAndOptionals.entries()){let Y=`${$+this.prefixLength}`;W.if(`${Y} >= ${W.data}.length`,()=>W.traversalKind==="Allows"?W.return(!0):W.return()),W.traverseKey(Y,`data[${Y}]`,X)}if(this.variadic){if(this.postfix)W.const("firstPostfixIndex",`${W.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(W.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>W.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[$,X]of this.postfix.entries()){let Y=`firstPostfixIndex + ${$}`;W.traverseKey(Y,`data[${Y}]`,X)}}if(W.traversalKind==="Allows")W.return(!0)}_transform(W,$){$.path.push(N.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(W,$);return $.path.pop(),X}expression=this.description;reduceJsonSchema(W,$){if(this.prevariadic.length)W.prefixItems=this.prevariadic.map((X)=>{let Y=X.node.toJsonSchemaRecurse($);if(X.kind==="defaultables"){let J=typeof X.default==="function"?X.default():X.default;Y.default=N.intrinsic.jsonData.allows(J)?J:$.fallback.defaultValue({code:"defaultValue",base:Y,value:J})}return Y});if(this.minLength)W.minItems=this.minLength;if(this.variadic){let X=Object.assign(W,{items:this.variadic.toJsonSchemaRecurse($)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let Y=this.postfix.map((J)=>J.toJsonSchemaRecurse($));W=$.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:Y})}}else W.items=!1,delete W.maxItems;return W}}var cA={},dA=(W)=>{if(!W.defaultables)return[];let $=[],X="[",Y=W.prefixLength+W.defaultablesLength-1;for(let J=W.prefixLength;J<=Y;J++){let[G,H]=W.defaultables[J-W.prefixLength];$.push(U7(J,G,H)),X+=`${J}: ${G.id} = ${TW(H)}, `}return X+="]",cA[X]??=$},A7={implementation:uA,Node:gU},lA=(W)=>{let $=[];if(W.prefix)for(let X of W.prefix)$.push({kind:"prefix",node:X});if(W.defaultables)for(let[X,Y]of W.defaultables)$.push({kind:"defaultables",node:X,default:Y});if(W.optionals)for(let X of W.optionals)$.push({kind:"optionals",node:X});if(W.variadic)$.push({kind:"variadic",node:W.variadic});if(W.postfix)for(let X of W.postfix)$.push({kind:"postfix",node:X});return $},hU=(W)=>W.reduce(($,X)=>{if(X.kind==="variadic")$.variadic=X.node;else if(X.kind==="defaultables")$.defaultables=D0($.defaultables,[[X.node,X.default]]);else $[X.kind]=D0($[X.kind],X.node);return $},{}),E7="A postfix required element cannot follow an optional or defaultable element",oA="A postfix element requires a variadic element",r6=(W)=>{let[$,...X]=W.l,[Y,...J]=W.r;if(!$||!Y)return W;let G=X.at(-1)?.kind==="postfix",H=J.at(-1)?.kind==="postfix",Q=$.kind==="prefix"||Y.kind==="prefix"?"prefix":$.kind==="postfix"||Y.kind==="postfix"?"postfix":$.kind==="variadic"&&Y.kind==="variadic"?"variadic":G||H?"prefix":$.kind==="defaultables"||Y.kind==="defaultables"?"defaultables":"optionals";if($.kind==="prefix"&&Y.kind==="variadic"&&H){let U=r6({...W,fixedVariants:[],r:J.map((_)=>({..._,kind:"prefix"}))});if(U.disjoint.length===0)W.fixedVariants.push(U)}else if(Y.kind==="prefix"&&$.kind==="variadic"&&G){let U=r6({...W,fixedVariants:[],l:X.map((_)=>({..._,kind:"prefix"}))});if(U.disjoint.length===0)W.fixedVariants.push(U)}let z=v0($.node,Y.node,W.ctx);if(z instanceof P)if(Q==="prefix"||Q==="postfix")W.disjoint.push(...z.withPrefixKey(Q==="prefix"?W.result.length:`-${X.length+1}`,"required")),W.result=[...W.result,{kind:Q,node:N.intrinsic.never.internal}];else if(Q==="optionals"||Q==="defaultables")return W;else return r6({...W,fixedVariants:[],l:X.map((U)=>({...U,kind:"prefix"})),r:X.map((U)=>({...U,kind:"prefix"}))});else if(Q==="defaultables"){if($.kind==="defaultables"&&Y.kind==="defaultables"&&$.default!==Y.default)A(T7($.default,Y.default));W.result=[...W.result,{kind:Q,node:z,default:$.kind==="defaultables"?$.default:Y.kind==="defaultables"?Y.default:K0(`Unexpected defaultable intersection from ${$.kind} and ${Y.kind} elements.`)}]}else W.result=[...W.result,{kind:Q,node:z}];let F=W.l.length,T=W.r.length;if($.kind!=="variadic"||F>=T&&(Y.kind==="variadic"||T===1))W.l=X;if(Y.kind!=="variadic"||T>=F&&($.kind==="variadic"||F===1))W.r=J;return r6(W)};var uU=(W)=>($)=>{if($.props.length||$.index){let X=$.index?.map((J)=>J[W])??[];for(let J of $.props)X.push(J[W]);if($.undeclared)X.push(`+ (undeclared): ${$.undeclared}`);let Y=`{ ${X.join(", ")} }`;return $.sequence?`${Y} & ${$.sequence.description}`:Y}return $.sequence?.description??"{}"},iA=uU("description"),nA=uU("expression"),mU=(W,$,X)=>{let Y=W.required?"required":"optional";if(!$.signature.allows(W.key))return null;let J=d1(W.value,$.value,X);if(J instanceof P)return Y==="optional"?X.node("optional",{key:W.key,value:N.intrinsic.never.internal}):J.withPrefixKey(W.key,W.kind);return null},rA=J0({kind:"structure",hasAssociatedError:!1,normalize:(W)=>W,applyConfig:(W,$)=>{if(!W.undeclared&&$.onUndeclaredKey!=="ignore")return{...W,undeclared:$.onUndeclaredKey};return W},keys:{required:{child:!0,parse:N1("required"),reduceIo:(W,$,X)=>{$.required=D0($.required,X.map((Y)=>Y[W]));return}},optional:{child:!0,parse:N1("optional"),reduceIo:(W,$,X)=>{if(W==="in"){$.optional=X.map((Y)=>Y.in);return}for(let Y of X)$[Y.outProp.kind]=D0($[Y.outProp.kind],Y.outProp.out)}},index:{child:!0,parse:N1("index")},sequence:{child:!0,parse:N1("sequence")},undeclared:{parse:(W)=>W==="ignore"?void 0:W,reduceIo:(W,$,X)=>{if(X!=="delete")return;if(W==="in")delete $.undeclared;else $.undeclared="reject"}}},defaults:{description:iA},intersections:{structure:(W,$,X)=>{let Y={...W.inner},J={...$.inner},G=new P;if(W.undeclared){let z=W.keyof();for(let F of $.requiredKeys)if(!z.allows(F))G.add("presence",N.intrinsic.never.internal,$.propsByKey[F].value,{path:[F]});if(J.optional)J.optional=J.optional.filter((F)=>z.allows(F.key));if(J.index)J.index=J.index.flatMap((F)=>{if(F.signature.extends(z))return F;let T=d1(z,F.signature,X.$);if(T instanceof P)return[];let U=Y9(T,F.value,X.$);if(U.required)J.required=Q2(J.required,U.required);if(U.optional)J.optional=Q2(J.optional,U.optional);return U.index??[]})}if($.undeclared){let z=$.keyof();for(let F of W.requiredKeys)if(!z.allows(F))G.add("presence",W.propsByKey[F].value,N.intrinsic.never.internal,{path:[F]});if(Y.optional)Y.optional=Y.optional.filter((F)=>z.allows(F.key));if(Y.index)Y.index=Y.index.flatMap((F)=>{if(F.signature.extends(z))return F;let T=d1(z,F.signature,X.$);if(T instanceof P)return[];let U=Y9(T,F.value,X.$);if(U.required)Y.required=Q2(Y.required,U.required);if(U.optional)Y.optional=Q2(Y.optional,U.optional);return U.index??[]})}let H={};if(W.undeclared||$.undeclared)H.undeclared=W.undeclared==="reject"||$.undeclared==="reject"?"reject":"delete";let Q=C$({kind:"structure",baseInner:H,l:k$(Y),r:k$(J),roots:[],ctx:X});if(Q instanceof P)G.push(...Q);if(G.length)return G;return Q}},reduce:(W,$)=>{if(W.index){if(!(W.required||W.optional))return;let X=!1,Y=W.required??[],J=W.optional??[],G=[...J];for(let H of W.index){for(let Q of Y){let z=mU(Q,H,$);if(z instanceof P)return z}for(let[Q,z]of J.entries()){let F=mU(z,H,$);if(F instanceof P)return F;if(F===null)continue;G[Q]=F,X=!0}}if(X)return $.node("structure",{...W,optional:G},{prereduced:!0})}}});class cU extends UW{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((W)=>W.impliedSiblings??[]);props=Q2(this.required,this.optional);propsByKey=X0(this.props,(W,$)=>[$.key,$]);propsByKeyReference=d0(this.propsByKey);expression=nA(this);requiredKeys=this.required?.map((W)=>W.key)??[];optionalKeys=this.optional?.map((W)=>W.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let W=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:$}of this.index)W=W.concat($.branches);return this._keyof=this.$.node("union",W)}map(W){return this.$.node("structure",this.props.flatMap(W).reduce(($,X)=>{let Y=this.propsByKey[X.key];if(x0(X)){if(X.kind!=="required"&&X.kind!=="optional")return A(`Map result must have kind "required" or "optional" (was ${X.kind})`);return $[X.kind]=D0($[X.kind],X),$}let J=X.kind??Y?.kind??"required",G=X0(X,(H,Q)=>(H in d6.implementation.keys)?[H,Q]:[]);return $[J]=D0($[J],this.$.node(J,G)),$},{}))}assertHasKeys(W){let $=W.filter((X)=>!o6(X,this.keyof()));if($.length)return A(pU(this.expression,$))}get(W,...$){let X,Y=!1,J=eA(W);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])X=this.propsByKey[J].value,Y=this.propsByKey[J].required;if(this.index){for(let H of this.index)if(o6(J,H.signature))X=X?.and(H.value)??H.value}if(this.sequence&&o6(J,N.intrinsic.nonNegativeIntegerString))if(d(J,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let H=Number.parseInt(J);if(H<this.sequence.prevariadic.length){let Q=this.sequence.prevariadic[H].node;X=X?.and(Q)??Q,Y||=H<this.sequence.prefixLength}else if(this.sequence.variadic){let Q=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(Q)??Q}}if(!X){if(this.sequence?.variadic&&d(J,"root")&&J.extends(N.intrinsic.number))return A(WE(J.expression,this.sequence.expression));return A(pU(this.expression,[J]))}let G=X.get(...$);return Y?G:G.or(N.intrinsic.undefined)}pick(...W){return this.assertHasKeys(W),this.$.node("structure",this.filterKeys("pick",W))}omit(...W){return this.assertHasKeys(W),this.$.node("structure",this.filterKeys("omit",W))}optionalize(){let{required:W,...$}=this.inner;return this.$.node("structure",{...$,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:W,...$}=this.inner;return this.$.node("structure",{...$,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(W){let $=this.filterKeys("omit",[W.keyof()]);if(W.required)$.required=D0($.required,W.required);if(W.optional)$.optional=D0($.optional,W.optional);if(W.index)$.index=D0($.index,W.index);if(W.sequence)$.sequence=W.sequence;if(W.undeclared)$.undeclared=W.undeclared;else delete $.undeclared;return this.$.node("structure",$)}filterKeys(W,$){let X=oY(this.inner),Y=(J)=>{let G=$.some((H)=>o6(J,H));return W==="pick"?G:!G};if(X.required)X.required=X.required.filter((J)=>Y(J.key));if(X.optional)X.optional=X.optional.filter((J)=>Y(J.key));if(X.index)X.index=X.index.filter((J)=>Y(J.signature));return X}traverseAllows=(W,$)=>this._traverse("Allows",W,$);traverseApply=(W,$)=>this._traverse("Apply",W,$);_traverse=(W,$,X)=>{let Y=X?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(W==="Allows"){if(!this.props[J].traverseAllows($,X))return!1}else if(this.props[J].traverseApply($,X),X.failFast&&X.currentErrorCount>Y)return!1;if(this.sequence){if(W==="Allows"){if(!this.sequence.traverseAllows($,X))return!1}else if(this.sequence.traverseApply($,X),X.failFast&&X.currentErrorCount>Y)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys($);J.push(...Object.getOwnPropertySymbols($));for(let G=0;G<J.length;G++){let H=J[G];if(this.index){for(let Q of this.index)if(Q.signature.traverseAllows(H,X)){if(W==="Allows"){if(!c1(H,()=>Q.value.traverseAllows($[H],X),X))return!1}else if(c1(H,()=>Q.value.traverseApply($[H],X),X),X.failFast&&X.currentErrorCount>Y)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(H)){if(W==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[H],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((W)=>W.hasDefault())??[])}declaresKey=(W)=>(W in this.propsByKey)||this.index?.some(($)=>$.signature.allows(W))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(W);_compileDeclaresKey(W){let $=[];if(this.props.length)$.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)$.push(W.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)$.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return $.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",aA(this))}structuralMorphRef=this.structuralMorph&&d0(this.structuralMorph);compile(W){if(W.traversalKind==="Apply")W.initializeErrorCount();for(let $ of this.props)if(W.check($),W.traversalKind==="Apply")W.returnIfFailFast();if(this.sequence){if(W.check(this.sequence),W.traversalKind==="Apply")W.returnIfFailFast()}if(this.index||this.undeclared==="reject")W.const("keys","Object.keys(data)"),W.line("keys.push(...Object.getOwnPropertySymbols(data))"),W.for("i < keys.length",()=>this.compileExhaustiveEntry(W));if(W.traversalKind==="Allows")return W.return(!0);if(this.structuralMorphRef)W.if("ctx && !ctx.hasError()",()=>{return W.line("ctx.queueMorphs(["),sA(W,this),W.line("])")})}compileExhaustiveEntry(W){if(W.const("k","keys[i]"),this.index)for(let $ of this.index)W.if(`${W.invoke($.signature,{arg:"k",kind:"Allows"})}`,()=>W.traverseKey("k","data[k]",$.value));if(this.undeclared==="reject")W.if(`!(${this._compileDeclaresKey(W)})`,()=>{if(W.traversalKind==="Allows")return W.return(!1);return W.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>W.return())});return W}reduceJsonSchema(W,$){switch(W.type){case"object":return this.reduceObjectJsonSchema(W,$);case"array":let X=this.sequence?.reduceJsonSchema(W,$)??W;if(this.props.length||this.index)return $.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},$)});return X;default:return h0.throwInternalOperandError("structure",W)}}reduceObjectJsonSchema(W,$){if(this.props.length){W.properties={};for(let X of this.props){let Y=X.value.toJsonSchemaRecurse($);if(typeof X.key==="symbol"){$.fallback.symbolKey({code:"symbolKey",base:W,key:X.key,value:Y,optional:X.optional});continue}if(X.hasDefault()){let J=typeof X.default==="function"?X.default():X.default;Y.default=N.intrinsic.jsonData.allows(J)?J:$.fallback.defaultValue({code:"defaultValue",base:Y,value:J})}W.properties[X.key]=Y}if(this.requiredKeys.length&&W.properties)W.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in W.properties))}if(this.index)for(let X of this.index){let Y=X.value.toJsonSchemaRecurse($);if(X.signature.equals(N.intrinsic.string)){W.additionalProperties=Y;continue}for(let J of X.signature.branches){if(!J.extends(N.intrinsic.string)){W=$.fallback.symbolKey({code:"symbolKey",base:W,key:null,value:Y,optional:!1});continue}let G={type:"string"};if(J.hasKind("morph"))G=$.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse($),out:J.out.toJsonSchemaRecurse($)});if(!J.hasKind("intersection"))return K0(`Unexpected index branch kind ${J.kind}.`);let{pattern:H}=J.inner;if(H){let Q=Object.assign(G,{pattern:H[0].rule});for(let z=1;z<H.length;z++)G=$.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:H[z].rule});W.patternProperties??={},W.patternProperties[Q.pattern]=Y}}}if(this.undeclared&&!W.additionalProperties)W.additionalProperties=!1;return W}}var L7={},tA=(W)=>{let $="";for(let X=0;X<W.defaultable.length;X++)$+=W.defaultable[X].defaultValueMorphRef;if(W.sequence?.defaultValueMorphsReference)$+=W.sequence?.defaultValueMorphsReference;if(W.undeclared==="delete"){if($+="delete !(",W.required)for(let X of W.required)$+=X.compiledKey+" | ";if(W.optional)for(let X of W.optional)$+=X.compiledKey+" | ";if(W.index)for(let X of W.index)$+=X.signature.id+" | ";if(W.sequence)if(W.sequence.maxLength===null)$+=r.nonNegativeIntegerString.id;else for(let X=0;X<W.sequence.tuple.length;X++)$+=X+" | ";$+=")"}return $},aA=(W)=>{let $=tA(W);if(!$)return;if(L7[$])return L7[$];let X=(Y,J)=>{for(let G=0;G<W.defaultable.length;G++)if(!(W.defaultable[G].key in Y))W.defaultable[G].defaultValueMorph(Y,J);if(W.sequence?.defaultables)for(let G=Y.length-W.sequence.prefixLength;G<W.sequence.defaultables.length;G++)W.sequence.defaultValueMorphs[G](Y,J);if(W.undeclared==="delete"){for(let G in Y)if(!W.declaresKey(G))delete Y[G]}return Y};return L7[$]=X},sA=(W,$)=>{let Y=`(data${$.defaultable.some((J)=>J.defaultValueMorph.length===2)||$.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return W.block(`${Y} => `,(J)=>{for(let G=0;G<$.defaultable.length;G++){let{serializedKey:H,defaultValueMorphRef:Q}=$.defaultable[G];J.if(`!(${H} in data)`,(z)=>z.line(`${Q}${Y}`))}if($.sequence?.defaultables)J.for(`i < ${$.sequence.defaultables.length}`,(G)=>G.set("data[i]",5),`data.length - ${$.sequence.prefixLength}`);if($.undeclared==="delete")J.forIn("data",(G)=>G.if(`!(${$._compileDeclaresKey(G)})`,(H)=>H.line("delete data[k]")));return J.return("data")})},B7={implementation:rA,Node:cU},eA=(W)=>{if(d(W,"root")&&W.hasKind("unit"))W=W.unit;if(typeof W==="number")W=`${W}`;return W},WE=(W,$)=>`${W} is not allowed as an array index on ${$}. Use the 'nonNegativeIntegerString' keyword instead.`,Y9=(W,$,X)=>{let[Y,J]=wT(W.branches,(H)=>H.hasKind("unit"));if(!Y.length)return{index:X.node("index",{signature:W,value:$})};let G={};for(let H of Y){let Q=X.node("required",{key:H.unit,value:$});G[Q.kind]=D0(G[Q.kind],Q)}if(J.length)G.index=X.node("index",{signature:J,value:$});return G},$E=(W)=>d(W,"root")?W.expression:Y0(W),pU=(W,$)=>`Key${$.length===1?"":"s"} ${$.map($E).join(", ")} ${$.length===1?"does":"do"} not exist on ${W}`;var I$={..._U,alias:i6.implementation,domain:X9.implementation,unit:V7.implementation,proto:n6.implementation,union:M7.implementation,morph:_7.implementation,intersection:w7.implementation,divisor:s5.implementation,pattern:H7.implementation,predicate:a5.implementation,required:K7.implementation,optional:d6.implementation,index:O7.implementation,sequence:A7.implementation,structure:B7.implementation};N.defaultConfig=LT(Object.assign(X0(I$,(W,$)=>[W,$.defaults]),{jitless:qT(),clone:NT,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:h0.defaultConfig}));N.resolvedConfig=y6(N.defaultConfig,N.config);var AU={...DU,alias:i6.Node,domain:X9.Node,unit:V7.Node,proto:n6.Node,union:M7.Node,morph:_7.Node,intersection:w7.Node,divisor:s5.Node,pattern:H7.Node,predicate:a5.Node,required:K7.Node,optional:d6.Node,index:O7.Node,sequence:A7.Node,structure:B7.Node};class x$ extends f5{get[f1](){return"module"}}var R7=(W,$)=>new x$(X0(W,(X,Y)=>[X,d(Y,"module")?R7(Y,$):$.bindReference(Y)]));var XE=(W)=>k0(W)?W:("branches"in W)&&k0(W.branches)?W.branches:void 0,YE=(W,$)=>A(`Node of kind ${$} is not valid as a ${W} definition`),dU=(W)=>`#${W} duplicates public alias ${W}`,N7={};N.ambient??={};var lU,iU="function $",JE=(W)=>nU(W,rU(W)),nU=(W,$)=>{let X=$.write(iU,4),Y=$.compile()();for(let J of W){if(J.precompilation)continue;if(J.traverseAllows=Y[`${J.id}Allows`].bind(Y),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=Y[`${J.id}Apply`].bind(Y),Y[`${J.id}Optimistic`])J.traverseOptimistic=Y[`${J.id}Optimistic`].bind(Y);J.precompilation=X}},rU=(W)=>new lY().return(W.reduce(($,X)=>{let Y=new b6({kind:"Allows"}).indent();X.compile(Y);let J=Y.write(`${X.id}Allows`),G=new b6({kind:"Apply"}).indent();X.compile(G);let H=G.write(`${X.id}Apply`),Q=`${$}${J},
123
+ Right: ${$}`;var gA=J0({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(W)=>W instanceof Date?W.toISOString():_W(W)}},normalize:(W)=>W,defaults:{description:(W)=>G0(W.unit),problem:({expected:W,actual:$})=>`${W===$?`must be reference equal to ${W} (serialized to the same value)`:`must be ${W} (was ${$})`}`},intersections:{unit:(W,$)=>b.init("unit",W,$),...dW("unit",(W,$)=>{if($.allows(W.unit))return W;let X=$.hasKind("intersection")?$.basis:$;if(X){let Y=X.hasKind("domain")?X:N.intrinsic.object;if(W.domain!==Y.domain){let G=W.domain==="undefined"||W.domain==="null"||W.domain==="boolean"?W.domain:N.intrinsic[W.domain];return b.init("domain",G,Y)}}return b.init("assignability",W,$.hasKind("intersection")?$.children.find((Y)=>!Y.allows(W.unit)):$)})}});class y_ extends j8{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=v_(this.unit,this.serializedValue);compiledNegation=v_(this.unit,this.serializedValue,"negated");expression=G0(this.unit);domain=z1(this.unit);get defaultShortDescription(){return this.domain==="object"?u1.object:this.description}innerToJsonSchema(W){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:W.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(W)=>W instanceof Date&&W.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(W)=>Number.isNaN(W):(W)=>W===this.unit}var KG={implementation:gA,Node:y_},v_=(W,$,X)=>{if(W instanceof Date){let Y=`data instanceof Date && data.toISOString() === ${$}`;return X?`!(${Y})`:Y}if(Number.isNaN(W))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${$}`};var mA=J0({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(W,$)=>{let X=$.$.parseSchema(W);if(!X.extends(N.intrinsic.key))return E(uA(X.expression));let Y=X.branches.filter((G)=>G.hasKind("unit"));if(Y.length)return E(pA(Y.map((G)=>G0(G.unit))));return X}},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`[${W.signature.expression}]: ${W.value.description}`},intersections:{index:(W,$,X)=>{if(W.signature.equals($.signature)){let Y=b0(W.value,$.value,X),G=Y instanceof b?N.intrinsic.never.internal:Y;return X.$.node("index",{signature:W.signature,value:G})}if(W.signature.extends($.signature)&&W.value.subsumes($.value))return $;if($.signature.extends(W.signature)&&$.value.subsumes(W.value))return W;return null}}});class h_ extends wW{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=D0(this.value.flatRefs.map((W)=>kW([this.signature,...W.path],W.node)),kW([this.signature],this.value));traverseAllows=(W,$)=>S8(W).every((X)=>{if(this.signature.traverseAllows(X[0],$))return d1(X[0],()=>this.value.traverseAllows(X[1],$),$);return!0});traverseApply=(W,$)=>{for(let X of S8(W))if(this.signature.traverseAllows(X[0],$))d1(X[0],()=>this.value.traverseApply(X[1],$),$)};_transform(W,$){$.path.push(this.signature);let X=super._transform(W,$);return $.path.pop(),X}compile(){}}var AG={implementation:mA,Node:h_},pA=(W)=>`Index keys ${W.join(", ")} should be specified as named props.`,uA=(W)=>`Indexed key definition '${W}' must be a string or symbol`;var cA=J0({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`${W.compiledKey}: ${W.value.description}`,expected:(W)=>W.missingValueDescription,actual:()=>"missing"},intersections:{required:d6,optional:d6}});class g_ extends l6{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=c2(this.errorContext)}var EG={implementation:cA,Node:g_};var dA=J0({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}},optionals:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}},defaultables:{child:(W)=>W.map(($)=>$[0]),parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>{let Y=$.$.parseSchema(X[0]);return i6(Y,X[1],null),[Y,X[1]]})},serialize:(W)=>W.map(($)=>[$[0].collapsibleJson,_W($[1])])},variadic:{child:!0,parse:(W,$)=>$.$.parseSchema(W,$)},minVariadicLength:{parse:(W)=>W===0?void 0:W},postfix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}}},normalize:(W)=>{if(typeof W==="string")return{variadic:W};if("variadic"in W||"prefix"in W||"defaultables"in W||"optionals"in W||"postfix"in W||"minVariadicLength"in W){if(W.postfix?.length){if(!W.variadic)return E(nA);if(W.optionals?.length||W.defaultables?.length)return E(BG)}if(W.minVariadicLength&&!W.variadic)return E("minVariadicLength may not be specified without a variadic element");return W}return{variadic:W}},reduce:(W,$)=>{let X=W.minVariadicLength??0,Y=W.prefix?.slice()??[],G=W.defaultables?.slice()??[],J=W.optionals?.slice()??[],H=W.postfix?.slice()??[];if(W.variadic){while(J.at(-1)?.equals(W.variadic))J.pop();if(J.length===0&&G.length===0)while(Y.at(-1)?.equals(W.variadic))Y.pop(),X++;while(H[0]?.equals(W.variadic))H.shift(),X++}else if(J.length===0&&G.length===0)Y.push(...H.splice(0));if(X!==W.minVariadicLength||W.prefix&&W.prefix.length!==Y.length)return $.node("sequence",{...W,prefix:Y,defaultables:G,optionals:J,postfix:H,minVariadicLength:X},{prereduced:!0})},defaults:{description:(W)=>{if(W.isVariadicOnly)return`${W.variadic.nestableExpression}[]`;return`[${W.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${G0(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(W,$,X)=>{let Y=a6({l:W.tuple,r:$.tuple,disjoint:new b,result:[],fixedVariants:[],ctx:X}),G=Y.disjoint.length===0?[Y,...Y.fixedVariants]:Y.fixedVariants;return G.length===0?Y.disjoint:G.length===1?X.$.node("sequence",m_(G[0].result)):X.$.node("union",G.map((J)=>({proto:Array,sequence:m_(J.result)})))}}});class p_ extends wW{impliedBasis=N.intrinsic.Array.internal;tuple=iA(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((W)=>{if(W.kind==="defaultables"||W.kind==="optionals")return this.defaultablesAndOptionals.push(W.node),!0;return W.kind==="prefix"});variadicOrPostfix=Q2(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return r7(this.flatRefs,this.prevariadic.flatMap((W,$)=>D0(W.node.flatRefs.map((X)=>kW([`${$}`,...X.path],X.node)),kW([`${$}`],W.node)))),r7(this.flatRefs,this.variadicOrPostfix.flatMap((W)=>D0(W.flatRefs.map(($)=>kW([N.intrinsic.nonNegativeIntegerString.internal,...$.path],$.node)),kW([N.intrinsic.nonNegativeIntegerString.internal],W)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=oA(this);defaultValueMorphsReference=this.defaultValueMorphs.length?d0(this.defaultValueMorphs):void 0;elementAtIndex(W,$){if($<this.prevariadic.length)return this.tuple[$];let X=W.length-this.postfixLength;if($>=X)return{kind:"postfix",node:this.postfix[$-X]};return{kind:"variadic",node:this.variadic??K0(`Unexpected attempt to access index ${$} on ${this}`)}}traverseAllows=(W,$)=>{for(let X=0;X<W.length;X++)if(!this.elementAtIndex(W,X).node.traverseAllows(W[X],$))return!1;return!0};traverseApply=(W,$)=>{let X=0;for(;X<W.length;X++)d1(X,()=>this.elementAtIndex(W,X).node.traverseApply(W[X],$),$)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(W){if(this.prefix)for(let[$,X]of this.prefix.entries())W.traverseKey(`${$}`,`data[${$}]`,X);for(let[$,X]of this.defaultablesAndOptionals.entries()){let Y=`${$+this.prefixLength}`;W.if(`${Y} >= ${W.data}.length`,()=>W.traversalKind==="Allows"?W.return(!0):W.return()),W.traverseKey(Y,`data[${Y}]`,X)}if(this.variadic){if(this.postfix)W.const("firstPostfixIndex",`${W.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(W.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>W.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[$,X]of this.postfix.entries()){let Y=`firstPostfixIndex + ${$}`;W.traverseKey(Y,`data[${Y}]`,X)}}if(W.traversalKind==="Allows")W.return(!0)}_transform(W,$){$.path.push(N.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(W,$);return $.path.pop(),X}expression=this.description;reduceJsonSchema(W,$){if(this.prevariadic.length)W.prefixItems=this.prevariadic.map((X)=>{let Y=X.node.toJsonSchemaRecurse($);if(X.kind==="defaultables"){let G=typeof X.default==="function"?X.default():X.default;Y.default=N.intrinsic.jsonData.allows(G)?G:$.fallback.defaultValue({code:"defaultValue",base:Y,value:G})}return Y});if(this.minLength)W.minItems=this.minLength;if(this.variadic){let X=Object.assign(W,{items:this.variadic.toJsonSchemaRecurse($)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let Y=this.postfix.map((G)=>G.toJsonSchemaRecurse($));W=$.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:Y})}}else W.items=!1,delete W.maxItems;return W}}var lA={},oA=(W)=>{if(!W.defaultables)return[];let $=[],X="[",Y=W.prefixLength+W.defaultablesLength-1;for(let G=W.prefixLength;G<=Y;G++){let[J,H]=W.defaultables[G-W.prefixLength];$.push(UG(G,J,H)),X+=`${G}: ${J.id} = ${_W(H)}, `}return X+="]",lA[X]??=$},LG={implementation:dA,Node:p_},iA=(W)=>{let $=[];if(W.prefix)for(let X of W.prefix)$.push({kind:"prefix",node:X});if(W.defaultables)for(let[X,Y]of W.defaultables)$.push({kind:"defaultables",node:X,default:Y});if(W.optionals)for(let X of W.optionals)$.push({kind:"optionals",node:X});if(W.variadic)$.push({kind:"variadic",node:W.variadic});if(W.postfix)for(let X of W.postfix)$.push({kind:"postfix",node:X});return $},m_=(W)=>W.reduce(($,X)=>{if(X.kind==="variadic")$.variadic=X.node;else if(X.kind==="defaultables")$.defaultables=D0($.defaultables,[[X.node,X.default]]);else $[X.kind]=D0($[X.kind],X.node);return $},{}),BG="A postfix required element cannot follow an optional or defaultable element",nA="A postfix element requires a variadic element",a6=(W)=>{let[$,...X]=W.l,[Y,...G]=W.r;if(!$||!Y)return W;let J=X.at(-1)?.kind==="postfix",H=G.at(-1)?.kind==="postfix",Q=$.kind==="prefix"||Y.kind==="prefix"?"prefix":$.kind==="postfix"||Y.kind==="postfix"?"postfix":$.kind==="variadic"&&Y.kind==="variadic"?"variadic":J||H?"prefix":$.kind==="defaultables"||Y.kind==="defaultables"?"defaultables":"optionals";if($.kind==="prefix"&&Y.kind==="variadic"&&H){let _=a6({...W,fixedVariants:[],r:G.map((w)=>({...w,kind:"prefix"}))});if(_.disjoint.length===0)W.fixedVariants.push(_)}else if(Y.kind==="prefix"&&$.kind==="variadic"&&J){let _=a6({...W,fixedVariants:[],l:X.map((w)=>({...w,kind:"prefix"}))});if(_.disjoint.length===0)W.fixedVariants.push(_)}let z=b0($.node,Y.node,W.ctx);if(z instanceof b)if(Q==="prefix"||Q==="postfix")W.disjoint.push(...z.withPrefixKey(Q==="prefix"?W.result.length:`-${X.length+1}`,"required")),W.result=[...W.result,{kind:Q,node:N.intrinsic.never.internal}];else if(Q==="optionals"||Q==="defaultables")return W;else return a6({...W,fixedVariants:[],l:X.map((_)=>({..._,kind:"prefix"})),r:X.map((_)=>({..._,kind:"prefix"}))});else if(Q==="defaultables"){if($.kind==="defaultables"&&Y.kind==="defaultables"&&$.default!==Y.default)E(wG($.default,Y.default));W.result=[...W.result,{kind:Q,node:z,default:$.kind==="defaultables"?$.default:Y.kind==="defaultables"?Y.default:K0(`Unexpected defaultable intersection from ${$.kind} and ${Y.kind} elements.`)}]}else W.result=[...W.result,{kind:Q,node:z}];let T=W.l.length,F=W.r.length;if($.kind!=="variadic"||T>=F&&(Y.kind==="variadic"||F===1))W.l=X;if(Y.kind!=="variadic"||F>=T&&($.kind==="variadic"||T===1))W.r=G;return a6(W)};var d_=(W)=>($)=>{if($.props.length||$.index){let X=$.index?.map((G)=>G[W])??[];for(let G of $.props)X.push(G[W]);if($.undeclared)X.push(`+ (undeclared): ${$.undeclared}`);let Y=`{ ${X.join(", ")} }`;return $.sequence?`${Y} & ${$.sequence.description}`:Y}return $.sequence?.description??"{}"},rA=d_("description"),tA=d_("expression"),u_=(W,$,X)=>{let Y=W.required?"required":"optional";if(!$.signature.allows(W.key))return null;let G=l1(W.value,$.value,X);if(G instanceof b)return Y==="optional"?X.node("optional",{key:W.key,value:N.intrinsic.never.internal}):G.withPrefixKey(W.key,W.kind);return null},aA=J0({kind:"structure",hasAssociatedError:!1,normalize:(W)=>W,applyConfig:(W,$)=>{if(!W.undeclared&&$.onUndeclaredKey!=="ignore")return{...W,undeclared:$.onUndeclaredKey};return W},keys:{required:{child:!0,parse:N1("required"),reduceIo:(W,$,X)=>{$.required=D0($.required,X.map((Y)=>Y[W]));return}},optional:{child:!0,parse:N1("optional"),reduceIo:(W,$,X)=>{if(W==="in"){$.optional=X.map((Y)=>Y.in);return}for(let Y of X)$[Y.outProp.kind]=D0($[Y.outProp.kind],Y.outProp.out)}},index:{child:!0,parse:N1("index")},sequence:{child:!0,parse:N1("sequence")},undeclared:{parse:(W)=>W==="ignore"?void 0:W,reduceIo:(W,$,X)=>{if(X!=="delete")return;if(W==="in")delete $.undeclared;else $.undeclared="reject"}}},defaults:{description:rA},intersections:{structure:(W,$,X)=>{let Y={...W.inner},G={...$.inner},J=new b;if(W.undeclared){let z=W.keyof();for(let T of $.requiredKeys)if(!z.allows(T))J.add("presence",N.intrinsic.never.internal,$.propsByKey[T].value,{path:[T]});if(G.optional)G.optional=G.optional.filter((T)=>z.allows(T.key));if(G.index)G.index=G.index.flatMap((T)=>{if(T.signature.extends(z))return T;let F=l1(z,T.signature,X.$);if(F instanceof b)return[];let _=Y9(F,T.value,X.$);if(_.required)G.required=Q2(G.required,_.required);if(_.optional)G.optional=Q2(G.optional,_.optional);return _.index??[]})}if($.undeclared){let z=$.keyof();for(let T of W.requiredKeys)if(!z.allows(T))J.add("presence",W.propsByKey[T].value,N.intrinsic.never.internal,{path:[T]});if(Y.optional)Y.optional=Y.optional.filter((T)=>z.allows(T.key));if(Y.index)Y.index=Y.index.flatMap((T)=>{if(T.signature.extends(z))return T;let F=l1(z,T.signature,X.$);if(F instanceof b)return[];let _=Y9(F,T.value,X.$);if(_.required)Y.required=Q2(Y.required,_.required);if(_.optional)Y.optional=Q2(Y.optional,_.optional);return _.index??[]})}let H={};if(W.undeclared||$.undeclared)H.undeclared=W.undeclared==="reject"||$.undeclared==="reject"?"reject":"delete";let Q=j4({kind:"structure",baseInner:H,l:I4(Y),r:I4(G),roots:[],ctx:X});if(Q instanceof b)J.push(...Q);if(J.length)return J;return Q}},reduce:(W,$)=>{if(W.index){if(!(W.required||W.optional))return;let X=!1,Y=W.required??[],G=W.optional??[],J=[...G];for(let H of W.index){for(let Q of Y){let z=u_(Q,H,$);if(z instanceof b)return z}for(let[Q,z]of G.entries()){let T=u_(z,H,$);if(T instanceof b)return T;if(T===null)continue;J[Q]=T,X=!0}}if(X)return $.node("structure",{...W,optional:J},{prereduced:!0})}}});class l_ extends wW{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((W)=>W.impliedSiblings??[]);props=Q2(this.required,this.optional);propsByKey=Y0(this.props,(W,$)=>[$.key,$]);propsByKeyReference=d0(this.propsByKey);expression=tA(this);requiredKeys=this.required?.map((W)=>W.key)??[];optionalKeys=this.optional?.map((W)=>W.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let W=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:$}of this.index)W=W.concat($.branches);return this._keyof=this.$.node("union",W)}map(W){return this.$.node("structure",this.props.flatMap(W).reduce(($,X)=>{let Y=this.propsByKey[X.key];if(x0(X)){if(X.kind!=="required"&&X.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${X.kind})`);return $[X.kind]=D0($[X.kind],X),$}let G=X.kind??Y?.kind??"required",J=Y0(X,(H,Q)=>(H in o6.implementation.keys)?[H,Q]:[]);return $[G]=D0($[G],this.$.node(G,J)),$},{}))}assertHasKeys(W){let $=W.filter((X)=>!n6(X,this.keyof()));if($.length)return E(c_(this.expression,$))}get(W,...$){let X,Y=!1,G=$E(W);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])X=this.propsByKey[G].value,Y=this.propsByKey[G].required;if(this.index){for(let H of this.index)if(n6(G,H.signature))X=X?.and(H.value)??H.value}if(this.sequence&&n6(G,N.intrinsic.nonNegativeIntegerString))if(d(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let H=Number.parseInt(G);if(H<this.sequence.prevariadic.length){let Q=this.sequence.prevariadic[H].node;X=X?.and(Q)??Q,Y||=H<this.sequence.prefixLength}else if(this.sequence.variadic){let Q=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(Q)??Q}}if(!X){if(this.sequence?.variadic&&d(G,"root")&&G.extends(N.intrinsic.number))return E(XE(G.expression,this.sequence.expression));return E(c_(this.expression,[G]))}let J=X.get(...$);return Y?J:J.or(N.intrinsic.undefined)}pick(...W){return this.assertHasKeys(W),this.$.node("structure",this.filterKeys("pick",W))}omit(...W){return this.assertHasKeys(W),this.$.node("structure",this.filterKeys("omit",W))}optionalize(){let{required:W,...$}=this.inner;return this.$.node("structure",{...$,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:W,...$}=this.inner;return this.$.node("structure",{...$,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(W){let $=this.filterKeys("omit",[W.keyof()]);if(W.required)$.required=D0($.required,W.required);if(W.optional)$.optional=D0($.optional,W.optional);if(W.index)$.index=D0($.index,W.index);if(W.sequence)$.sequence=W.sequence;if(W.undeclared)$.undeclared=W.undeclared;else delete $.undeclared;return this.$.node("structure",$)}filterKeys(W,$){let X=oY(this.inner),Y=(G)=>{let J=$.some((H)=>n6(G,H));return W==="pick"?J:!J};if(X.required)X.required=X.required.filter((G)=>Y(G.key));if(X.optional)X.optional=X.optional.filter((G)=>Y(G.key));if(X.index)X.index=X.index.filter((G)=>Y(G.signature));return X}traverseAllows=(W,$)=>this._traverse("Allows",W,$);traverseApply=(W,$)=>this._traverse("Apply",W,$);_traverse=(W,$,X)=>{let Y=X?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(W==="Allows"){if(!this.props[G].traverseAllows($,X))return!1}else if(this.props[G].traverseApply($,X),X.failFast&&X.currentErrorCount>Y)return!1;if(this.sequence){if(W==="Allows"){if(!this.sequence.traverseAllows($,X))return!1}else if(this.sequence.traverseApply($,X),X.failFast&&X.currentErrorCount>Y)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys($);G.push(...Object.getOwnPropertySymbols($));for(let J=0;J<G.length;J++){let H=G[J];if(this.index){for(let Q of this.index)if(Q.signature.traverseAllows(H,X)){if(W==="Allows"){if(!d1(H,()=>Q.value.traverseAllows($[H],X),X))return!1}else if(d1(H,()=>Q.value.traverseApply($[H],X),X),X.failFast&&X.currentErrorCount>Y)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(H)){if(W==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[H],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((W)=>W.hasDefault())??[])}declaresKey=(W)=>(W in this.propsByKey)||this.index?.some(($)=>$.signature.allows(W))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(W);_compileDeclaresKey(W){let $=[];if(this.props.length)$.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)$.push(W.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)$.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return $.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",eA(this))}structuralMorphRef=this.structuralMorph&&d0(this.structuralMorph);compile(W){if(W.traversalKind==="Apply")W.initializeErrorCount();for(let $ of this.props)if(W.check($),W.traversalKind==="Apply")W.returnIfFailFast();if(this.sequence){if(W.check(this.sequence),W.traversalKind==="Apply")W.returnIfFailFast()}if(this.index||this.undeclared==="reject")W.const("keys","Object.keys(data)"),W.line("keys.push(...Object.getOwnPropertySymbols(data))"),W.for("i < keys.length",()=>this.compileExhaustiveEntry(W));if(W.traversalKind==="Allows")return W.return(!0);if(this.structuralMorphRef)W.if("ctx && !ctx.hasError()",()=>{return W.line("ctx.queueMorphs(["),WE(W,this),W.line("])")})}compileExhaustiveEntry(W){if(W.const("k","keys[i]"),this.index)for(let $ of this.index)W.if(`${W.invoke($.signature,{arg:"k",kind:"Allows"})}`,()=>W.traverseKey("k","data[k]",$.value));if(this.undeclared==="reject")W.if(`!(${this._compileDeclaresKey(W)})`,()=>{if(W.traversalKind==="Allows")return W.return(!1);return W.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>W.return())});return W}reduceJsonSchema(W,$){switch(W.type){case"object":return this.reduceObjectJsonSchema(W,$);case"array":let X=this.sequence?.reduceJsonSchema(W,$)??W;if(this.props.length||this.index)return $.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},$)});return X;default:return h0.throwInternalOperandError("structure",W)}}reduceObjectJsonSchema(W,$){if(this.props.length){W.properties={};for(let X of this.props){let Y=X.value.toJsonSchemaRecurse($);if(typeof X.key==="symbol"){$.fallback.symbolKey({code:"symbolKey",base:W,key:X.key,value:Y,optional:X.optional});continue}if(X.hasDefault()){let G=typeof X.default==="function"?X.default():X.default;Y.default=N.intrinsic.jsonData.allows(G)?G:$.fallback.defaultValue({code:"defaultValue",base:Y,value:G})}W.properties[X.key]=Y}if(this.requiredKeys.length&&W.properties)W.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in W.properties))}if(this.index)for(let X of this.index){let Y=X.value.toJsonSchemaRecurse($);if(X.signature.equals(N.intrinsic.string)){W.additionalProperties=Y;continue}for(let G of X.signature.branches){if(!G.extends(N.intrinsic.string)){W=$.fallback.symbolKey({code:"symbolKey",base:W,key:null,value:Y,optional:!1});continue}let J={type:"string"};if(G.hasKind("morph"))J=$.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse($),out:G.out.toJsonSchemaRecurse($)});if(!G.hasKind("intersection"))return K0(`Unexpected index branch kind ${G.kind}.`);let{pattern:H}=G.inner;if(H){let Q=Object.assign(J,{pattern:H[0].rule});for(let z=1;z<H.length;z++)J=$.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:H[z].rule});W.patternProperties??={},W.patternProperties[Q.pattern]=Y}}}if(this.undeclared&&!W.additionalProperties)W.additionalProperties=!1;return W}}var RG={},sA=(W)=>{let $="";for(let X=0;X<W.defaultable.length;X++)$+=W.defaultable[X].defaultValueMorphRef;if(W.sequence?.defaultValueMorphsReference)$+=W.sequence?.defaultValueMorphsReference;if(W.undeclared==="delete"){if($+="delete !(",W.required)for(let X of W.required)$+=X.compiledKey+" | ";if(W.optional)for(let X of W.optional)$+=X.compiledKey+" | ";if(W.index)for(let X of W.index)$+=X.signature.id+" | ";if(W.sequence)if(W.sequence.maxLength===null)$+=r.nonNegativeIntegerString.id;else for(let X=0;X<W.sequence.tuple.length;X++)$+=X+" | ";$+=")"}return $},eA=(W)=>{let $=sA(W);if(!$)return;if(RG[$])return RG[$];let X=(Y,G)=>{for(let J=0;J<W.defaultable.length;J++)if(!(W.defaultable[J].key in Y))W.defaultable[J].defaultValueMorph(Y,G);if(W.sequence?.defaultables)for(let J=Y.length-W.sequence.prefixLength;J<W.sequence.defaultables.length;J++)W.sequence.defaultValueMorphs[J](Y,G);if(W.undeclared==="delete"){for(let J in Y)if(!W.declaresKey(J))delete Y[J]}return Y};return RG[$]=X},WE=(W,$)=>{let Y=`(data${$.defaultable.some((G)=>G.defaultValueMorph.length===2)||$.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return W.block(`${Y} => `,(G)=>{for(let J=0;J<$.defaultable.length;J++){let{serializedKey:H,defaultValueMorphRef:Q}=$.defaultable[J];G.if(`!(${H} in data)`,(z)=>z.line(`${Q}${Y}`))}if($.sequence?.defaultables)G.for(`i < ${$.sequence.defaultables.length}`,(J)=>J.set("data[i]",5),`data.length - ${$.sequence.prefixLength}`);if($.undeclared==="delete")G.forIn("data",(J)=>J.if(`!(${$._compileDeclaresKey(J)})`,(H)=>H.line("delete data[k]")));return G.return("data")})},NG={implementation:aA,Node:l_},$E=(W)=>{if(d(W,"root")&&W.hasKind("unit"))W=W.unit;if(typeof W==="number")W=`${W}`;return W},XE=(W,$)=>`${W} is not allowed as an array index on ${$}. Use the 'nonNegativeIntegerString' keyword instead.`,Y9=(W,$,X)=>{let[Y,G]=DF(W.branches,(H)=>H.hasKind("unit"));if(!Y.length)return{index:X.node("index",{signature:W,value:$})};let J={};for(let H of Y){let Q=X.node("required",{key:H.unit,value:$});J[Q.kind]=D0(J[Q.kind],Q)}if(G.length)J.index=X.node("index",{signature:G,value:$});return J},YE=(W)=>d(W,"root")?W.expression:G0(W),c_=(W,$)=>`Key${$.length===1?"":"s"} ${$.map(YE).join(", ")} ${$.length===1?"does":"do"} not exist on ${W}`;var f4={...V_,alias:r6.implementation,domain:X9.implementation,unit:KG.implementation,proto:t6.implementation,union:OG.implementation,morph:VG.implementation,intersection:DG.implementation,divisor:WG.implementation,pattern:zG.implementation,predicate:e7.implementation,required:EG.implementation,optional:o6.implementation,index:AG.implementation,sequence:LG.implementation,structure:NG.implementation};N.defaultConfig=RF(Object.assign(Y0(f4,(W,$)=>[W,$.defaults]),{jitless:kF(),clone:SF,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:h0.defaultConfig}));N.resolvedConfig=g6(N.defaultConfig,N.config);var L_={...M_,alias:r6.Node,domain:X9.Node,unit:KG.Node,proto:t6.Node,union:OG.Node,morph:VG.Node,intersection:DG.Node,divisor:WG.Node,pattern:zG.Node,predicate:e7.Node,required:EG.Node,optional:o6.Node,index:AG.Node,sequence:LG.Node,structure:NG.Node};class v4 extends x7{get[f1](){return"module"}}var ZG=(W,$)=>new v4(Y0(W,(X,Y)=>[X,d(Y,"module")?ZG(Y,$):$.bindReference(Y)]));var GE=(W)=>k0(W)?W:("branches"in W)&&k0(W.branches)?W.branches:void 0,JE=(W,$)=>E(`Node of kind ${$} is not valid as a ${W} definition`),o_=(W)=>`#${W} duplicates public alias ${W}`,SG={};N.ambient??={};var i_,r_="function $",HE=(W)=>t_(W,a_(W)),t_=(W,$)=>{let X=$.write(r_,4),Y=$.compile()();for(let G of W){if(G.precompilation)continue;if(G.traverseAllows=Y[`${G.id}Allows`].bind(Y),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=Y[`${G.id}Apply`].bind(Y),Y[`${G.id}Optimistic`])G.traverseOptimistic=Y[`${G.id}Optimistic`].bind(Y);G.precompilation=X}},a_=(W)=>new lY().return(W.reduce(($,X)=>{let Y=new h6({kind:"Allows"}).indent();X.compile(Y);let G=Y.write(`${X.id}Allows`),J=new h6({kind:"Apply"}).indent();X.compile(J);let H=J.write(`${X.id}Apply`),Q=`${$}${G},
124
124
  ${H},
125
- `;if(!X.hasKind("union"))return Q;let z=new b6({kind:"Allows",optimistic:!0}).indent();X.compile(z);let F=z.write(`${X.id}Optimistic`);return`${Q}${F},
125
+ `;if(!X.hasKind("union"))return Q;let z=new h6({kind:"Allows",optimistic:!0}).indent();X.compile(z);let T=z.write(`${X.id}Optimistic`);return`${Q}${T},
126
126
  `},`{
127
- `)+"}");class J9{config;resolvedConfig;name;get[f1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(W,$){if(this.config=y6(N.config,$),this.resolvedConfig=y6(N.resolvedConfig,$),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(N7).length}`,this.name in N7)A(`A Scope already named ${this.name} already exists`);N7[this.name]=this;let X=Object.entries(W).map((Y)=>this.preparseOwnAliasEntry(...Y));for(let[Y,J]of X){let G=Y;if(Y[0]==="#"){if(G=Y.slice(1),G in this.aliases)A(dU(G));this.aliases[G]=J}else{if(G in this.aliases)A(dU(Y));this.aliases[G]=J,this.exportedNames.push(G)}if(!d(J,"module")&&!d(J,"generic")&&!y2(J)){let H=this.preparseOwnDefinitionFormat(J,{alias:G});this.resolutions[G]=d(H,"root")?this.bindReference(H):this.createParseContext(H).id}}lU??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[lU.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?X0(N.intrinsic,(Y,J)=>Y.startsWith("json")?[]:[Y,this.bindReference(J)]):{}}cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(W){return W}generic=(...W)=>{let $=this;return(X,Y)=>new u2(W,Y?new tY(X):X,$,$,Y??null)};units=(W,$)=>{let X=[];for(let J of W)if(!X.includes(J))X.push(J);let Y=X.map((J)=>this.node("unit",{unit:J},$));return this.node("union",Y,{...$,prereduced:!0})};lazyResolutions=[];lazilyResolve(W,$){let X=this.node("alias",{reference:$??"synthetic",resolve:W},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(W,$)=>this.finalize(this.parseSchema(W,$));parseSchema=(W,$)=>this.node(p6(W),W,$);preparseNode(W,$,X){let Y=typeof W==="string"?W:p6($,W);if(x0($)&&$.kind===Y)return $;if(Y==="alias"&&!X?.prereduced){let{reference:H}=i6.implementation.normalize($,this);if(H.startsWith("$")){let Q=this.resolveRoot(H.slice(1));$=Q,Y=Q.kind}}else if(Y==="union"&&m1($,"object")){let H=XE($);if(H?.length===1)$=H[0],Y=p6($)}if(x0($)&&$.kind===Y)return $;let G=I$[Y].normalize?.($,this)??$;if(x0(G))return G.kind===Y?G:YE(Y,G.kind);return{...X,$:this,kind:Y,def:G,prefix:X.alias??Y}}bindReference(W){let $;if(x0(W))$=W.$===this?W:new W.constructor(W.attachments,this);else $=W.$===this?W:new u2(W.params,W.bodyDef,W.$,this,W.hkt);if(!this.resolved)Object.assign(this.referencesById,$.referencesById);return $}resolveRoot(W){return this.maybeResolveRoot(W)??A(q7(W))}maybeResolveRoot(W){let $=this.maybeResolve(W);if(d($,"generic"))return;return $}maybeResolveSubalias(W){return Z7(this.aliases,W)??Z7(this.ambient,W)}get ambient(){return N.ambient}maybeResolve(W){let $=this.resolutions[W];if($){if(typeof $!=="string")return this.bindReference($);let Y=P1[$];if(d(Y,"root"))return this.resolutions[W]=Y;if(d(Y,"context")){if(Y.phase==="resolving")return this.node("alias",{reference:`$${W}`},{prereduced:!0});if(Y.phase==="resolved")return K0(`Unexpected resolved context for was uncached by its scope: ${Y0(Y)}`);Y.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(Y.def,Y));return Y.phase="resolved",P1[J.id]=J,P1[Y.id]=J,this.resolutions[W]=J}return K0(`Unexpected nodesById entry for ${$}: ${Y0(Y)}`)}let X=this.aliases[W]??this.ambient?.[W];if(!X)return this.maybeResolveSubalias(W);if(X=this.normalizeRootScopeValue(X),d(X,"generic"))return this.resolutions[W]=this.bindReference(X);if(d(X,"module")){if(!X.root)A(sU(W));return this.resolutions[W]=this.bindReference(X.root)}return this.resolutions[W]=this.parse(X,{alias:W})}createParseContext(W){let $=W.id??Q7(W.prefix);return P1[$]=Object.assign(W,{[f1]:"context",$:this,id:$,phase:"unresolved"})}traversal(W){return new qW(W,this.resolvedConfig)}import(...W){return new x$(X0(this.export(...W),($,X)=>[`#${$}`,X]))}precompilation;_exportedResolutions;_exports;export(...W){if(!this._exports){this._exports={};for(let X of this.exportedNames){let Y=this.aliases[X];this._exports[X]=d(Y,"module")?R7(Y,this):oU(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=aU(this,this._exports),this._json=tU(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=rU(this.references);this.precompilation=X.write(iU,4),nU(this.references,X)}this.resolved=!0}let $=W.length?W:this.exportedNames;return new x$(X0($,(X,Y)=>[Y,this._exports[Y]]))}resolve(W){return this.export()[W]}node=(W,$,X={})=>{let Y=this.preparseNode(W,$,X);if(x0(Y))return this.bindReference(Y);let J=this.createParseContext(Y),G=z7(J),H=this.bindReference(G);return P1[J.id]=H};parse=(W,$={})=>this.finalize(this.parseDefinition(W,$));parseDefinition(W,$={}){if(d(W,"root"))return this.bindReference(W);let X=this.preparseOwnDefinitionFormat(W,$);if(d(X,"root"))return this.bindReference(X);let Y=this.createParseContext(X);P1[Y.id]=Y;let J=this.bindReference(this.parseOwnDefinitionFormat(W,Y));if(J.isCyclic)J=KU(J,Y.id);return P1[Y.id]=J,J}finalize(W){if(oU(W),!W.precompilation&&!this.resolvedConfig.jitless)JE(W.references);return W}}class S7 extends J9{parseOwnDefinitionFormat(W,$){return z7($)}preparseOwnDefinitionFormat(W,$){return this.preparseNode(p6(W),W,$)}preparseOwnAliasEntry(W,$){return[W,$]}normalizeRootScopeValue(W){return W}}var oU=(W)=>{let $=W.references.filter((X)=>X.hasKind("alias"));for(let X of $){Object.assign(X.referencesById,X.resolution.referencesById);for(let Y of W.references)if(X.id in Y.referencesById)Object.assign(Y.referencesById,X.referencesById)}return W},tU=(W)=>X0(W,($,X)=>[$,d(X,"root")||d(X,"generic")?X.json:d(X,"module")?tU(X):K0(`Unexpected resolution ${Y0(X)}`)]),Z7=(W,$)=>{let X=$.indexOf(".");if(X===-1)return;let Y=$.slice(0,X),J=W[Y];if(J===void 0)return;if(!d(J,"module"))return A(GE(Y));let G=$.slice(X+1),H=J[G];if(H===void 0)return Z7(J,G);if(d(H,"root")||d(H,"generic"))return H;if(d(H,"module"))return H.root??A(sU($));K0(`Unexpected resolution for alias '${$}': ${Y0(H)}`)},G9=(W,$)=>new S7(W,$),t6=new S7({});var aU=(W,$)=>{let X={};for(let Y in $){let J=$[Y];if(d(J,"module")){let G=aU(W,J),H=X0(G,(Q,z)=>[`${Y}.${Q}`,z]);Object.assign(X,H)}else if(d(J,"root")||d(J,"generic"))X[Y]=J;else K0(`Unexpected scope resolution ${Y0(J)}`)}return X},q7=(W)=>`'${W}' is unresolvable`,GE=(W)=>`'${W}' must reference a module to be accessed using dot syntax`,sU=(W)=>`Reference to submodule '${W}' must specify an alias`;t6.export();var{schema:B0,node:v$,defineSchema:On,generic:_W}=t6;var C7="^(?:0|[1-9]\\d*)$",HE=new RegExp(C7),En=d0(HE);var eU=G9({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();N.intrinsic={...eU};var Ww=G9({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:C7}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,Ww);var QE=G9({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),r={...eU,...Ww,...QE,emptyStructure:v$("structure",{},{prereduced:!0})};N.intrinsic={...r};var Xw=(W)=>typeof W==="string"&&W[0]==="d"&&(W[1]==="'"||W[1]==='"')&&W.at(-1)===W[1],$w=(W)=>W.toString()!=="Invalid Date",Yw=(W)=>W.slice(2,-1),k7=(W)=>`'${W}' could not be parsed by the Date constructor`,Jw=(W,$)=>zE(W,$),zE=(W,$)=>{let X=new Date(W);if($w(X))return X;let Y=bT(W);if(Y!==void 0){let J=new Date(Y);if($w(J))return J}return $?A($===!0?k7(W):$):void 0};var j7=(W,$)=>{let X=W.scanner.shiftUntil(FE[Hw[$]]);if(W.scanner.lookahead==="")return W.error(UE(X,$));if(W.scanner.shift(),$==="/"){try{new RegExp(X)}catch(Y){A(String(Y))}W.root=W.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(F1($,I7))W.root=W.ctx.$.node("unit",{unit:X});else{let Y=Jw(X,k7(X));W.root=W.ctx.$.node("unit",{meta:X,unit:Y})}},I7={"'":1,'"':1},Gw={"/":1,"'":1,'"':1},Hw={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},FE={"'":(W)=>W.lookahead==="'",'"':(W)=>W.lookahead==='"',"/":(W)=>W.lookahead==="/"},TE={'"':"double-quote","'":"single-quote","/":"forward slash"},UE=(W,$)=>`${$}${W} requires a closing ${TE[Hw[$]]}`;var Qw=(W)=>`Private type references should not include '#'. Use '${W}' instead.`,H9="Optional definitions like 'string?' are only valid as properties in an object or tuple",Q9="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var zw={">":!0,">=":!0},Fw={"<":!0,"<=":!0};var b$={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Tw=(W)=>`Unmatched )${W===""?"":` before ${W}`}`,z9=(W)=>`Missing ${W}`,Uw=(W,$)=>`Left bounds are only valid when paired with right bounds (try ...${$}${W})`,F9=(W)=>`Left-bounded expressions must specify their limits using < or <= (was ${W})`,ww=(W,$,X,Y)=>`An expression may have at most one left bound (parsed ${W}${b$[$]}, ${X}${b$[Y]})`;var _w=(W,$,X)=>Dw(W,$,X,[]),Dw=(W,$,X,Y)=>{let J=X.parseUntilFinalizer();if(Y.push(J.root),J.finalizer===">"){if(Y.length!==$.params.length)return X.error(f7(W,$.names,Y.map((G)=>G.expression)));return Y}if(J.finalizer===",")return Dw(W,$,X,Y);return J.error(z9(">"))},f7=(W,$,X)=>`${W}<${$.join(", ")}> requires exactly ${$.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var P7=(W)=>{let $=W.scanner.shiftUntilNextTerminator();if($==="keyof")W.addPrefix("keyof");else W.root=_E(W,$)},wE=(W,$,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(f7(W,$.names,[]));let J=_w(W,$,X);return $(...J)},_E=(W,$)=>DE(W,$)??ME(W,$)??W.error($===""?W.scanner.lookahead==="#"?Qw(W.shiftedByOne().scanner.shiftUntilNextTerminator()):x7(W):q7($)),DE=(W,$)=>{if(W.ctx.args?.[$]){let Y=W.ctx.args[$];if(typeof Y!=="string")return Y;return W.ctx.$.node("alias",{reference:Y},{prereduced:!0})}let X=W.ctx.$.maybeResolve($);if(d(X,"root"))return X;if(X===void 0)return;if(d(X,"generic"))return wE($,X,W);return A(`Unexpected resolution ${Y0(X)}`)},ME=(W,$)=>{let X=yT($);if(X!==void 0)return W.ctx.$.node("unit",{unit:X});let Y=gT($);if(Y!==void 0)return W.ctx.$.node("unit",{unit:Y})},x7=(W)=>{let $=W.previousOperator();return $?v7($,W.scanner.unscanned):VE(W.scanner.unscanned)},v7=(W,$="")=>`Token '${W}' requires a right operand${$?` before '${$}'`:""}`,VE=(W)=>`Expected an expression${W?` before '${W}'`:""}`;var b7=(W)=>W.scanner.lookahead===""?W.error(x7(W)):W.scanner.lookahead==="("?W.shiftedByOne().reduceGroupOpen():W.scanner.lookaheadIsIn(Gw)?j7(W,W.scanner.shift()):W.scanner.lookaheadIsIn(h2)?b7(W.shiftedByOne()):W.scanner.lookahead==="d"?W.scanner.nextLookahead in I7?j7(W,`${W.scanner.shift()}${W.scanner.shift()}`):P7(W):P7(W);class _2 extends p5{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in _2.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...h2};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(W,$)=>W===">"?$[0]==="="?$[1]==="=":$.trimStart()===""||F1($.trimStart()[0],_2.terminatingChars):W==="="?$[0]!=="=":W===","||W==="?"}var Vw=(W,$)=>{let X=OE(W,$);if(W.root.hasKind("unit")){if(typeof W.root.unit==="number"){W.reduceLeftBound(W.root.unit,X),W.unsetRoot();return}if(W.root.unit instanceof Date){let Y=`d'${W.root.description??W.root.unit.toISOString()}'`;W.unsetRoot(),W.reduceLeftBound(Y,X);return}}return AE(W,X)},Ow={"<":1,">":1,"=":1},OE=(W,$)=>W.scanner.lookaheadIs("=")?`${$}${W.scanner.shift()}`:$;var Mw=(W,$,X,Y)=>{if(X.extends(N.intrinsic.number)){if(typeof $!=="number")return A(y7(W,$,Y));return W==="=="?["min","max"]:W[0]===">"?["min"]:["max"]}if(X.extends(N.intrinsic.lengthBoundable)){if(typeof $!=="number")return A(y7(W,$,Y));return W==="=="?["exactLength"]:W[0]===">"?["minLength"]:["maxLength"]}if(X.extends(N.intrinsic.Date))return W==="=="?["after","before"]:W[0]===">"?["after"]:["before"];return A(GU(X.expression))},KE=(W)=>({rule:Xw(W.limit)?Yw(W.limit):W.limit,exclusive:W.comparator.length===1}),AE=(W,$)=>{let X=W.unsetRoot(),Y=W.scanner.location;W.parseOperand();let J=W.unsetRoot(),G=W.scanner.sliceChars(Y,W.scanner.location);if(W.root=X,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return W.error(y7($,G,"right"));let H=J.unit,Q=$.length===1,z=Mw($,typeof H==="number"?H:G,X,"right");for(let T of z)W.constrainRoot(T,$==="=="?{rule:H}:{rule:H,exclusive:Q});if(!W.branches.leftBound)return;if(!F1($,Fw))return W.error(F9($));let F=Mw(W.branches.leftBound.comparator,W.branches.leftBound.limit,X,"left");W.constrainRoot(F[0],KE(W.branches.leftBound)),W.branches.leftBound=null},y7=(W,$,X)=>`Comparator ${X==="left"?b$[W]:W} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${$})`;var Kw=(W)=>{W.scanner.shiftUntilNonWhitespace();let $=W.scanner.shiftUntilNextTerminator();W.root=W.root.brand($)};var Ew=(W)=>{let $=W.scanner.shiftUntilNextTerminator(),X=hT($,{errorOnFail:Aw($)});if(X===0)W.error(Aw(0));W.root=W.root.constrain("divisor",X)},Aw=(W)=>`% operator must be followed by a non-zero integer literal (was ${W})`;var h7=(W)=>{let $=W.scanner.shift();return $===""?W.finalize(""):$==="["?W.scanner.shift()==="]"?W.setRoot(W.root.array()):W.error(EE):$==="|"?W.scanner.lookahead===">"?W.shiftedByOne().pushRootToBranch("|>"):W.pushRootToBranch($):$==="&"?W.pushRootToBranch($):$===")"?W.finalizeGroup():_2.lookaheadIsFinalizing($,W.scanner.unscanned)?W.finalize($):F1($,Ow)?Vw(W,$):$==="%"?Ew(W):$==="#"?Kw(W):($ in h2)?h7(W):W.error(T9($))},T9=(W,$="")=>`'${W}' is not allowed here${$&&` (should be ${$})`}`,EE="Missing expected ']'";var Lw=(W)=>{let $=W.unsetRoot();W.parseOperand();let X=W.unsetRoot();if(!X.hasKind("unit"))return W.error(LE(X.expression));let Y=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[$,"=",Y]},LE=(W)=>`Default value '${W}' must a literal value`;var g7=(W,$)=>{let X=$.$.maybeResolveRoot(W);if(X)return X;if(W.endsWith("[]")){let G=$.$.maybeResolveRoot(W.slice(0,-2));if(G)return G.array()}let Y=new y$(new _2(W),$),J=BE(Y);if(Y.finalizer===">")A(T9(">"));return J},BE=(W)=>{W.parseOperand();let $=a6(W).root;if(!$)return K0(`Root was unexpectedly unset after parsing string '${W.scanner.scanned}'`);if(W.finalizer==="=")$=Lw(W);else if(W.finalizer==="?")$=[$,"?"];if(W.scanner.shiftUntilNonWhitespace(),W.scanner.lookahead)A(T9(W.scanner.lookahead));return $},a6=(W)=>{while(W.finalizer===void 0)RE(W);return W},RE=(W)=>W.hasRoot()?W.parseOperator():W.parseOperand();class y${root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(W,$){this.scanner=W,this.ctx=$}error(W){return A(W)}hasRoot(){return this.root!==void 0}setRoot(W){this.root=W}unsetRoot(){let W=this.root;return this.root=void 0,W}constrainRoot(...W){this.root=this.root.constrain(W[0],W[1])}finalize(W){if(this.groups.length)return this.error(z9(")"));this.finalizeBranches(),this.finalizer=W}reduceLeftBound(W,$){let X=b$[$];if(!F1(X,zw))return this.error(F9($));if(this.branches.leftBound)return this.error(ww(this.branches.leftBound.limit,this.branches.leftBound.comparator,W,X));this.branches.leftBound={comparator:X,limit:W}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let W=this.groups.pop();if(!W)return this.error(Tw(this.scanner.unscanned));this.branches=W}addPrefix(W){this.branches.prefixes.push(W)}applyPrefixes(){while(this.branches.prefixes.length){let W=this.branches.prefixes.pop();this.root=W==="keyof"?this.root.keyof():K0(`Unexpected prefix '${W}'`)}}pushRootToBranch(W){this.assertRangeUnset(),this.applyPrefixes();let $=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd($)??$,W==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,W==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return a6(new y$(this.scanner,this.ctx))}parseOperator(){return h7(this)}parseOperand(){return b7(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Uw(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var NE="An empty string is not a valid generic parameter name",U9=(W,$,X)=>{W.shiftUntilNonWhitespace();let Y=W.shiftUntilNextTerminator();if(Y===""){if(W.lookahead===""&&$.length)return $;return A(NE)}return W.shiftUntilNonWhitespace(),ZE(W,Y,$,X)},Bw="extends ",ZE=(W,$,X,Y)=>{if(W.shiftUntilNonWhitespace(),W.unscanned.startsWith(Bw))W.jumpForward(Bw.length);else{if(W.lookahead===",")W.shift();return X.push($),U9(W,X,Y)}let J=a6(new y$(W,Y));return X.push([$,J.root]),U9(W,X,Y)};class m7 extends SW{$;constructor(W){super((...$)=>new s6(W)(...$),{bind:W});this.$=W}in(W){return new s6(this.$,W===void 0?void 0:this.$.parse(W))}at(W,$){return new s6(this.$).at(W,$)}case(W,$){return new s6(this.$).case(W,$)}}class s6 extends SW{$;in;key;branches=[];constructor(W,$){super((X)=>this.caseEntries(Object.entries(X).map(([Y,J])=>Y==="default"?[Y,J]:[this.$.parse(Y),J])));this.$=W,this.in=$}at(W,$){if(this.key)A(qE);if(this.branches.length)A(SE);return this.key=W,$?this.match($):this}case(W,$){return this.caseEntry(this.$.parse(W),$)}caseEntry(W,$){let Y=(this.key?this.$.parse({[this.key]:W}):W).pipe($);return this.branches.push(Y),this}match(W){return this(W)}strings(W){return this.caseEntries(Object.entries(W).map(([$,X])=>$==="default"?[$,X]:[this.$.node("unit",{unit:$}),X]))}caseEntries(W){for(let $=0;$<W.length;$++){let[X,Y]=W[$];if(X==="default"){if($!==W.length-1)A("default may only be specified as the last key of a switch definition");return this.default(Y)}if(typeof Y!=="function")return A(`Value for case "${X}" must be a function (was ${z1(Y)})`);this.caseEntry(X,Y)}return this}default(W){if(typeof W==="function")this.case(r.unknown,W);let $={branches:this.branches,ordered:!0};if(W==="never"||W==="assert")$.meta={onFail:Rw};let X=this.$.node("union",$);if(!this.in)return this.$.finalize(X);let Y=this.in.pipe(X);if(W==="never"||W==="assert")Y=Y.configureReferences({onFail:Rw},"self");return this.$.finalize(Y)}}var Rw=(W)=>W.throw(),SE="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",qE="At most one key matcher may be specified per expression";var w9=(W,$)=>{if(k0(W)){if(W[1]==="=")return[$.$.parseOwnDefinitionFormat(W[0],$),"=",W[2]];if(W[1]==="?")return[$.$.parseOwnDefinitionFormat(W[0],$),"?"]}return _9(W,$)},Nw="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Zw="Only required keys may specify default values, e.g. { value: 'number = 0' }";var Sw=(W,$)=>{let X,Y={},J=R8(W);for(let[H,Q]of J){let z=jE(H);if(z.kind==="spread"){if(!cW(Y))return A(kE);let V=$.$.parseOwnDefinitionFormat(Q,$);if(V.equals(r.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(r.object))return A(IE(V.expression));X=V.structure;continue}if(z.kind==="undeclared"){if(Q!=="reject"&&Q!=="delete"&&Q!=="ignore")A(CE(Q));Y.undeclared=Q;continue}let F=w9(Q,$),T=z;if(z.kind==="required"){if(!k0(F))p7(Y,"required",{key:z.normalized,value:F},$);else p7(Y,"optional",F[1]==="="?{key:z.normalized,value:F[0],default:F[2]}:{key:z.normalized,value:F[0]},$);continue}if(k0(F)){if(F[1]==="?")A(Nw);if(F[1]==="=")A(Zw)}if(z.kind==="optional"){p7(Y,"optional",{key:z.normalized,value:F},$);continue}let U=$.$.parseOwnDefinitionFormat(T.normalized,$),_=Y9(U,F,$.$);if(_.index)Y.index=D0(Y.index,_.index);if(_.required)Y.required=D0(Y.required,_.required)}let G=$.$.node("structure",Y);return $.$.parseSchema({domain:"object",structure:X?.merge(G)??G})},p7=(W,$,X,Y)=>{W[$]=D0(W[$],Y.$.node($,X))},CE=(W)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${Y0(W)})`,kE="Spread operator may only be used as the first key in an object",jE=(W)=>typeof W==="symbol"?{kind:"required",normalized:W}:W.at(-1)==="?"?W.at(-2)===j6?{kind:"required",normalized:`${W.slice(0,-2)}?`}:{kind:"optional",normalized:W.slice(0,-1)}:W[0]==="["&&W.at(-1)==="]"?{kind:"index",normalized:W.slice(1,-1)}:W[0]===j6&&W[1]==="["&&W.at(-1)==="]"?{kind:"required",normalized:W.slice(1)}:W==="..."?{kind:"spread"}:W==="+"?{kind:"undeclared"}:{kind:"required",normalized:W==="\\..."?"...":W==="\\+"?"+":W},IE=(W)=>`Spread operand must resolve to an object literal type (was ${W})`;var Cw=(W,$)=>pE(W)?fw[W[0]](W,$):gE(W)?Iw[W[1]](W,$):null,fE=(W,$)=>$.$.parseOwnDefinitionFormat(W[1],$).keyof(),u7=(W,$)=>{if(W[2]===void 0)return A(v7(W[1],""));let X=$.$.parseOwnDefinitionFormat(W[0],$),Y=$.$.parseOwnDefinitionFormat(W[2],$);if(W[1]==="|")return $.$.node("union",{branches:[X,Y]});let J=W[1]==="&"?d1(X,Y,$.$):m6(X,Y,$.$);if(J instanceof P)return J.throw();return J},PE=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).array(),xE=(W,$)=>{if(typeof W[2]!=="function")return A(kw("=>",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).pipe(W[2])},kw=(W,$)=>`${W===":"?"Narrow":"Morph"} expression requires a function following '${W}' (was ${typeof $})`,vE=(W,$)=>{if(typeof W[2]!=="function")return A(kw(":",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).constrain("predicate",W[2])},bE=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).configureReferences(W[2],"shallow"),jw=(W)=>W,yE=jw({"[]":PE,"?":()=>A(H9)}),hE=jw({"|":u7,"&":u7,":":vE,"=>":xE,"|>":u7,"@":bE,"=":()=>A(Q9)}),Iw={...yE,...hE},gE=(W)=>Iw[W[1]]!==void 0,mE=(W)=>W,fw=mE({keyof:fE,instanceof:(W,$)=>{if(typeof W[1]!=="function")return A(qw(C6(W[1])));let X=W.slice(1).map((Y)=>typeof Y==="function"?$.$.node("proto",{proto:Y}):A(qw(C6(Y))));return X.length===1?X[0]:$.$.node("union",{branches:X})},"===":(W,$)=>$.$.units(W.slice(1))}),pE=(W)=>fw[W[0]]!==void 0,qw=(W)=>`Expected a constructor following 'instanceof' operator (was ${W})`;var vw=(W,$)=>{let X=[{}],Y=0;while(Y<W.length){let J=!1;if(W[Y]==="..."&&Y<W.length-1)J=!0,Y++;let G=w9(W[Y],$),[H,Q,z]=!k0(G)?[G]:G;if(Y++,J){if(!H.extends(N.intrinsic.Array))return A(dE(H.expression));X=X.flatMap((F)=>H.distribute((T)=>cE(oY(F),T)))}else X=X.map((F)=>{if(Q==="?")return bw(F,H);if(Q==="=")return uE(F,H,z);return c7(F,H)})}return $.$.parseSchema(X.map((J)=>cW(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},c7=(W,$)=>{if(W.defaultables||W.optionals)return A(W.variadic?E7:lE);if(W.variadic)W.postfix=D0(W.postfix,$);else W.prefix=D0(W.prefix,$);return W},bw=(W,$)=>{if(W.variadic)return A(yw);return W.optionals=D0(W.optionals,$),W},uE=(W,$,X)=>{if(W.variadic)return A(yw);if(W.optionals)return A(oE);return W.defaultables=D0(W.defaultables,[[$,X]]),W},Pw=(W,$)=>{if(W.postfix)A(xw);if(W.variadic){if(!W.variadic.equals($))A(xw)}else W.variadic=$.internal;return W},cE=(W,$)=>{let X=$.select({method:"find",kind:"sequence"});if(!X)return Pw(W,N.intrinsic.unknown);if(X.prefix)for(let Y of X.prefix)c7(W,Y);if(X.optionals)for(let Y of X.optionals)bw(W,Y);if(X.variadic)Pw(W,X.variadic);if(X.postfix)for(let Y of X.postfix)c7(W,Y);return W},dE=(W)=>`Spread element must be an array (was ${W})`,xw="A tuple may have at most one variadic element",lE="A required element may not follow an optional element",yw="An optional element may not follow a variadic element";var oE="A defaultable element may not follow an optional element without a default";var iE={},_9=(W,$)=>{if(typeof W==="string"){if($.args&&Object.keys($.args).some((Y)=>W.includes(Y)))return g7(W,$);let X=iE[$.$.name]??={};return X[W]??=g7(W,$)}return m1(W,"object")?nE(W,$):A(d7(z1(W)))},nE=(W,$)=>{let X=q6(W);switch(X){case void 0:if(d(W,"root"))return W;return Sw(W,$);case"Array":return rE(W,$);case"RegExp":return $.$.node("intersection",{domain:"string",pattern:W},{prereduced:!0});case"Function":{let Y=y2(W)?W():W;if(d(Y,"root"))return Y;return A(d7("Function"))}default:return A(d7(X??Y0(W)))}},rE=(W,$)=>Cw(W,$)??vw(W,$),d7=(W)=>`Type definitions must be strings or objects (was ${W})`;class l7 extends SW{constructor(W){let $=Object.assign({errors:u1,hkt:R1,$:W,raw:W.parse,module:W.constructor.module,scope:W.constructor.scope,define:W.define,match:W.match,generic:W.generic,schema:W.schema,keywords:W.ambient,unit:W.unit,enumerated:W.enumerated,instanceOf:W.instanceOf,valueOf:W.valueOf,or:W.or,and:W.and,merge:W.merge,pipe:W.pipe},W.ambientAttachments);super((...X)=>{if(X.length===1)return W.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let Y=X[0].slice(1,-1),J=W.parseGenericParams(Y,{});return new u2(J,X[1],W,W,null)}return W.parse(X)},{bind:W,attach:$})}}var h$=N;class D9 extends J9{get ambientAttachments(){if(!h$.typeAttachments)return;return this.cacheGetter("ambientAttachments",X0(h$.typeAttachments,(W,$)=>[W,this.bindReference($)]))}preparseOwnAliasEntry(W,$){let X=W.indexOf("<");if(X===-1){if(d($,"module")||d($,"generic"))return[W,$];let G=this.name==="ark"?W:W==="root"?this.name:`${this.name}.${W}`,H=this.resolvedConfig.keywords?.[G];if(H)$=[$,"@",H];return[W,$]}if(W.at(-1)!==">")A("'>' must be the last character of a generic declaration in a scope");let Y=W.slice(0,X),J=W.slice(X+1,-1);return[Y,()=>{let G=this.parseGenericParams(J,{alias:Y});return XU(G,$,this)}]}parseGenericParams(W,$){return U9(new _2(W),[],this.createParseContext({...$,def:W,prefix:"generic"}))}normalizeRootScopeValue(W){if(y2(W)&&!d(W,"generic"))return W();return W}preparseOwnDefinitionFormat(W,$){return{...$,def:W,prefix:$.alias??"type"}}parseOwnDefinitionFormat(W,$){if(!($.alias&&($.alias in this.aliases))&&!$.args)$.args={this:$.id};let Y=_9(W,$);if(k0(Y)){if(Y[1]==="=")return A(Q9);if(Y[1]==="?")return A(H9)}return Y}unit=(W)=>this.units([W]);valueOf=(W)=>this.units(BT(W));enumerated=(...W)=>this.units(W);instanceOf=(W)=>this.node("proto",{proto:W},{prereduced:!0});or=(...W)=>this.schema(W.map(($)=>this.parse($)));and=(...W)=>W.reduce(($,X)=>$.and(this.parse(X)),this.intrinsic.unknown);merge=(...W)=>W.reduce(($,X)=>$.merge(this.parse(X)),this.intrinsic.object);pipe=(...W)=>this.intrinsic.unknown.pipe(...W);match=new m7(this);declare=()=>({type:this.type});define(W){return W}type=new l7(this);static scope=(W,$={})=>new D9(W,$);static module=(W,$={})=>this.scope(W,$).export()}var o7=Object.assign(D9.scope,{define:(W)=>W}),F0=D9;class hw extends R1{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var tE=_W(["base",r.object],["props",r.object])((W)=>W.base.merge(W.props),hw),gw=F0.module({Key:r.key,Merge:tE});class mw extends R1{}var aE=_W("element")((W)=>{let $=W.element.exclude(r.Array),X=$.array();return $.rawOr(X).pipe(b2).distribute((Y)=>Y.assertHasKind("morph").declareOut(X),B0)},mw),pw=F0.module({root:r.Array,readonly:"root",index:r.nonNegativeIntegerString,liftFrom:aE},{name:"Array"});var i7=B0(["string",Z8.FileConstructor]),sE=i7.rawOr(i7.array()),uw=B0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:sE}}),cw=F0.module({root:["instanceof",FormData],value:i7,parsed:uw,parse:B0({in:FormData,morphs:(W)=>{let $={};for(let[X,Y]of W)if(X in $){let J=$[X];if(typeof J==="string"||J instanceof Z8.FileConstructor)$[X]=[J,Y];else J.push(Y)}else $[X]=Y;return $},declaredOut:uw})},{name:"FormData"});var dw=F0.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var eE={Boolean:1,Number:1,String:1},lw=F0.module({...X0({...P5,...v5},(W,$)=>(W in eE)?[]:[W,["instanceof",$]]),Array:pw,TypedArray:dw,FormData:cw});var WL=B0({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),$L=B0({domain:"number",divisor:1}),M9=F0.module({root:r.number,integer:$L,epoch:WL,safe:B0({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var g0=(W,$,X)=>{let Y={domain:"string",pattern:{rule:W.source,flags:W.flags,meta:$}};if(X)Y.meta={format:X};return v$("intersection",Y)},ow=g0(I6,"a well-formed integer string"),J_=F0.module({root:ow,parse:B0({in:ow,morphs:(W,$)=>{let X=Number.parseInt(W);return Number.isSafeInteger(X)?X:$.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:r.integer})},{name:"string.integer"}),XL=g0(/^[\dA-Fa-f]+$/,"hex characters only"),YL=F0.module({root:g0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:g0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),iw=g0(/^[A-Z].*$/,"capitalized"),JL=F0.module({root:B0({in:"string",morphs:(W)=>W.charAt(0).toUpperCase()+W.slice(1),declaredOut:iw}),preformatted:iw},{name:"string.capitalize"}),GL=(W)=>{let $=W.replaceAll(/[ -]+/g,""),X=0,Y,J,G=!1;for(let H=$.length-1;H>=0;H--){if(Y=$.substring(H,H+1),J=Number.parseInt(Y,10),G)J*=2,X+=J>=10?J%10+1:J;else X+=J;G=!G}return!!(X%10===0?$:!1)},HL=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,QL=B0({domain:"string",pattern:{meta:"a credit card number",rule:HL.source},predicate:{meta:"a credit card number",predicate:GL}});var zL=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var FL=(W)=>!Number.isNaN(new Date(W).valueOf()),nw=B0({domain:"string",predicate:{meta:"a parsable date",predicate:FL}}).assertHasKind("intersection"),rw=J_.root.internal.narrow((W,$)=>{let X=Number.parseInt(W),Y=M9.epoch(X);if(Y instanceof u1)return $.errors.merge(Y),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),TL=F0.module({root:rw,parse:B0({in:rw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.epoch"}),tw=g0(zL,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),UL=F0.module({root:tw,parse:B0({in:tw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.iso"}),wL=F0.module({root:nw,parse:B0({declaredIn:nw,in:"string",morphs:(W,$)=>{let X=new Date(W);if(Number.isNaN(X.valueOf()))return $.error("a parsable date");return X},declaredOut:r.Date}),iso:UL,epoch:TL},{name:"string.date"}),_L=g0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),aw="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",c2=`(${aw}[.]){3}${aw}`,DL=new RegExp(`^${c2}$`),s0="(?:[0-9a-fA-F]{1,4})",ML=new RegExp(`^((?:${s0}:){7}(?:${s0}|:)|(?:${s0}:){6}(?:${c2}|:${s0}|:)|(?:${s0}:){5}(?::${c2}|(:${s0}){1,2}|:)|(?:${s0}:){4}(?:(:${s0}){0,1}:${c2}|(:${s0}){1,3}|:)|(?:${s0}:){3}(?:(:${s0}){0,2}:${c2}|(:${s0}){1,4}|:)|(?:${s0}:){2}(?:(:${s0}){0,3}:${c2}|(:${s0}){1,5}|:)|(?:${s0}:){1}(?:(:${s0}){0,4}:${c2}|(:${s0}){1,6}|:)|(?::((?::${s0}){0,5}:${c2}|(?::${s0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),VL=F0.module({root:["v4 | v6","@","an IP address"],v4:g0(DL,"an IPv4 address","ipv4"),v6:g0(ML,"an IPv6 address","ipv6")},{name:"string.ip"}),g$="a JSON string",G_=(W)=>{if(!(W instanceof SyntaxError))throw W;return`must be ${g$} (${W})`},OL=B0({meta:g$,domain:"string",predicate:{meta:g$,predicate:(W,$)=>{try{return JSON.parse(W),!0}catch(X){return $.reject({code:"predicate",expected:g$,problem:G_(X)})}}}}),KL=(W,$)=>{if(W.length===0)return $.error({code:"predicate",expected:g$,actual:"empty"});try{return JSON.parse(W)}catch(X){return $.error({code:"predicate",expected:g$,problem:G_(X)})}},AL=F0.module({root:OL,parse:B0({meta:"safe JSON string parser",in:"string",morphs:KL,declaredOut:r.jsonObject})},{name:"string.json"}),sw=g0(/^[a-z]*$/,"only lowercase letters"),EL=F0.module({root:B0({in:"string",morphs:(W)=>W.toLowerCase(),declaredOut:sw}),preformatted:sw},{name:"string.lower"}),H_=["NFC","NFD","NFKC","NFKD"],e6=X0(H_,(W,$)=>[$,B0({domain:"string",predicate:(X)=>X.normalize($)===X,meta:`${$}-normalized unicode`})]),V9=X0(H_,(W,$)=>[$,B0({in:"string",morphs:(X)=>X.normalize($),declaredOut:e6[$]})]),LL=F0.module({root:V9.NFC,preformatted:e6.NFC},{name:"string.normalize.NFC"}),BL=F0.module({root:V9.NFD,preformatted:e6.NFD},{name:"string.normalize.NFD"}),RL=F0.module({root:V9.NFKC,preformatted:e6.NFKC},{name:"string.normalize.NFKC"}),NL=F0.module({root:V9.NFKD,preformatted:e6.NFKD},{name:"string.normalize.NFKD"}),ZL=F0.module({root:"NFC",NFC:LL,NFD:BL,NFKC:RL,NFKD:NL},{name:"string.normalize"}),ew=g0(cY,"a well-formed numeric string"),SL=F0.module({root:ew,parse:B0({in:ew,morphs:(W)=>Number.parseFloat(W),declaredOut:r.number})},{name:"string.numeric"}),W_="a regex pattern",qL=B0({domain:"string",predicate:{meta:W_,predicate:(W,$)=>{try{return new RegExp(W),!0}catch(X){return $.reject({code:"predicate",expected:W_,problem:String(X)})}}},meta:{format:"regex"}}),CL=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,kL=g0(CL,"a semantic version (see https://semver.org/)"),$_=g0(/^\S.*\S$|^\S?$/,"trimmed"),jL=F0.module({root:B0({in:"string",morphs:(W)=>W.trim(),declaredOut:$_}),preformatted:$_},{name:"string.trim"}),X_=g0(/^[A-Z]*$/,"only uppercase letters"),IL=F0.module({root:B0({in:"string",morphs:(W)=>W.toUpperCase(),declaredOut:X_}),preformatted:X_},{name:"string.upper"}),fL=(W)=>{if(URL.canParse)return URL.canParse(W);try{return new URL(W),!0}catch{return!1}},Y_=B0({domain:"string",predicate:{meta:"a URL string",predicate:fL},meta:{format:"uri"}}),PL=F0.module({root:Y_,parse:B0({declaredIn:Y_,in:"string",morphs:(W,$)=>{try{return new URL(W)}catch{return $.error("a URL string")}},declaredOut:B0(URL)})},{name:"string.url"}),xL=F0.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:g0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:g0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:g0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:g0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:g0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:g0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:g0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:g0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Q_=F0.module({root:r.string,alpha:g0(/^[A-Za-z]*$/,"only letters"),alphanumeric:g0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:XL,base64:YL,capitalize:JL,creditCard:QL,date:wL,digits:g0(/^\d*$/,"only digits 0-9"),email:_L,integer:J_,ip:VL,json:AL,lower:EL,normalize:ZL,numeric:SL,regex:qL,semver:kL,trim:jL,upper:IL,url:PL,uuid:xL},{name:"string"});var z_=F0.module({bigint:r.bigint,boolean:r.boolean,false:r.false,never:r.never,null:r.null,number:r.number,object:r.object,string:r.string,symbol:r.symbol,true:r.true,unknown:r.unknown,undefined:r.undefined}),F_=F0.module({root:r.unknown,any:r.unknown},{name:"unknown"}),vL=F0.module({root:r.jsonObject,stringify:v$("morph",{in:r.jsonObject,morphs:(W)=>JSON.stringify(W),declaredOut:r.string})},{name:"object.json"}),T_=F0.module({root:r.object,json:vL},{name:"object"});class U_ extends R1{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var bL=_W(["K",r.key],"V")((W)=>({domain:"object",index:{signature:W.K,value:W.V}}),U_);class w_ extends R1{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var yL=_W(["T",r.object],["K",r.key])((W)=>W.T.pick(W.K),w_);class __ extends R1{description='omit a set of properties from an object like `Omit(User, "age")`'}var hL=_W(["T",r.object],["K",r.key])((W)=>W.T.omit(W.K),__);class D_ extends R1{description="make all named properties of an object optional like `Partial(User)`"}var gL=_W(["T",r.object])((W)=>W.T.partial(),D_);class M_ extends R1{description="make all named properties of an object required like `Required(User)`"}var mL=_W(["T",r.object])((W)=>W.T.required(),M_);class V_ extends R1{description='exclude branches of a union like `Exclude("boolean", "true")`'}var pL=_W("T","U")((W)=>W.T.exclude(W.U),V_);class O_ extends R1{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var uL=_W("T","U")((W)=>W.T.extract(W.U),O_),K_=F0.module({Exclude:pL,Extract:uL,Omit:hL,Partial:gL,Pick:yL,Record:bL,Required:mL});var d2=o7({...z_,...K_,...lw,...gw,string:Q_,number:M9,object:T_,unknown:F_},{prereducedAliases:!0,name:"ark"}),T1=d2.export();Object.assign(h$.ambient,T1);h$.typeAttachments={string:T1.string.root,number:T1.number.root,bigint:T1.bigint,boolean:T1.boolean,symbol:T1.symbol,undefined:T1.undefined,null:T1.null,object:T1.object.root,unknown:T1.unknown.root,false:T1.false,true:T1.true,never:T1.never,arrayIndex:T1.Array.index,Key:T1.Key,Record:T1.Record,Array:T1.Array.root,Date:T1.Date};var kW=Object.assign(d2.type,h$.typeAttachments),cL=d2.match,dL=d2.generic,ca=d2.schema,lL=d2.define,oL=d2.declare;var iL="__vite_start_time"in globalThis,nL=typeof window!=="undefined",Qs="vitest"in globalThis,D2=kW("string"),A_=kW('"true" | "false" | undefined'),M2=j5({isServer:!iL&&!nL,server:{CI:kW("string | undefined").pipe(Boolean),POSTGRES_USER:D2,POSTGRES_PASSWORD:D2,POSTGRES_DATABASE:D2,POSTGRES_HOST:D2,POSTGRES_PORT:D2.pipe((W)=>Number.parseInt(W,10)),BACKEND_PORT:D2.pipe((W)=>Number.parseInt(W,10)),RUN_WORKERS_FROM_SOURCE:A_.pipe((W)=>W==="true"),FRONTEND_PORT:D2.pipe((W)=>Number.parseInt(W,10)),FRONTEND_ORIGINS:D2.pipe.try((W)=>JSON.parse(W),kW("string[]")),API_KEY_OPENAI:kW("string | undefined"),API_KEY_RESEND:kW("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:D2,VITE_DEV_FRONTEND_HOST:kW("string | undefined"),VITE_DEV_HTTPS:A_.pipe((W)=>W==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var r7={};xD(r7,{users:()=>C8,untrackedUserColumnNames:()=>rL,twoFactorMethod:()=>N_,trackedUserColumnName:()=>tL,trackableUserColumnNames:()=>B_,signInHistory:()=>sL,role:()=>L_,players:()=>n7,passwordResetAttempts:()=>eL,games:()=>O9,banishedIps:()=>K9,accountActions:()=>aL,accountAction:()=>R_});function E_(W){return M`lower(${W})`}var L_=J6("role",["admin","user"]),C8=P2("users",{id:zW().primaryKey().defaultRandom(),username:j1({length:16}).notNull(),emailOffered:j1({length:254}).notNull(),emailVerified:j1({length:254}),password:j1({length:254}),createdAt:NW({withTimezone:!0}).notNull().defaultNow(),createdIp:j1({length:45}).notNull(),isActive:T6().notNull().default(!1),verifiedAt:NW({withTimezone:!0}),userRole:L_().default("user")},(W)=>[Z5("usernameUniqueIndex").on(E_(W.username)),Z5("emailVerifiedUniqueIndex").on(E_(W.emailVerified))]),rL=["id","createdAt","createdIp","isActive","verifiedAt"],B_=["username","emailOffered","emailVerified","password","userRole"],tL=J6("trackedUserColumnName",B_),R_=J6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),aL=P2("accountActions",{userId:zW().references(()=>C8.id).primaryKey(),action:R_().notNull(),code:j1({length:254}).notNull(),wrongCodeCount:U6().notNull().default(0),expiresAt:NW({withTimezone:!0}).notNull()}),O9=P2("games",{id:zW().primaryKey().defaultRandom()}),n7=P2("players",{userId:zW().notNull().references(()=>C8.id,{onDelete:"cascade"}),gameId:zW().notNull().references(()=>O9.id,{onDelete:"cascade"}),score:U6().notNull()},(W)=>[UF({name:"players_userId_gameId_pk",columns:[W.userId,W.gameId]})]),sL=P2("signInHistory",{id:zW().primaryKey().defaultRandom(),userId:zW().references(()=>C8.id,{onDelete:"cascade"}),signInTime:NW({withTimezone:!0}).notNull().defaultNow(),ipAddress:j1({length:45}).notNull(),userAgent:j1({length:1024}),successful:T6().notNull().default(!1)}),N_=J6("twoFactorMethod",["email","phone"]),eL=P2("passwordResetAttempts",{id:zW().primaryKey().defaultRandom(),userId:zW().notNull().references(()=>C8.id,{onDelete:"cascade"}),requestedIp:j1({length:45}).notNull(),requestedAt:NW({withTimezone:!0}).notNull().defaultNow(),succeededIp:j1({length:45}),succeededAt:NW({withTimezone:!0}),verificationMethod:N_().notNull()}),K9=P2("banishedIps",{ip:j1({length:45}).primaryKey(),reason:j1({length:2048}).notNull(),banishedAt:NW({withTimezone:!0}).notNull().defaultNow(),banishedUntil:NW({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class t7{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(WB.resolve(__dirname,"notify_update.sql"));let W=[w1(C8),w1(O9),w1(n7)];await this.sql`SELECT create_notify_triggers(${this.sql.array(W)})`,await this.sql.listen("table_update",($)=>{let X=$.split(","),Y=X[0],J=X[1],G=`${Y}("${J}")`;if(this.observers.has(G))this.observers.get(G).next(G)})}constructor(W=!1,$={host:M2.POSTGRES_HOST,port:M2.POSTGRES_PORT,user:M2.POSTGRES_USER,password:M2.POSTGRES_PASSWORD,database:M2.POSTGRES_DATABASE}){this.options=$,this.sql=K$($),this.drizzle=pY(this.sql,{schema:r7,logger:W})}observe(W,$){if(!this.observers.has(W))this.observers.set(W,new S0);this.observers.get(W).subscribe("SINGLETON",$)}}import{resolve as YB}from"path";import{existsSync as a7,mkdirSync as Z_,readFileSync as $B,readdirSync as S_,rmSync as q_,statSync as C_,writeFileSync as XB}from"fs";import{resolve as s7}from"path";var k_=class{rootDir;get initialized(){return a7(this.rootDir)}initialize(){if(!this.initialized)Z_(this.rootDir,{recursive:!0})}constructor(W){if(this.rootDir=W.path,W.eagerInit)this.initialize()}getItem(W){let $=s7(this.rootDir,W);if(a7($))return $B($,"utf-8");return null}setItem(W,$){this.initialize();let X=s7(this.rootDir,W);XB(X,$)}removeItem(W){let $=s7(this.rootDir,W);if(a7($))this.initialize(),q_($)}key(W){return S_(this.rootDir).sort((Y,J)=>{let G=C_(Y);return C_(J).ctimeMs-G.ctimeMs})[W]??null}clear(){q_(this.rootDir,{recursive:!0}),Z_(this.rootDir,{recursive:!0})}get length(){return S_(this.rootDir).length}};var e7=new k_({path:YB(process.cwd(),"storage")});import*as A9 from"fs";import*as j_ from"readline";function JB(W){let X=W.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(Y,J,G,H,Q)=>{let F={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[G];return`${H}-${F}-${J}T${Q}`});return new Date(X)}async function I_(W,$="/var/log/nginx/access.log",X=new Date){let Y=new Map;if(!A9.existsSync($))return W.error(`Log file not found: ${$}`),Y;let J=A9.createReadStream($),G=j_.createInterface({input:J,crlfDelay:Number.POSITIVE_INFINITY}),H=new Date(X.getTime()-3600000);return G.on("line",(Q)=>{let z=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,F=Q.match(z);if(F?.groups){let T=F.groups.ip,U=F.groups.dateTime,_=JB(U);if(!Number.isNaN(_.getTime())){if(_>=H&&_<=X){let V=Y.get(T);if(!V)V=[],Y.set(T,V);V.push(Q)}}else W.error(`Failed to parse date: ${U}`)}}),new Promise((Q,z)=>{G.on("error",(F)=>{z(F)}),G.on("close",()=>{Q(Y)})})}function f_(W){return W.toJsonSchema()}var GB=["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(`
128
- `);function P_(W){return GB+W.join(`
127
+ `)+"}");class G9{config;resolvedConfig;name;get[f1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(W,$){if(this.config=g6(N.config,$),this.resolvedConfig=g6(N.resolvedConfig,$),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(SG).length}`,this.name in SG)E(`A Scope already named ${this.name} already exists`);SG[this.name]=this;let X=Object.entries(W).map((Y)=>this.preparseOwnAliasEntry(...Y));for(let[Y,G]of X){let J=Y;if(Y[0]==="#"){if(J=Y.slice(1),J in this.aliases)E(o_(J));this.aliases[J]=G}else{if(J in this.aliases)E(o_(Y));this.aliases[J]=G,this.exportedNames.push(J)}if(!d(G,"module")&&!d(G,"generic")&&!m2(G)){let H=this.preparseOwnDefinitionFormat(G,{alias:J});this.resolutions[J]=d(H,"root")?this.bindReference(H):this.createParseContext(H).id}}i_??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[i_.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?Y0(N.intrinsic,(Y,G)=>Y.startsWith("json")?[]:[Y,this.bindReference(G)]):{}}cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(W){return W}generic=(...W)=>{let $=this;return(X,Y)=>new l2(W,Y?new tY(X):X,$,$,Y??null)};units=(W,$)=>{let X=[];for(let G of W)if(!X.includes(G))X.push(G);let Y=X.map((G)=>this.node("unit",{unit:G},$));return this.node("union",Y,{...$,prereduced:!0})};lazyResolutions=[];lazilyResolve(W,$){let X=this.node("alias",{reference:$??"synthetic",resolve:W},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(W,$)=>this.finalize(this.parseSchema(W,$));parseSchema=(W,$)=>this.node(c6(W),W,$);preparseNode(W,$,X){let Y=typeof W==="string"?W:c6($,W);if(x0($)&&$.kind===Y)return $;if(Y==="alias"&&!X?.prereduced){let{reference:H}=r6.implementation.normalize($,this);if(H.startsWith("$")){let Q=this.resolveRoot(H.slice(1));$=Q,Y=Q.kind}}else if(Y==="union"&&p1($,"object")){let H=GE($);if(H?.length===1)$=H[0],Y=c6($)}if(x0($)&&$.kind===Y)return $;let J=f4[Y].normalize?.($,this)??$;if(x0(J))return J.kind===Y?J:JE(Y,J.kind);return{...X,$:this,kind:Y,def:J,prefix:X.alias??Y}}bindReference(W){let $;if(x0(W))$=W.$===this?W:new W.constructor(W.attachments,this);else $=W.$===this?W:new l2(W.params,W.bodyDef,W.$,this,W.hkt);if(!this.resolved)Object.assign(this.referencesById,$.referencesById);return $}resolveRoot(W){return this.maybeResolveRoot(W)??E(kG(W))}maybeResolveRoot(W){let $=this.maybeResolve(W);if(d($,"generic"))return;return $}maybeResolveSubalias(W){return qG(this.aliases,W)??qG(this.ambient,W)}get ambient(){return N.ambient}maybeResolve(W){let $=this.resolutions[W];if($){if(typeof $!=="string")return this.bindReference($);let Y=x1[$];if(d(Y,"root"))return this.resolutions[W]=Y;if(d(Y,"context")){if(Y.phase==="resolving")return this.node("alias",{reference:`$${W}`},{prereduced:!0});if(Y.phase==="resolved")return K0(`Unexpected resolved context for was uncached by its scope: ${G0(Y)}`);Y.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(Y.def,Y));return Y.phase="resolved",x1[G.id]=G,x1[Y.id]=G,this.resolutions[W]=G}return K0(`Unexpected nodesById entry for ${$}: ${G0(Y)}`)}let X=this.aliases[W]??this.ambient?.[W];if(!X)return this.maybeResolveSubalias(W);if(X=this.normalizeRootScopeValue(X),d(X,"generic"))return this.resolutions[W]=this.bindReference(X);if(d(X,"module")){if(!X.root)E(Ww(W));return this.resolutions[W]=this.bindReference(X.root)}return this.resolutions[W]=this.parse(X,{alias:W})}createParseContext(W){let $=W.id??TG(W.prefix);return x1[$]=Object.assign(W,{[f1]:"context",$:this,id:$,phase:"unresolved"})}traversal(W){return new CW(W,this.resolvedConfig)}import(...W){return new v4(Y0(this.export(...W),($,X)=>[`#${$}`,X]))}precompilation;_exportedResolutions;_exports;export(...W){if(!this._exports){this._exports={};for(let X of this.exportedNames){let Y=this.aliases[X];this._exports[X]=d(Y,"module")?ZG(Y,this):n_(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=e_(this,this._exports),this._json=s_(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=a_(this.references);this.precompilation=X.write(r_,4),t_(this.references,X)}this.resolved=!0}let $=W.length?W:this.exportedNames;return new v4(Y0($,(X,Y)=>[Y,this._exports[Y]]))}resolve(W){return this.export()[W]}node=(W,$,X={})=>{let Y=this.preparseNode(W,$,X);if(x0(Y))return this.bindReference(Y);let G=this.createParseContext(Y),J=FG(G),H=this.bindReference(J);return x1[G.id]=H};parse=(W,$={})=>this.finalize(this.parseDefinition(W,$));parseDefinition(W,$={}){if(d(W,"root"))return this.bindReference(W);let X=this.preparseOwnDefinitionFormat(W,$);if(d(X,"root"))return this.bindReference(X);let Y=this.createParseContext(X);x1[Y.id]=Y;let G=this.bindReference(this.parseOwnDefinitionFormat(W,Y));if(G.isCyclic)G=E_(G,Y.id);return x1[Y.id]=G,G}finalize(W){if(n_(W),!W.precompilation&&!this.resolvedConfig.jitless)HE(W.references);return W}}class CG extends G9{parseOwnDefinitionFormat(W,$){return FG($)}preparseOwnDefinitionFormat(W,$){return this.preparseNode(c6(W),W,$)}preparseOwnAliasEntry(W,$){return[W,$]}normalizeRootScopeValue(W){return W}}var n_=(W)=>{let $=W.references.filter((X)=>X.hasKind("alias"));for(let X of $){Object.assign(X.referencesById,X.resolution.referencesById);for(let Y of W.references)if(X.id in Y.referencesById)Object.assign(Y.referencesById,X.referencesById)}return W},s_=(W)=>Y0(W,($,X)=>[$,d(X,"root")||d(X,"generic")?X.json:d(X,"module")?s_(X):K0(`Unexpected resolution ${G0(X)}`)]),qG=(W,$)=>{let X=$.indexOf(".");if(X===-1)return;let Y=$.slice(0,X),G=W[Y];if(G===void 0)return;if(!d(G,"module"))return E(QE(Y));let J=$.slice(X+1),H=G[J];if(H===void 0)return qG(G,J);if(d(H,"root")||d(H,"generic"))return H;if(d(H,"module"))return H.root??E(Ww($));K0(`Unexpected resolution for alias '${$}': ${G0(H)}`)},J9=(W,$)=>new CG(W,$),s6=new CG({});var e_=(W,$)=>{let X={};for(let Y in $){let G=$[Y];if(d(G,"module")){let J=e_(W,G),H=Y0(J,(Q,z)=>[`${Y}.${Q}`,z]);Object.assign(X,H)}else if(d(G,"root")||d(G,"generic"))X[Y]=G;else K0(`Unexpected scope resolution ${G0(G)}`)}return X},kG=(W)=>`'${W}' is unresolvable`,QE=(W)=>`'${W}' must reference a module to be accessed using dot syntax`,Ww=(W)=>`Reference to submodule '${W}' must specify an alias`;s6.export();var{schema:R0,node:y4,defineSchema:xn,generic:DW}=s6;var jG="^(?:0|[1-9]\\d*)$",zE=new RegExp(jG),yn=d0(zE);var $w=J9({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();N.intrinsic={...$w};var Xw=J9({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:jG}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,Xw);var TE=J9({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),r={...$w,...Xw,...TE,emptyStructure:y4("structure",{},{prereduced:!0})};N.intrinsic={...r};var Gw=(W)=>typeof W==="string"&&W[0]==="d"&&(W[1]==="'"||W[1]==='"')&&W.at(-1)===W[1],Yw=(W)=>W.toString()!=="Invalid Date",Jw=(W)=>W.slice(2,-1),IG=(W)=>`'${W}' could not be parsed by the Date constructor`,Hw=(W,$)=>FE(W,$),FE=(W,$)=>{let X=new Date(W);if(Yw(X))return X;let Y=hF(W);if(Y!==void 0){let G=new Date(Y);if(Yw(G))return G}return $?E($===!0?IG(W):$):void 0};var PG=(W,$)=>{let X=W.scanner.shiftUntil(_E[zw[$]]);if(W.scanner.lookahead==="")return W.error(UE(X,$));if(W.scanner.shift(),$==="/"){try{new RegExp(X)}catch(Y){E(String(Y))}W.root=W.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(T1($,fG))W.root=W.ctx.$.node("unit",{unit:X});else{let Y=Hw(X,IG(X));W.root=W.ctx.$.node("unit",{meta:X,unit:Y})}},fG={"'":1,'"':1},Qw={"/":1,"'":1,'"':1},zw={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},_E={"'":(W)=>W.lookahead==="'",'"':(W)=>W.lookahead==='"',"/":(W)=>W.lookahead==="/"},wE={'"':"double-quote","'":"single-quote","/":"forward slash"},UE=(W,$)=>`${$}${W} requires a closing ${wE[zw[$]]}`;var Tw=(W)=>`Private type references should not include '#'. Use '${W}' instead.`,H9="Optional definitions like 'string?' are only valid as properties in an object or tuple",Q9="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var Fw={">":!0,">=":!0},_w={"<":!0,"<=":!0};var h4={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},ww=(W)=>`Unmatched )${W===""?"":` before ${W}`}`,z9=(W)=>`Missing ${W}`,Uw=(W,$)=>`Left bounds are only valid when paired with right bounds (try ...${$}${W})`,T9=(W)=>`Left-bounded expressions must specify their limits using < or <= (was ${W})`,Dw=(W,$,X,Y)=>`An expression may have at most one left bound (parsed ${W}${h4[$]}, ${X}${h4[Y]})`;var Vw=(W,$,X)=>Mw(W,$,X,[]),Mw=(W,$,X,Y)=>{let G=X.parseUntilFinalizer();if(Y.push(G.root),G.finalizer===">"){if(Y.length!==$.params.length)return X.error(xG(W,$.names,Y.map((J)=>J.expression)));return Y}if(G.finalizer===",")return Mw(W,$,X,Y);return G.error(z9(">"))},xG=(W,$,X)=>`${W}<${$.join(", ")}> requires exactly ${$.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var bG=(W)=>{let $=W.scanner.shiftUntilNextTerminator();if($==="keyof")W.addPrefix("keyof");else W.root=VE(W,$)},DE=(W,$,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(xG(W,$.names,[]));let G=Vw(W,$,X);return $(...G)},VE=(W,$)=>ME(W,$)??OE(W,$)??W.error($===""?W.scanner.lookahead==="#"?Tw(W.shiftedByOne().scanner.shiftUntilNextTerminator()):vG(W):kG($)),ME=(W,$)=>{if(W.ctx.args?.[$]){let Y=W.ctx.args[$];if(typeof Y!=="string")return Y;return W.ctx.$.node("alias",{reference:Y},{prereduced:!0})}let X=W.ctx.$.maybeResolve($);if(d(X,"root"))return X;if(X===void 0)return;if(d(X,"generic"))return DE($,X,W);return E(`Unexpected resolution ${G0(X)}`)},OE=(W,$)=>{let X=gF($);if(X!==void 0)return W.ctx.$.node("unit",{unit:X});let Y=pF($);if(Y!==void 0)return W.ctx.$.node("unit",{unit:Y})},vG=(W)=>{let $=W.previousOperator();return $?yG($,W.scanner.unscanned):KE(W.scanner.unscanned)},yG=(W,$="")=>`Token '${W}' requires a right operand${$?` before '${$}'`:""}`,KE=(W)=>`Expected an expression${W?` before '${W}'`:""}`;var hG=(W)=>W.scanner.lookahead===""?W.error(vG(W)):W.scanner.lookahead==="("?W.shiftedByOne().reduceGroupOpen():W.scanner.lookaheadIsIn(Qw)?PG(W,W.scanner.shift()):W.scanner.lookaheadIsIn(p2)?hG(W.shiftedByOne()):W.scanner.lookahead==="d"?W.scanner.nextLookahead in fG?PG(W,`${W.scanner.shift()}${W.scanner.shift()}`):bG(W):bG(W);class U2 extends c7{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in U2.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...p2};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(W,$)=>W===">"?$[0]==="="?$[1]==="=":$.trimStart()===""||T1($.trimStart()[0],U2.terminatingChars):W==="="?$[0]!=="=":W===","||W==="?"}var Kw=(W,$)=>{let X=AE(W,$);if(W.root.hasKind("unit")){if(typeof W.root.unit==="number"){W.reduceLeftBound(W.root.unit,X),W.unsetRoot();return}if(W.root.unit instanceof Date){let Y=`d'${W.root.description??W.root.unit.toISOString()}'`;W.unsetRoot(),W.reduceLeftBound(Y,X);return}}return LE(W,X)},Aw={"<":1,">":1,"=":1},AE=(W,$)=>W.scanner.lookaheadIs("=")?`${$}${W.scanner.shift()}`:$;var Ow=(W,$,X,Y)=>{if(X.extends(N.intrinsic.number)){if(typeof $!=="number")return E(gG(W,$,Y));return W==="=="?["min","max"]:W[0]===">"?["min"]:["max"]}if(X.extends(N.intrinsic.lengthBoundable)){if(typeof $!=="number")return E(gG(W,$,Y));return W==="=="?["exactLength"]:W[0]===">"?["minLength"]:["maxLength"]}if(X.extends(N.intrinsic.Date))return W==="=="?["after","before"]:W[0]===">"?["after"]:["before"];return E(Q_(X.expression))},EE=(W)=>({rule:Gw(W.limit)?Jw(W.limit):W.limit,exclusive:W.comparator.length===1}),LE=(W,$)=>{let X=W.unsetRoot(),Y=W.scanner.location;W.parseOperand();let G=W.unsetRoot(),J=W.scanner.sliceChars(Y,W.scanner.location);if(W.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return W.error(gG($,J,"right"));let H=G.unit,Q=$.length===1,z=Ow($,typeof H==="number"?H:J,X,"right");for(let F of z)W.constrainRoot(F,$==="=="?{rule:H}:{rule:H,exclusive:Q});if(!W.branches.leftBound)return;if(!T1($,_w))return W.error(T9($));let T=Ow(W.branches.leftBound.comparator,W.branches.leftBound.limit,X,"left");W.constrainRoot(T[0],EE(W.branches.leftBound)),W.branches.leftBound=null},gG=(W,$,X)=>`Comparator ${X==="left"?h4[W]:W} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${$})`;var Ew=(W)=>{W.scanner.shiftUntilNonWhitespace();let $=W.scanner.shiftUntilNextTerminator();W.root=W.root.brand($)};var Bw=(W)=>{let $=W.scanner.shiftUntilNextTerminator(),X=mF($,{errorOnFail:Lw($)});if(X===0)W.error(Lw(0));W.root=W.root.constrain("divisor",X)},Lw=(W)=>`% operator must be followed by a non-zero integer literal (was ${W})`;var mG=(W)=>{let $=W.scanner.shift();return $===""?W.finalize(""):$==="["?W.scanner.shift()==="]"?W.setRoot(W.root.array()):W.error(BE):$==="|"?W.scanner.lookahead===">"?W.shiftedByOne().pushRootToBranch("|>"):W.pushRootToBranch($):$==="&"?W.pushRootToBranch($):$===")"?W.finalizeGroup():U2.lookaheadIsFinalizing($,W.scanner.unscanned)?W.finalize($):T1($,Aw)?Kw(W,$):$==="%"?Bw(W):$==="#"?Ew(W):($ in p2)?mG(W):W.error(F9($))},F9=(W,$="")=>`'${W}' is not allowed here${$&&` (should be ${$})`}`,BE="Missing expected ']'";var Rw=(W)=>{let $=W.unsetRoot();W.parseOperand();let X=W.unsetRoot();if(!X.hasKind("unit"))return W.error(RE(X.expression));let Y=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[$,"=",Y]},RE=(W)=>`Default value '${W}' must a literal value`;var pG=(W,$)=>{let X=$.$.maybeResolveRoot(W);if(X)return X;if(W.endsWith("[]")){let J=$.$.maybeResolveRoot(W.slice(0,-2));if(J)return J.array()}let Y=new g4(new U2(W),$),G=NE(Y);if(Y.finalizer===">")E(F9(">"));return G},NE=(W)=>{W.parseOperand();let $=e6(W).root;if(!$)return K0(`Root was unexpectedly unset after parsing string '${W.scanner.scanned}'`);if(W.finalizer==="=")$=Rw(W);else if(W.finalizer==="?")$=[$,"?"];if(W.scanner.shiftUntilNonWhitespace(),W.scanner.lookahead)E(F9(W.scanner.lookahead));return $},e6=(W)=>{while(W.finalizer===void 0)ZE(W);return W},ZE=(W)=>W.hasRoot()?W.parseOperator():W.parseOperand();class g4{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(W,$){this.scanner=W,this.ctx=$}error(W){return E(W)}hasRoot(){return this.root!==void 0}setRoot(W){this.root=W}unsetRoot(){let W=this.root;return this.root=void 0,W}constrainRoot(...W){this.root=this.root.constrain(W[0],W[1])}finalize(W){if(this.groups.length)return this.error(z9(")"));this.finalizeBranches(),this.finalizer=W}reduceLeftBound(W,$){let X=h4[$];if(!T1(X,Fw))return this.error(T9($));if(this.branches.leftBound)return this.error(Dw(this.branches.leftBound.limit,this.branches.leftBound.comparator,W,X));this.branches.leftBound={comparator:X,limit:W}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let W=this.groups.pop();if(!W)return this.error(ww(this.scanner.unscanned));this.branches=W}addPrefix(W){this.branches.prefixes.push(W)}applyPrefixes(){while(this.branches.prefixes.length){let W=this.branches.prefixes.pop();this.root=W==="keyof"?this.root.keyof():K0(`Unexpected prefix '${W}'`)}}pushRootToBranch(W){this.assertRangeUnset(),this.applyPrefixes();let $=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd($)??$,W==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,W==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return e6(new g4(this.scanner,this.ctx))}parseOperator(){return mG(this)}parseOperand(){return hG(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Uw(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var SE="An empty string is not a valid generic parameter name",_9=(W,$,X)=>{W.shiftUntilNonWhitespace();let Y=W.shiftUntilNextTerminator();if(Y===""){if(W.lookahead===""&&$.length)return $;return E(SE)}return W.shiftUntilNonWhitespace(),qE(W,Y,$,X)},Nw="extends ",qE=(W,$,X,Y)=>{if(W.shiftUntilNonWhitespace(),W.unscanned.startsWith(Nw))W.jumpForward(Nw.length);else{if(W.lookahead===",")W.shift();return X.push($),_9(W,X,Y)}let G=e6(new g4(W,Y));return X.push([$,G.root]),_9(W,X,Y)};class uG extends qW{$;constructor(W){super((...$)=>new WX(W)(...$),{bind:W});this.$=W}in(W){return new WX(this.$,W===void 0?void 0:this.$.parse(W))}at(W,$){return new WX(this.$).at(W,$)}case(W,$){return new WX(this.$).case(W,$)}}class WX extends qW{$;in;key;branches=[];constructor(W,$){super((X)=>this.caseEntries(Object.entries(X).map(([Y,G])=>Y==="default"?[Y,G]:[this.$.parse(Y),G])));this.$=W,this.in=$}at(W,$){if(this.key)E(kE);if(this.branches.length)E(CE);return this.key=W,$?this.match($):this}case(W,$){return this.caseEntry(this.$.parse(W),$)}caseEntry(W,$){let Y=(this.key?this.$.parse({[this.key]:W}):W).pipe($);return this.branches.push(Y),this}match(W){return this(W)}strings(W){return this.caseEntries(Object.entries(W).map(([$,X])=>$==="default"?[$,X]:[this.$.node("unit",{unit:$}),X]))}caseEntries(W){for(let $=0;$<W.length;$++){let[X,Y]=W[$];if(X==="default"){if($!==W.length-1)E("default may only be specified as the last key of a switch definition");return this.default(Y)}if(typeof Y!=="function")return E(`Value for case "${X}" must be a function (was ${z1(Y)})`);this.caseEntry(X,Y)}return this}default(W){if(typeof W==="function")this.case(r.unknown,W);let $={branches:this.branches,ordered:!0};if(W==="never"||W==="assert")$.meta={onFail:Zw};let X=this.$.node("union",$);if(!this.in)return this.$.finalize(X);let Y=this.in.pipe(X);if(W==="never"||W==="assert")Y=Y.configureReferences({onFail:Zw},"self");return this.$.finalize(Y)}}var Zw=(W)=>W.throw(),CE="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",kE="At most one key matcher may be specified per expression";var w9=(W,$)=>{if(k0(W)){if(W[1]==="=")return[$.$.parseOwnDefinitionFormat(W[0],$),"=",W[2]];if(W[1]==="?")return[$.$.parseOwnDefinitionFormat(W[0],$),"?"]}return U9(W,$)},Sw="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",qw="Only required keys may specify default values, e.g. { value: 'number = 0' }";var Cw=(W,$)=>{let X,Y={},G=S8(W);for(let[H,Q]of G){let z=PE(H);if(z.kind==="spread"){if(!cW(Y))return E(IE);let O=$.$.parseOwnDefinitionFormat(Q,$);if(O.equals(r.object))continue;if(!O.hasKind("intersection")||!O.basis?.equals(r.object))return E(fE(O.expression));X=O.structure;continue}if(z.kind==="undeclared"){if(Q!=="reject"&&Q!=="delete"&&Q!=="ignore")E(jE(Q));Y.undeclared=Q;continue}let T=w9(Q,$),F=z;if(z.kind==="required"){if(!k0(T))cG(Y,"required",{key:z.normalized,value:T},$);else cG(Y,"optional",T[1]==="="?{key:z.normalized,value:T[0],default:T[2]}:{key:z.normalized,value:T[0]},$);continue}if(k0(T)){if(T[1]==="?")E(Sw);if(T[1]==="=")E(qw)}if(z.kind==="optional"){cG(Y,"optional",{key:z.normalized,value:T},$);continue}let _=$.$.parseOwnDefinitionFormat(F.normalized,$),w=Y9(_,T,$.$);if(w.index)Y.index=D0(Y.index,w.index);if(w.required)Y.required=D0(Y.required,w.required)}let J=$.$.node("structure",Y);return $.$.parseSchema({domain:"object",structure:X?.merge(J)??J})},cG=(W,$,X,Y)=>{W[$]=D0(W[$],Y.$.node($,X))},jE=(W)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${G0(W)})`,IE="Spread operator may only be used as the first key in an object",PE=(W)=>typeof W==="symbol"?{kind:"required",normalized:W}:W.at(-1)==="?"?W.at(-2)===P6?{kind:"required",normalized:`${W.slice(0,-2)}?`}:{kind:"optional",normalized:W.slice(0,-1)}:W[0]==="["&&W.at(-1)==="]"?{kind:"index",normalized:W.slice(1,-1)}:W[0]===P6&&W[1]==="["&&W.at(-1)==="]"?{kind:"required",normalized:W.slice(1)}:W==="..."?{kind:"spread"}:W==="+"?{kind:"undeclared"}:{kind:"required",normalized:W==="\\..."?"...":W==="\\+"?"+":W},fE=(W)=>`Spread operand must resolve to an object literal type (was ${W})`;var jw=(W,$)=>cE(W)?xw[W[0]](W,$):pE(W)?fw[W[1]](W,$):null,xE=(W,$)=>$.$.parseOwnDefinitionFormat(W[1],$).keyof(),dG=(W,$)=>{if(W[2]===void 0)return E(yG(W[1],""));let X=$.$.parseOwnDefinitionFormat(W[0],$),Y=$.$.parseOwnDefinitionFormat(W[2],$);if(W[1]==="|")return $.$.node("union",{branches:[X,Y]});let G=W[1]==="&"?l1(X,Y,$.$):u6(X,Y,$.$);if(G instanceof b)return G.throw();return G},bE=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).array(),vE=(W,$)=>{if(typeof W[2]!=="function")return E(Iw("=>",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).pipe(W[2])},Iw=(W,$)=>`${W===":"?"Narrow":"Morph"} expression requires a function following '${W}' (was ${typeof $})`,yE=(W,$)=>{if(typeof W[2]!=="function")return E(Iw(":",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).constrain("predicate",W[2])},hE=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).configureReferences(W[2],"shallow"),Pw=(W)=>W,gE=Pw({"[]":bE,"?":()=>E(H9)}),mE=Pw({"|":dG,"&":dG,":":yE,"=>":vE,"|>":dG,"@":hE,"=":()=>E(Q9)}),fw={...gE,...mE},pE=(W)=>fw[W[1]]!==void 0,uE=(W)=>W,xw=uE({keyof:xE,instanceof:(W,$)=>{if(typeof W[1]!=="function")return E(kw(j6(W[1])));let X=W.slice(1).map((Y)=>typeof Y==="function"?$.$.node("proto",{proto:Y}):E(kw(j6(Y))));return X.length===1?X[0]:$.$.node("union",{branches:X})},"===":(W,$)=>$.$.units(W.slice(1))}),cE=(W)=>xw[W[0]]!==void 0,kw=(W)=>`Expected a constructor following 'instanceof' operator (was ${W})`;var yw=(W,$)=>{let X=[{}],Y=0;while(Y<W.length){let G=!1;if(W[Y]==="..."&&Y<W.length-1)G=!0,Y++;let J=w9(W[Y],$),[H,Q,z]=!k0(J)?[J]:J;if(Y++,G){if(!H.extends(N.intrinsic.Array))return E(oE(H.expression));X=X.flatMap((T)=>H.distribute((F)=>lE(oY(T),F)))}else X=X.map((T)=>{if(Q==="?")return hw(T,H);if(Q==="=")return dE(T,H,z);return lG(T,H)})}return $.$.parseSchema(X.map((G)=>cW(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},lG=(W,$)=>{if(W.defaultables||W.optionals)return E(W.variadic?BG:iE);if(W.variadic)W.postfix=D0(W.postfix,$);else W.prefix=D0(W.prefix,$);return W},hw=(W,$)=>{if(W.variadic)return E(gw);return W.optionals=D0(W.optionals,$),W},dE=(W,$,X)=>{if(W.variadic)return E(gw);if(W.optionals)return E(nE);return W.defaultables=D0(W.defaultables,[[$,X]]),W},bw=(W,$)=>{if(W.postfix)E(vw);if(W.variadic){if(!W.variadic.equals($))E(vw)}else W.variadic=$.internal;return W},lE=(W,$)=>{let X=$.select({method:"find",kind:"sequence"});if(!X)return bw(W,N.intrinsic.unknown);if(X.prefix)for(let Y of X.prefix)lG(W,Y);if(X.optionals)for(let Y of X.optionals)hw(W,Y);if(X.variadic)bw(W,X.variadic);if(X.postfix)for(let Y of X.postfix)lG(W,Y);return W},oE=(W)=>`Spread element must be an array (was ${W})`,vw="A tuple may have at most one variadic element",iE="A required element may not follow an optional element",gw="An optional element may not follow a variadic element";var nE="A defaultable element may not follow an optional element without a default";var rE={},U9=(W,$)=>{if(typeof W==="string"){if($.args&&Object.keys($.args).some((Y)=>W.includes(Y)))return pG(W,$);let X=rE[$.$.name]??={};return X[W]??=pG(W,$)}return p1(W,"object")?tE(W,$):E(oG(z1(W)))},tE=(W,$)=>{let X=k6(W);switch(X){case void 0:if(d(W,"root"))return W;return Cw(W,$);case"Array":return aE(W,$);case"RegExp":return $.$.node("intersection",{domain:"string",pattern:W},{prereduced:!0});case"Function":{let Y=m2(W)?W():W;if(d(Y,"root"))return Y;return E(oG("Function"))}default:return E(oG(X??G0(W)))}},aE=(W,$)=>jw(W,$)??yw(W,$),oG=(W)=>`Type definitions must be strings or objects (was ${W})`;class iG extends qW{constructor(W){let $=Object.assign({errors:c1,hkt:R1,$:W,raw:W.parse,module:W.constructor.module,scope:W.constructor.scope,define:W.define,match:W.match,generic:W.generic,schema:W.schema,keywords:W.ambient,unit:W.unit,enumerated:W.enumerated,instanceOf:W.instanceOf,valueOf:W.valueOf,or:W.or,and:W.and,merge:W.merge,pipe:W.pipe},W.ambientAttachments);super((...X)=>{if(X.length===1)return W.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let Y=X[0].slice(1,-1),G=W.parseGenericParams(Y,{});return new l2(G,X[1],W,W,null)}return W.parse(X)},{bind:W,attach:$})}}var m4=N;class D9 extends G9{get ambientAttachments(){if(!m4.typeAttachments)return;return this.cacheGetter("ambientAttachments",Y0(m4.typeAttachments,(W,$)=>[W,this.bindReference($)]))}preparseOwnAliasEntry(W,$){let X=W.indexOf("<");if(X===-1){if(d($,"module")||d($,"generic"))return[W,$];let J=this.name==="ark"?W:W==="root"?this.name:`${this.name}.${W}`,H=this.resolvedConfig.keywords?.[J];if(H)$=[$,"@",H];return[W,$]}if(W.at(-1)!==">")E("'>' must be the last character of a generic declaration in a scope");let Y=W.slice(0,X),G=W.slice(X+1,-1);return[Y,()=>{let J=this.parseGenericParams(G,{alias:Y});return G_(J,$,this)}]}parseGenericParams(W,$){return _9(new U2(W),[],this.createParseContext({...$,def:W,prefix:"generic"}))}normalizeRootScopeValue(W){if(m2(W)&&!d(W,"generic"))return W();return W}preparseOwnDefinitionFormat(W,$){return{...$,def:W,prefix:$.alias??"type"}}parseOwnDefinitionFormat(W,$){if(!($.alias&&($.alias in this.aliases))&&!$.args)$.args={this:$.id};let Y=U9(W,$);if(k0(Y)){if(Y[1]==="=")return E(Q9);if(Y[1]==="?")return E(H9)}return Y}unit=(W)=>this.units([W]);valueOf=(W)=>this.units(NF(W));enumerated=(...W)=>this.units(W);instanceOf=(W)=>this.node("proto",{proto:W},{prereduced:!0});or=(...W)=>this.schema(W.map(($)=>this.parse($)));and=(...W)=>W.reduce(($,X)=>$.and(this.parse(X)),this.intrinsic.unknown);merge=(...W)=>W.reduce(($,X)=>$.merge(this.parse(X)),this.intrinsic.object);pipe=(...W)=>this.intrinsic.unknown.pipe(...W);match=new uG(this);declare=()=>({type:this.type});define(W){return W}type=new iG(this);static scope=(W,$={})=>new D9(W,$);static module=(W,$={})=>this.scope(W,$).export()}var nG=Object.assign(D9.scope,{define:(W)=>W}),T0=D9;class mw extends R1{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var sE=DW(["base",r.object],["props",r.object])((W)=>W.base.merge(W.props),mw),pw=T0.module({Key:r.key,Merge:sE});class uw extends R1{}var eE=DW("element")((W)=>{let $=W.element.exclude(r.Array),X=$.array();return $.rawOr(X).pipe(g2).distribute((Y)=>Y.assertHasKind("morph").declareOut(X),R0)},uw),cw=T0.module({root:r.Array,readonly:"root",index:r.nonNegativeIntegerString,liftFrom:eE},{name:"Array"});var rG=R0(["string",C8.FileConstructor]),WL=rG.rawOr(rG.array()),dw=R0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:WL}}),lw=T0.module({root:["instanceof",FormData],value:rG,parsed:dw,parse:R0({in:FormData,morphs:(W)=>{let $={};for(let[X,Y]of W)if(X in $){let G=$[X];if(typeof G==="string"||G instanceof C8.FileConstructor)$[X]=[G,Y];else G.push(Y)}else $[X]=Y;return $},declaredOut:dw})},{name:"FormData"});var ow=T0.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var $L={Boolean:1,Number:1,String:1},iw=T0.module({...Y0({...b7,...y7},(W,$)=>(W in $L)?[]:[W,["instanceof",$]]),Array:cw,TypedArray:ow,FormData:lw});var XL=R0({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),YL=R0({domain:"number",divisor:1}),V9=T0.module({root:r.number,integer:YL,epoch:XL,safe:R0({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var g0=(W,$,X)=>{let Y={domain:"string",pattern:{rule:W.source,flags:W.flags,meta:$}};if(X)Y.meta={format:X};return y4("intersection",Y)},nw=g0(f6,"a well-formed integer string"),HU=T0.module({root:nw,parse:R0({in:nw,morphs:(W,$)=>{let X=Number.parseInt(W);return Number.isSafeInteger(X)?X:$.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:r.integer})},{name:"string.integer"}),GL=g0(/^[\dA-Fa-f]+$/,"hex characters only"),JL=T0.module({root:g0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:g0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),rw=g0(/^[A-Z].*$/,"capitalized"),HL=T0.module({root:R0({in:"string",morphs:(W)=>W.charAt(0).toUpperCase()+W.slice(1),declaredOut:rw}),preformatted:rw},{name:"string.capitalize"}),QL=(W)=>{let $=W.replaceAll(/[ -]+/g,""),X=0,Y,G,J=!1;for(let H=$.length-1;H>=0;H--){if(Y=$.substring(H,H+1),G=Number.parseInt(Y,10),J)G*=2,X+=G>=10?G%10+1:G;else X+=G;J=!J}return!!(X%10===0?$:!1)},zL=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,TL=R0({domain:"string",pattern:{meta:"a credit card number",rule:zL.source},predicate:{meta:"a credit card number",predicate:QL}});var FL=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var _L=(W)=>!Number.isNaN(new Date(W).valueOf()),tw=R0({domain:"string",predicate:{meta:"a parsable date",predicate:_L}}).assertHasKind("intersection"),aw=HU.root.internal.narrow((W,$)=>{let X=Number.parseInt(W),Y=V9.epoch(X);if(Y instanceof c1)return $.errors.merge(Y),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),wL=T0.module({root:aw,parse:R0({in:aw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.epoch"}),sw=g0(FL,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),UL=T0.module({root:sw,parse:R0({in:sw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.iso"}),DL=T0.module({root:tw,parse:R0({declaredIn:tw,in:"string",morphs:(W,$)=>{let X=new Date(W);if(Number.isNaN(X.valueOf()))return $.error("a parsable date");return X},declaredOut:r.Date}),iso:UL,epoch:wL},{name:"string.date"}),VL=g0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),ew="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",o2=`(${ew}[.]){3}${ew}`,ML=new RegExp(`^${o2}$`),s0="(?:[0-9a-fA-F]{1,4})",OL=new RegExp(`^((?:${s0}:){7}(?:${s0}|:)|(?:${s0}:){6}(?:${o2}|:${s0}|:)|(?:${s0}:){5}(?::${o2}|(:${s0}){1,2}|:)|(?:${s0}:){4}(?:(:${s0}){0,1}:${o2}|(:${s0}){1,3}|:)|(?:${s0}:){3}(?:(:${s0}){0,2}:${o2}|(:${s0}){1,4}|:)|(?:${s0}:){2}(?:(:${s0}){0,3}:${o2}|(:${s0}){1,5}|:)|(?:${s0}:){1}(?:(:${s0}){0,4}:${o2}|(:${s0}){1,6}|:)|(?::((?::${s0}){0,5}:${o2}|(?::${s0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),KL=T0.module({root:["v4 | v6","@","an IP address"],v4:g0(ML,"an IPv4 address","ipv4"),v6:g0(OL,"an IPv6 address","ipv6")},{name:"string.ip"}),p4="a JSON string",QU=(W)=>{if(!(W instanceof SyntaxError))throw W;return`must be ${p4} (${W})`},AL=R0({meta:p4,domain:"string",predicate:{meta:p4,predicate:(W,$)=>{try{return JSON.parse(W),!0}catch(X){return $.reject({code:"predicate",expected:p4,problem:QU(X)})}}}}),EL=(W,$)=>{if(W.length===0)return $.error({code:"predicate",expected:p4,actual:"empty"});try{return JSON.parse(W)}catch(X){return $.error({code:"predicate",expected:p4,problem:QU(X)})}},LL=T0.module({root:AL,parse:R0({meta:"safe JSON string parser",in:"string",morphs:EL,declaredOut:r.jsonObject})},{name:"string.json"}),WU=g0(/^[a-z]*$/,"only lowercase letters"),BL=T0.module({root:R0({in:"string",morphs:(W)=>W.toLowerCase(),declaredOut:WU}),preformatted:WU},{name:"string.lower"}),zU=["NFC","NFD","NFKC","NFKD"],$X=Y0(zU,(W,$)=>[$,R0({domain:"string",predicate:(X)=>X.normalize($)===X,meta:`${$}-normalized unicode`})]),M9=Y0(zU,(W,$)=>[$,R0({in:"string",morphs:(X)=>X.normalize($),declaredOut:$X[$]})]),RL=T0.module({root:M9.NFC,preformatted:$X.NFC},{name:"string.normalize.NFC"}),NL=T0.module({root:M9.NFD,preformatted:$X.NFD},{name:"string.normalize.NFD"}),ZL=T0.module({root:M9.NFKC,preformatted:$X.NFKC},{name:"string.normalize.NFKC"}),SL=T0.module({root:M9.NFKD,preformatted:$X.NFKD},{name:"string.normalize.NFKD"}),qL=T0.module({root:"NFC",NFC:RL,NFD:NL,NFKC:ZL,NFKD:SL},{name:"string.normalize"}),$U=g0(cY,"a well-formed numeric string"),CL=T0.module({root:$U,parse:R0({in:$U,morphs:(W)=>Number.parseFloat(W),declaredOut:r.number})},{name:"string.numeric"}),XU="a regex pattern",kL=R0({domain:"string",predicate:{meta:XU,predicate:(W,$)=>{try{return new RegExp(W),!0}catch(X){return $.reject({code:"predicate",expected:XU,problem:String(X)})}}},meta:{format:"regex"}}),jL=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,IL=g0(jL,"a semantic version (see https://semver.org/)"),YU=g0(/^\S.*\S$|^\S?$/,"trimmed"),PL=T0.module({root:R0({in:"string",morphs:(W)=>W.trim(),declaredOut:YU}),preformatted:YU},{name:"string.trim"}),GU=g0(/^[A-Z]*$/,"only uppercase letters"),fL=T0.module({root:R0({in:"string",morphs:(W)=>W.toUpperCase(),declaredOut:GU}),preformatted:GU},{name:"string.upper"}),xL=(W)=>{if(URL.canParse)return URL.canParse(W);try{return new URL(W),!0}catch{return!1}},JU=R0({domain:"string",predicate:{meta:"a URL string",predicate:xL},meta:{format:"uri"}}),bL=T0.module({root:JU,parse:R0({declaredIn:JU,in:"string",morphs:(W,$)=>{try{return new URL(W)}catch{return $.error("a URL string")}},declaredOut:R0(URL)})},{name:"string.url"}),vL=T0.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:g0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:g0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:g0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:g0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:g0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:g0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:g0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:g0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),TU=T0.module({root:r.string,alpha:g0(/^[A-Za-z]*$/,"only letters"),alphanumeric:g0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:GL,base64:JL,capitalize:HL,creditCard:TL,date:DL,digits:g0(/^\d*$/,"only digits 0-9"),email:VL,integer:HU,ip:KL,json:LL,lower:BL,normalize:qL,numeric:CL,regex:kL,semver:IL,trim:PL,upper:fL,url:bL,uuid:vL},{name:"string"});var FU=T0.module({bigint:r.bigint,boolean:r.boolean,false:r.false,never:r.never,null:r.null,number:r.number,object:r.object,string:r.string,symbol:r.symbol,true:r.true,unknown:r.unknown,undefined:r.undefined}),_U=T0.module({root:r.unknown,any:r.unknown},{name:"unknown"}),yL=T0.module({root:r.jsonObject,stringify:y4("morph",{in:r.jsonObject,morphs:(W)=>JSON.stringify(W),declaredOut:r.string})},{name:"object.json"}),wU=T0.module({root:r.object,json:yL},{name:"object"});class UU extends R1{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var hL=DW(["K",r.key],"V")((W)=>({domain:"object",index:{signature:W.K,value:W.V}}),UU);class DU extends R1{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var gL=DW(["T",r.object],["K",r.key])((W)=>W.T.pick(W.K),DU);class VU extends R1{description='omit a set of properties from an object like `Omit(User, "age")`'}var mL=DW(["T",r.object],["K",r.key])((W)=>W.T.omit(W.K),VU);class MU extends R1{description="make all named properties of an object optional like `Partial(User)`"}var pL=DW(["T",r.object])((W)=>W.T.partial(),MU);class OU extends R1{description="make all named properties of an object required like `Required(User)`"}var uL=DW(["T",r.object])((W)=>W.T.required(),OU);class KU extends R1{description='exclude branches of a union like `Exclude("boolean", "true")`'}var cL=DW("T","U")((W)=>W.T.exclude(W.U),KU);class AU extends R1{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var dL=DW("T","U")((W)=>W.T.extract(W.U),AU),EU=T0.module({Exclude:cL,Extract:dL,Omit:mL,Partial:pL,Pick:gL,Record:hL,Required:uL});var i2=nG({...FU,...EU,...iw,...pw,string:TU,number:V9,object:wU,unknown:_U},{prereducedAliases:!0,name:"ark"}),F1=i2.export();Object.assign(m4.ambient,F1);m4.typeAttachments={string:F1.string.root,number:F1.number.root,bigint:F1.bigint,boolean:F1.boolean,symbol:F1.symbol,undefined:F1.undefined,null:F1.null,object:F1.object.root,unknown:F1.unknown.root,false:F1.false,true:F1.true,never:F1.never,arrayIndex:F1.Array.index,Key:F1.Key,Record:F1.Record,Array:F1.Array.root,Date:F1.Date};var jW=Object.assign(i2.type,m4.typeAttachments),lL=i2.match,oL=i2.generic,Hs=i2.schema,iL=i2.define,nL=i2.declare;var rL="__vite_start_time"in globalThis,tL=typeof window!=="undefined",Ns="vitest"in globalThis,D2=jW("string"),LU=jW('"true" | "false" | undefined'),V2=P7({isServer:!rL&&!tL,server:{CI:jW("string | undefined").pipe(Boolean),POSTGRES_USER:D2,POSTGRES_PASSWORD:D2,POSTGRES_DATABASE:D2,POSTGRES_HOST:D2,POSTGRES_PORT:D2.pipe((W)=>Number.parseInt(W,10)),BACKEND_PORT:D2.pipe((W)=>Number.parseInt(W,10)),RUN_WORKERS_FROM_SOURCE:LU.pipe((W)=>W==="true"),FRONTEND_PORT:D2.pipe((W)=>Number.parseInt(W,10)),FRONTEND_ORIGINS:D2.pipe.try((W)=>JSON.parse(W),jW("string[]")),API_KEY_OPENAI:jW("string | undefined"),API_KEY_RESEND:jW("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:D2,VITE_DEV_FRONTEND_HOST:jW("string | undefined"),VITE_DEV_HTTPS:LU.pipe((W)=>W==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var aG={};vD(aG,{users:()=>I8,untrackedUserColumnNames:()=>aL,twoFactorMethod:()=>SU,trackedUserColumnName:()=>sL,trackableUserColumnNames:()=>NU,signInHistory:()=>WB,role:()=>RU,players:()=>tG,passwordResetAttempts:()=>$B,games:()=>O9,banishedIps:()=>K9,accountActions:()=>eL,accountAction:()=>ZU});function BU(W){return V`lower(${W})`}var RU=H6("role",["admin","user"]),I8=v2("users",{id:TW().primaryKey().defaultRandom(),username:I1({length:16}).notNull(),emailOffered:I1({length:254}).notNull(),emailVerified:I1({length:254}),password:I1({length:254}),createdAt:ZW({withTimezone:!0}).notNull().defaultNow(),createdIp:I1({length:45}).notNull(),isActive:w6().notNull().default(!1),verifiedAt:ZW({withTimezone:!0}),userRole:RU().default("user")},(W)=>[q7("usernameUniqueIndex").on(BU(W.username)),q7("emailVerifiedUniqueIndex").on(BU(W.emailVerified))]),aL=["id","createdAt","createdIp","isActive","verifiedAt"],NU=["username","emailOffered","emailVerified","password","userRole"],sL=H6("trackedUserColumnName",NU),ZU=H6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),eL=v2("accountActions",{userId:TW().references(()=>I8.id).primaryKey(),action:ZU().notNull(),code:I1({length:254}).notNull(),wrongCodeCount:U6().notNull().default(0),expiresAt:ZW({withTimezone:!0}).notNull()}),O9=v2("games",{id:TW().primaryKey().defaultRandom()}),tG=v2("players",{userId:TW().notNull().references(()=>I8.id,{onDelete:"cascade"}),gameId:TW().notNull().references(()=>O9.id,{onDelete:"cascade"}),score:U6().notNull()},(W)=>[UT({name:"players_userId_gameId_pk",columns:[W.userId,W.gameId]})]),WB=v2("signInHistory",{id:TW().primaryKey().defaultRandom(),userId:TW().references(()=>I8.id,{onDelete:"cascade"}),signInTime:ZW({withTimezone:!0}).notNull().defaultNow(),ipAddress:I1({length:45}).notNull(),userAgent:I1({length:1024}),successful:w6().notNull().default(!1)}),SU=H6("twoFactorMethod",["email","phone"]),$B=v2("passwordResetAttempts",{id:TW().primaryKey().defaultRandom(),userId:TW().notNull().references(()=>I8.id,{onDelete:"cascade"}),requestedIp:I1({length:45}).notNull(),requestedAt:ZW({withTimezone:!0}).notNull().defaultNow(),succeededIp:I1({length:45}),succeededAt:ZW({withTimezone:!0}),verificationMethod:SU().notNull()}),K9=v2("banishedIps",{ip:I1({length:45}).primaryKey(),reason:I1({length:2048}).notNull(),banishedAt:ZW({withTimezone:!0}).notNull().defaultNow(),banishedUntil:ZW({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class sG{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(XB.resolve(__dirname,"notify_update.sql"));let W=[w1(I8),w1(O9),w1(tG)];await this.sql`SELECT create_notify_triggers(${this.sql.array(W)})`,await this.sql.listen("table_update",($)=>{let X=$.split(","),Y=X[0],G=X[1],J=`${Y}("${G}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(W=!1,$={host:V2.POSTGRES_HOST,port:V2.POSTGRES_PORT,user:V2.POSTGRES_USER,password:V2.POSTGRES_PASSWORD,database:V2.POSTGRES_DATABASE}){this.options=$,this.sql=E4($),this.drizzle=pY(this.sql,{schema:aG,logger:W})}observe(W,$){if(!this.observers.has(W))this.observers.set(W,new B0);this.observers.get(W).subscribe("SINGLETON",$)}}import{resolve as JB}from"path";import{existsSync as eG,mkdirSync as qU,readFileSync as YB,readdirSync as CU,rmSync as kU,statSync as jU,writeFileSync as GB}from"fs";import{resolve as WJ}from"path";var IU=class{rootDir;get initialized(){return eG(this.rootDir)}initialize(){if(!this.initialized)qU(this.rootDir,{recursive:!0})}constructor(W){if(this.rootDir=W.path,W.eagerInit)this.initialize()}getItem(W){let $=WJ(this.rootDir,W);if(eG($))return YB($,"utf-8");return null}setItem(W,$){this.initialize();let X=WJ(this.rootDir,W);GB(X,$)}removeItem(W){let $=WJ(this.rootDir,W);if(eG($))this.initialize(),kU($)}key(W){return CU(this.rootDir).sort((Y,G)=>{let J=jU(Y);return jU(G).ctimeMs-J.ctimeMs})[W]??null}clear(){kU(this.rootDir,{recursive:!0}),qU(this.rootDir,{recursive:!0})}get length(){return CU(this.rootDir).length}};var $J=new IU({path:JB(process.cwd(),"storage")});import*as A9 from"fs";import*as PU from"readline";function HB(W){let X=W.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(Y,G,J,H,Q)=>{let T={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`${H}-${T}-${G}T${Q}`});return new Date(X)}async function fU(W,$="/var/log/nginx/access.log",X=new Date){let Y=new Map;if(!A9.existsSync($))return W.error(`Log file not found: ${$}`),Y;let G=A9.createReadStream($),J=PU.createInterface({input:G,crlfDelay:Number.POSITIVE_INFINITY}),H=new Date(X.getTime()-3600000);return J.on("line",(Q)=>{let z=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,T=Q.match(z);if(T?.groups){let F=T.groups.ip,_=T.groups.dateTime,w=HB(_);if(!Number.isNaN(w.getTime())){if(w>=H&&w<=X){let O=Y.get(F);if(!O)O=[],Y.set(F,O);O.push(Q)}}else W.error(`Failed to parse date: ${_}`)}}),new Promise((Q,z)=>{J.on("error",(T)=>{z(T)}),J.on("close",()=>{Q(Y)})})}function xU(W){return W.toJsonSchema()}var QB=["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(`
128
+ `);function bU(W){return QB+W.join(`
129
129
 
130
- `)}var x_={schema:kW([{shouldBanIp:"false"},"|",{shouldBanIp:"true",veryConciseReason:"string"}]),toJsonSchema:f_,fallback:{shouldBanIp:!1}};var QB=[".env","php"];async function v_({generator:W,logFilePath:$,logger:X,now:Y=new Date}){let J=W.usdBudget,G=new t7({logQuery(q,m){X.info("\uD83D\uDCDD query",q,m)}}),H=await I_(X,$,Y),Q=[],z=W.from(x_),F=0,T=0;for(let[q,m]of H){X.info(`\uD83D\uDD0D ruling on ${q}. logs:`),X.info(m.map((v)=>` ${v}`).join(`
131
- `));let c=!1;for(let v of QB)if(m.some((h)=>h.includes(v))){Q.push({ip:q,reason:`Always ban ${v}`}),X.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${q}--always ban ${v}
132
- `),c=!0;break}if(c)continue;if(W.usdBudget>W.usdMinimum){let v=P_(m),h=await z(v);if(h.shouldBanIp)Q.push({ip:q,reason:h.veryConciseReason}),X.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${q}--${h.veryConciseReason}
133
- `);else T++,X.info(` \uD83D\uDD4A\uFE0F not banning ${q}
134
- `);F++}else{X.warn("\uD83D\uDCB0 insufficient funds to process all logs"),X.warn(`\uD83D\uDCB0 got through ${F}/${H.size} ips
135
- `);break}}let U=Q.length;if(Q.length>0)await G.drizzle.insert(K9).values(Q).onConflictDoNothing();let _=[],V=e7.getItem("lastTribunalProcessedDate"),K=new Date(V??"1970-01-01");try{_.push(...await G.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:NY(K9.banishedAt,K)}))}catch(q){X.error(q)}try{if(process.env.EXPERIMENTAL_BAN_IPS)await Promise.all(_.map((q)=>new Promise((m,c)=>HB(`iptables -D INPUT -s ${q.ip} -j DROP`).on("exit",(v)=>{if(v===0)X.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${q.ip}`),m();else c(new Error(`iptables exited with code ${v}`))}))));else X.info("\uD83E\uDDD1\u200D\u2696\uFE0F skipping iptables update")}catch(q){if(q instanceof Error)X.error(q.message);else{let m=oH(q);X.error("iptables exited with error",m)}}e7.setItem("lastTribunalProcessedDate",Y.toISOString()),X.info(`\u2728 banned ${U} ips, didn't ban ${T} ips`);let B=J-W.usdBudget,I=B.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),C=J.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),R=Math.round(B/J*100);X.info(`\uD83D\uDCB8 spent ${I}, ${R}% of ${C} budget`)}var V2=new v9;Object.assign(console,V2.logger,{log:V2.logger.info});process.on("SIGINT",()=>{V2.logger.info("\u2757 received SIGINT; exiting gracefully"),E9()});process.on("SIGTERM",()=>{V2.logger.info("\u2757 received SIGTERM; exiting gracefully"),E9()});process.on("exit",()=>{V2.logger.info("\u2757 received exit; exiting gracefully"),E9()});V2.logger.info("\uD83D\uDEEB tribunal worker ready");var zB=new lH({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:M2.API_KEY_OPENAI,cachingMode:"off",logger:V2.logger});if(M2.API_KEY_OPENAI===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await v_({generator:zB,logFilePath:"/var/log/nginx/access.log",logger:V2.logger});E9();function E9(){V2.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
130
+ `)}var vU={schema:jW([{shouldBanIp:"false"},"|",{shouldBanIp:"true",veryConciseReason:"string"}]),toJsonSchema:xU,fallback:{shouldBanIp:!1}};var TB=[".env","php"];async function yU({generator:W,logFilePath:$,logger:X,now:Y=new Date}){let G=W.usdBudget,J=new sG({logQuery(Z,P){X.info("\uD83D\uDCDD query",Z,P)}}),H=await fU(X,$,Y),Q=[],z=W.from(vU),T=0,F=0;for(let[Z,P]of H){X.info(`\uD83D\uDD0D ruling on ${Z}. logs:`),X.info(P.map((x)=>` ${x}`).join(`
131
+ `));let h=!1;for(let x of TB)if(P.some((m)=>m.includes(x))){Q.push({ip:Z,reason:`Always ban ${x}`}),X.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${Z}--always ban ${x}
132
+ `),h=!0;break}if(h)continue;if(W.usdBudget>W.usdMinimum){let x=bU(P),m=await z(x);if(m.shouldBanIp)Q.push({ip:Z,reason:m.veryConciseReason}),X.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${Z}--${m.veryConciseReason}
133
+ `);else F++,X.info(` \uD83D\uDD4A\uFE0F not banning ${Z}
134
+ `);T++}else{X.warn("\uD83D\uDCB0 insufficient funds to process all logs"),X.warn(`\uD83D\uDCB0 got through ${T}/${H.size} ips
135
+ `);break}}let _=Q.length;if(Q.length>0)await J.drizzle.insert(K9).values(Q).onConflictDoNothing();let w=[],O=$J.getItem("lastTribunalProcessedDate"),M=new Date(O??"1970-01-01");try{w.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:NY(K9.banishedAt,M)}))}catch(Z){X.error(Z)}try{if(process.env.EXPERIMENTAL_BAN_IPS)await Promise.all(w.map((Z)=>new Promise((P,h)=>zB(`iptables -D INPUT -s ${Z.ip} -j DROP`).on("exit",(x)=>{if(x===0)X.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${Z.ip}`),P();else h(new Error(`iptables exited with code ${x}`))}))));else X.info("\uD83E\uDDD1\u200D\u2696\uFE0F skipping iptables update")}catch(Z){if(Z instanceof Error)X.error(Z.message);else{let P=nH(Z);X.error("iptables exited with error",P)}}$J.setItem("lastTribunalProcessedDate",Y.toISOString()),X.info(`\u2728 banned ${_} ips, didn't ban ${F} ips`);let A=G-W.usdBudget,I=A.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),j=G.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),R=Math.round(A/G*100);X.info(`\uD83D\uDCB8 spent ${I}, ${R}% of ${j} budget`)}var M2=new y9;Object.assign(console,M2.logger,{log:M2.logger.info});process.on("SIGINT",()=>{M2.logger.info("\u2757 received SIGINT; exiting gracefully"),E9()});process.on("SIGTERM",()=>{M2.logger.info("\u2757 received SIGTERM; exiting gracefully"),E9()});process.on("exit",()=>{M2.logger.info("\u2757 received exit; exiting gracefully"),E9()});M2.logger.info("\uD83D\uDEEB tribunal worker ready");var FB=new iH({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:V2.API_KEY_OPENAI,cachingMode:"off",logger:M2.logger});if(V2.API_KEY_OPENAI===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await yU({generator:FB,logFilePath:"/var/log/nginx/access.log",logger:M2.logger});E9();function E9(){M2.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}