tempest.games 0.2.8 → 0.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/app/assets/index-CGlDykR1.js +109 -0
- package/app/assets/index-ki_mruCb.css +1 -0
- package/app/index.html +2 -2
- package/bin/backend.bun.js +248 -244
- package/bin/backend.worker.tribunal.bun.js +107 -83
- package/bin/frontend.bun.js +19 -19
- package/bin/setup-db.bun.js +76 -71
- package/package.json +14 -14
- package/app/assets/index-B2F2ZwG-.css +0 -1
- package/app/assets/index-D-81-7hL.js +0 -109
|
@@ -1,49 +1,73 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var jD=Object.create;var{getPrototypeOf:ID,defineProperty:S9,getOwnPropertyNames:PD}=Object;var fD=Object.prototype.hasOwnProperty;var bD=(W,$,Y)=>{Y=W!=null?jD(ID(W)):{};let X=$||!W||!W.__esModule?S9(Y,"default",{value:W,enumerable:!0}):Y;for(let G of PD(W))if(!fD.call(X,G))S9(X,G,{get:()=>W[G],enumerable:!0});return X};var xD=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var vD=(W,$)=>{for(var Y in $)S9(W,Y,{get:$[Y],enumerable:!0,configurable:!0,set:(X)=>$[Y]=()=>X})};var wZ=(W,$)=>()=>(W&&($=W(W=0)),$);var DJ=import.meta.require;var f3=xD((Bk,P3)=>{var K4=DJ("os"),E4=DJ("path");function I3(W){let $=process.env.XDG_CACHE_HOME||E4.join(K4.homedir(),".cache");return E4.join($,W)}function AM(W){return E4.join(K4.homedir(),"Library","Caches",W)}function LM(W){let $=process.env.LOCALAPPDATA||E4.join(K4.homedir(),"AppData","Local");return E4.join($,W,"Cache")}var ZM=function(){switch(K4.platform()){case"darwin":return AM;case"win32":return LM;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 "${K4.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 ZM($)}});class i8 extends Promise{fate;resolve;reject;done=!1;constructor(W){let $,Y;super((X,G)=>{$=X,Y=G});this.resolve=$,this.reject=Y,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((Y)=>{this.pass($,Y)},(Y)=>{this.fail($,Y)})}else this.resolve(W),this.fate=void 0}}var VZ=(W,$,Y=VJ.STORE)=>{return MJ(Y,{key:`${W.key}:JSON`,get:({get:X})=>$.toJson(X(W)),set:({set:X},G)=>{X(W,$.fromJson(G))}})};function EZ(W,$,Y){return q9(W,{key:`${$.key}:JSON`,get:(G)=>({get:J})=>{let H=J($,G);return Y.toJson(H)},set:(G)=>({set:J},H)=>{J($,G,Y.fromJson(H))}},["mutable","json"])}var n8=(W)=>JSON.parse(W),q1=(W)=>JSON.stringify(W),LZ=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function s(W){while(W.child!==null)W=W.child;return W}class HY{_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 HY([...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 OJ(W,$){let Y=q1($),X=`${W.key}(${Y})`,G=yD[W.type],J={key:X,type:G};return Object.assign(J,{family:{key:W.key,subKey:Y}}),Object.assign(J,{counterfeit:!0}),J}function r8(W){let $={key:W.key,type:W.type};if("family"in W)$.family=W.family;return $}var C9=(W)=>($,Y,X,G,...J)=>{console[W](`${$} ${Y} "${X}" ${G}`,...J)},hD={error:C9("error"),info:C9("info"),warn:C9("warn")};class k9{logLevel;filter;logger;constructor(W,$,Y=hD){this.logLevel=W,this.filter=$,this.logger=Y}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 Y=this.relations.get(W),X=this.relations.get($);if(Y)Y.add($);else Y=new Set([$]),this.relations.set(W,Y);if(X)X.add(W);else X=new Set([W]),this.relations.set($,X)}deleteRelation(W,$){let Y=this.relations.get(W);if(Y){if(Y.delete($),Y.size===0)this.relations.delete(W);let X=this.relations.get($);if(X){if(X.delete(W),X.size===0)this.relations.delete($)}}}replaceRelationsUnsafely(W,$){this.relations.set(W,new Set($));for(let Y of $){let X=new Set().add(W);this.relations.set(Y,X)}}replaceRelationsSafely(W,$){let Y=this.relations.get(W),X=this.isAType?.(W)?W:void 0,G=X===void 0?W:void 0;if(Y)for(let J of Y){X??=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(X,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(([Y,X])=>[Y,new Set(X)])),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 Y=$.externalStore;if(this.has=(X,G)=>Y.has(X,G),this.addRelation=(X,G)=>{Y.addRelation(X,G)},this.deleteRelation=(X,G)=>{Y.deleteRelation(X,G)},this.replaceRelationsSafely=(X,G)=>{Y.replaceRelationsSafely(X,G)},this.replaceRelationsUnsafely=(X,G)=>{Y.replaceRelationsUnsafely(X,G)},this.getRelatedKeys=(X)=>Y.getRelatedKeys(X),Y.getContent)this.getContentInternal=(X)=>{return Y.getContent(X)},this.setContent=(X,G)=>{Y.setContent(X,G)},this.deleteContent=(X)=>{Y.deleteContent(X)};for(let[X,G]of W.relations??[]){let J=this.isAType?.(X)?X:void 0,H=J===void 0?X:void 0;for(let T of G)J??=T,H??=T,this.addRelation(J,H)}for(let[X,G]of W.contents??[])this.setContent(X,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 $,Y,X;switch(W.length){case 1:{let G=W[0];$=G[this.a],Y=G[this.b],X=void 0;break}case 2:{let G=W[0];if(typeof G==="string")[$,Y]=W;else $=G[this.a],Y=G[this.b],X=W[1];break}default:{$=W[0],Y=W[1],X=W[2];break}}switch(this.cardinality){case"1:1":{let G=this.getRelatedKey($);if(G&&G!==Y)this.delete($,G)}case"1:n":{let G=this.getRelatedKey(Y);if(G&&G!==$)this.delete(G,Y)}break;case"n:n":}if(X){let G=this.makeContentKey($,Y);this.setContent(G,X)}return this.addRelation($,Y),this}delete(W,$){$=typeof $==="string"?$:W[this.b];let Y=typeof W==="string"?W:W[this.a];if(Y===void 0&&typeof $==="string"){let X=this.getRelatedKeys($);if(X)for(let G of X)this.delete(G,$)}if(typeof Y==="string"&&$===void 0){let X=this.getRelatedKeys(Y);if(X)for(let G of X)this.delete(Y,G)}if(typeof Y==="string"&&typeof $==="string"){this.deleteRelation(Y,$);let X=this.makeContentKey(Y,$);this.deleteContent(X)}return this}getRelatedKey(W){let $=this.getRelatedKeys(W);if($){if($.size>1)this.warn?.(`${$.size} related keys were found for key "${W}": (${[...$].map((X)=>`"${X}"`).join(", ")}). Only one related key was expected.`);let Y;for(let X of $){Y=X;break}return Y}}replaceRelations(W,$,Y){let X=!Array.isArray($),G=X?Object.keys($):$;if(Y?.reckless)this.replaceRelationsUnsafely(W,G);else this.replaceRelationsSafely(W,G);if(X)for(let J of G){let H=this.makeContentKey(W,J),T=$[J];this.setContent(H,T)}return this}getContent(W,$){let Y=this.makeContentKey(W,$);return this.getContentInternal(Y)}getRelationEntries(W){let $=W[this.a],Y=W[this.b];if($!==void 0&&Y===void 0){let X=this.getRelatedKeys($);if(X)return[...X].map((G)=>{return[G,this.getContent($,G)]})}if($===void 0&&Y!==void 0){let X=this.getRelatedKeys(Y);if(X)return[...X].map((G)=>{return[G,this.getContent(G,Y)]})}return[]}has(W,$){if($)return this.getRelatedKeys(W)?.has($)??!1;return this.relations.has(W)}}class Z0{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 Y of $)Y(W)}}class j9 extends Z0{state;constructor(W){super();this.state=W}next(W){this.state=W,super.next(W)}}function A$(W){return"epoch"in W.transactionMeta}function o1(W){return"phase"in W.transactionMeta}function KJ(W){return W[0].toUpperCase()+W.slice(1)}function TY(W){return W.type.split("_").map(KJ).join(" ")}class t8 extends Error{constructor(W,$){super(`${TY(W)} ${q1(W.key)} not found in store "${$.config.name}".`)}}var y2=(W)=>($)=>W instanceof Function?W($):W;var L$=(W,$)=>{if(W.valueMap.has($.key))return W.logger.info("\uD83D\uDCD6",$.type,$.key,"reading cached value"),EJ($,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 Y=$.default,X;if(Y instanceof Function)X=Y();else X=Y;return W.logger.info("\uD83D\uDC81","atom",$.key,"could not find cached value; using default",X),X}}};var AJ=(W,$)=>{if(W.operation.open){let Y=performance.now();return W.logger.info("\u2757",$.type,$.key,`deferring setState at T-${Y} until setState for "${W.operation.token.key}" is done`),Y}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}"`}`)},LJ=(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)},ZJ=(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($)},Z$=(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 NJ=(W,$,Y)=>{switch($.type){case"mutable_atom":W.logger.info("\uD83D\uDCE2",$.type,$.key,"is now (",Y.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 (",Y.oldValue,"->",Y.newValue,") subscribers:",$.subject.subscribers)}$.subject.next(Y)};var I9=(W,$)=>{let Y=s(W),X=Y.selectorAtoms.getRelatedKeys($.key);if(Y.logger.info("\uD83E\uDDF9",$.type,$.key,X?`evicting ${X.size} states downstream:`:"no downstream states",X??"to evict"),X){if(Y.operation.open)Y.logger.info("\uD83E\uDDF9",$.type,$.key,`[ ${[...Y.operation.done].join(", ")} ] already done`);for(let G of X){if(ZJ(Y,G))continue;RJ(G,Y),Z$(Y,G)}}};var BJ=(W,$,Y)=>{let X=L$(W,$),G=X;if($.type==="mutable_atom"&&o1(W)){let{parent:H}=W;G=a8(W,$,H)}if(G=y2(Y)(G),W.logger.info("\uD83D\uDCDD","atom",$.key,"set to",G),G=C1(W,$.key,G,$.subject),qJ(W,$.key))CJ(W,$.key);Z$(W,$.key),I9(W,$);let J={oldValue:X,newValue:G};if(!o1(W)){NJ(W,$,J);return}if(W.on.transactionApplying.state===null){let{key:H}=$;if(SJ(J.newValue))return;let T={type:"atom_update",key:H,...J};if($.family)T.family=$.family;W.transactionMeta.update.updates.push(T),W.logger.info("\uD83D\uDCC1","atom",H,"stowed (",J.oldValue,"->",J.newValue,")")}else if($.key.startsWith("*")){let H=$.key.slice(1),T=W.atoms.get(H),Q=W.valueMap.get(H);if(T.type==="mutable_atom"&&o1(W)){let{parent:z}=W;Q=a8(W,T,z)}if(Q.do(J.newValue)===null)I9(W,T)}};var QY=(W,$,Y)=>{switch($.type){case"atom":case"mutable_atom":BJ(W,$,Y);break;case"writable_pure_selector":case"writable_held_selector":$.set(Y);break}};var _Y=(W,$)=>s(W).atoms.has($),gD=(W,$)=>s(W).writableSelectors.has($),mD=(W,$)=>s(W).readonlySelectors.has($),kJ=(W,$)=>_Y(W,$)||gD(W,$)||mD(W,$);var zY=(W,$)=>{return s(W).selectorGraph.getRelationEntries({downstreamSelectorKey:$}).filter(([X,{source:G}])=>G!==$).map(([X,{source:G}])=>G).filter((X)=>kJ(W,X))};var P9=(W,$,Y)=>{let X=[],G=zY(W,$);while(G.length>0){let J=G.shift();if(Y.has(J))continue;if(Y.add(J),!_Y(W,J))G.push(...zY(W,J));else if(!X.includes(J))X.push(J)}return X},jJ=(W,$)=>{let Y=W.key,X=zY($,Y),G=new Set;return X.flatMap((J)=>_Y($,J)?J:P9($,J,G))};var IJ=(W,$,Y,X,G)=>{let J=s(W),{type:H,key:T}=X;if(H==="atom"||H==="mutable_atom")J.selectorAtoms.set({selectorKey:Y,atomKey:T}),W.logger.info("\uD83D\uDD0D",$,Y,`discovers root atom "${T}"`);else{let Q=P9(W,T,G);W.logger.info("\uD83D\uDD0D",$,Y,`discovers root atoms: [ ${Q.map((_)=>`"${_}"`).join(", ")} ]`);for(let _ of Q)J.selectorAtoms=J.selectorAtoms.set({selectorKey:Y,atomKey:_})}G.add(T)};var N$=(W,$,Y,X)=>({get:(...G)=>{let J=s(W),H;if(G.length===2){let[z,F]=G;H=i1(W,z,F)}else[H]=G;let T=v1(W,H),Q=L$(W,T),_=H.key;return W.logger.info("\uD83D\uDD0C",$,Y,`registers dependency ( "${_}" =`,Q,")"),J.selectorGraph.set({upstreamSelectorKey:_,downstreamSelectorKey:Y},{source:H.key}),IJ(W,$,Y,H,X),Q},set:(...G)=>{let J,H;if(G.length===2)J=G[0],H=G[1];else{let _=G[0],z=G[1];H=G[2],J=i1(W,_,z)}let T=s(W),Q=v1(T,J);QY(T,Q,H)},find:(...G)=>i1(W,...G),json:(G)=>h2(W,G)});var f9=(W,$,Y)=>{let X=s(W),G=new Z0,J=new Set,{key:H,const:T}=$,Q="readonly_held_selector",{get:_,find:z,json:F}=N$(X,"readonly_held_selector",H,J),O={...$,type:"readonly_held_selector",subject:G,install:(E)=>f9(E,$,Y),get:()=>{return $.get({get:_,find:z,json:F},T),C1(s(W),H,T,G),J.clear(),T},...Y&&{family:Y}};X.readonlySelectors.set(H,O),W.logger.info("\u2728","readonly_held_selector",H,"=",T);let V={key:H,type:"readonly_held_selector"};if(Y)V.family=Y;return V};var b9=(W,$,Y)=>{let X=s(W),G=new Z0,J=new Set,H=$.key,T="readonly_pure_selector",{get:Q,find:_,json:z}=N$(X,"readonly_pure_selector",H,J),F=()=>{let E=$.get({get:Q,find:_,json:z});return C1(s(W),H,E,G),J.clear(),E},w={...$,type:"readonly_pure_selector",subject:G,install:(E)=>b9(E,$,Y),get:F,...Y&&{family:Y}};X.readonlySelectors.set(H,w);let O=F();W.logger.info("\u2728","readonly_pure_selector",H,"=",O);let V={key:H,type:"readonly_pure_selector"};if(Y)V.family=Y;return V};var x9=(W,$,Y)=>{let X=s(W),G=new Z0,J=new Set,{key:H,const:T}=$,Q="writable_held_selector",_=N$(X,"writable_held_selector",H,J),{find:z,get:F,json:w}=_,O={find:z,get:F,json:w},V=(B=$.get,P=s(W))=>{return B(O,T),C1(P,H,T,G),J.clear(),T},I={...$,type:"writable_held_selector",subject:G,install:(B)=>x9(B,$,Y),get:V,set:(B)=>{let P=s(W),g=V($.get,P),x=y2(B)(g);if(W.logger.info("\uD83D\uDCDD","writable_held_selector",H,"set (",g,"->",x,")"),C1(P,H,x,G),Z$(P,H),A$(P))G.next({newValue:x,oldValue:g});$.set(_,x)},...Y&&{family:Y}};X.writableSelectors.set(H,I);let j=V();W.logger.info("\u2728","writable_held_selector",H,"=",j);let N={key:H,type:"writable_held_selector"};if(Y)N.family=Y;return N};var s8=(W,$,Y)=>{let X=s(W),G=new Z0,J=new Set,H=$.key,T="writable_pure_selector",Q=N$(X,"writable_pure_selector",H,J),{find:_,get:z,json:F}=Q,w={find:_,get:z,json:F},O=(N=$.get,B=s(W))=>{let P=N(w);return C1(B,H,P,G),J.clear(),P},E={...$,type:"writable_pure_selector",subject:G,install:(N)=>s8(N,$,Y),get:O,set:(N)=>{let B=s(W),P=O($.get,B),g=y2(N)(P);if(W.logger.info("\uD83D\uDCDD","writable_pure_selector",H,"set (",P,"->",g,")"),C1(B,$.key,g,G),Z$(B,$.key),A$(B))G.next({newValue:g,oldValue:P});$.set(Q,g)},...Y&&{family:Y}};X.writableSelectors.set(H,E);let I=O();W.logger.info("\u2728",E.type,E.key,"=",I);let j={key:H,type:"writable_pure_selector"};if(Y)j.family=Y;return j};function MJ(W,$){let Y="set"in $,X="const"in $;if(X&&Y){let J=x9(W,$,void 0);return W.on.selectorCreation.next(J),J}if(X){let J=f9(W,$,void 0);return W.on.selectorCreation.next(J),J}if(Y){let J=s8(W,$,void 0);return W.on.selectorCreation.next(J),J}let G=b9(W,$,void 0);return W.on.selectorCreation.next(G),G}function q9(W,$,Y){let X=$.key,G="writable_pure_selector_family",J={key:X,type:"writable_pure_selector_family"},H=W.families.get(X);if(H)W.logger.error("\u2757","writable_pure_selector_family",X,`Overwriting an existing ${TY(H)} "${H.key}" in store "${W.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let T=new Z0,_=Object.assign((z)=>{let F=q1(z),w={key:X,subKey:F},O=`${X}(${F})`,V=s(W),E=s8(V,{key:O,get:$.get(z),set:$.set(z)},w);return T.next({type:"state_creation",token:E}),E},J,{internalRoles:Y,subject:T,install:(z)=>q9(z,$),default:(z)=>{return $.get(z)({get:(...w)=>e8(W,...w),find:(...w)=>i1(W,...w),json:(w)=>h2(W,w)})}});return W.families.set(X,_),J}function PJ(W,$,Y){let X=W.families.get($.key);if(X===void 0)throw new t8($,W);let G=X(Y),J=s(W);if(G.family){if(A$(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 fJ(W,$,Y){let X=q1(Y),G=`${$.key}(${X})`,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 r8(H);return H}function i1(W,$,Y){let X=fJ(W,$,Y);if(X)return X;let G=q1(Y),J=W.molecules.get(G);if(!J&&W.config.lifespan==="immortal"){let H=OJ($,Y);return W.logger.error("\u274C",H.type,H.key,`was not found in store "${W.config.name}"; returned a counterfeit token.`),H}if(X=PJ(W,$,Y),J)s(W).moleculeData.set(G,$.key);return X}function bJ(W,$){if($.family){let Y=W.families.get($.family.key);if(Y)return Y}}function R$(W,...$){let Y,X,G,J;if($.length===2){if(Y=$[0],J=$[1],X=bJ(W,Y)??null,X)G=Y.family?n8(Y.family.subKey):null,Y=i1(W,X,G)}else X=$[0],G=$[1],J=$[2],Y=i1(W,X,G);if("counterfeit"in Y&&"family"in Y){let Q=Y.family.subKey,_=W.disposalTraces.buffer.find((z)=>z?.key===Q);W.logger.error("\u274C",Y.type,Y.key,`could not be set because it was not found in the store "${W.config.name}".`,_?`This state was previously disposed:
|
|
4
|
-
${
|
|
5
|
-
${H.trace}`:"No previous disposal trace was found."),X.type){case"atom_family":case"mutable_atom_family":return W.defaults.get(X.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(X.key))return W.defaults.get(Y.family.key);let T=v1(W,X).default(J);return W.defaults.set(X.key,T),T}}}return L$(W,v1(W,Y))}class xJ{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 HY(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 Z0,atomDisposal:new Z0,selectorCreation:new Z0,selectorDisposal:new Z0,timelineCreation:new Z0,transactionCreation:new Z0,transactionApplying:new j9(null),operationClose:new Z0,moleculeCreation:new Z0,moleculeDisposal:new Z0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new k9("warn",(W,$,Y)=>!yJ(Y))];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},A$($))this.transactionMeta={epoch:new Map($?.transactionMeta.epoch),actionContinuities:new fW($?.transactionMeta.actionContinuities.toJSON())};for(let[,X]of $.families){if(X.internalRoles?.includes("mutable")||X.internalRoles?.includes("join"))continue;X.install(this)}let Y=new Set;for(let[,X]of $.atoms){if(Y.has(X.key))continue;if(X.install(this),X.type==="mutable_atom"){let G=h2($,X),J=vJ(X);Y.add(G.key),Y.add(J.key)}}for(let[,X]of $.readonlySelectors)X.install(this);for(let[,X]of $.writableSelectors){if(Y.has(X.key))continue;X.install(this)}for(let[,X]of $.transactions)X.install(this);for(let[,X]of $.timelines)X.install(this)}}}var VJ={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new xJ({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function v1(W,$){let Y,X=W;while(X!==null){switch($.type){case"atom":case"mutable_atom":Y=X.atoms.get($.key);break;case"writable_pure_selector":case"writable_held_selector":Y=X.writableSelectors.get($.key);break;case"readonly_pure_selector":case"readonly_held_selector":Y=X.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":Y=X.families.get($.key);break;case"timeline":Y=X.timelines.get($.key);break;case"transaction":Y=X.transactions.get($.key);break}if(Y)return Y;X=X.child}throw new t8($,W)}var hJ=(W,$)=>{let Y=s(W);if(Y.operation.open)return Y.operation.prev.get($.key);return Y.valueMap.get($.key)};var v9=(W,$)=>{let Y=s(W);return jJ($,W).map((G)=>{let J=Y.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 T=hJ(Y,$),Q=L$(Y,$);W.logger.info("\u2728",$.type,$.key,"went",T,"->",Q),$.subject.next({newValue:Q,oldValue:T})})})};function W4(W,$,Y,X){function G(F){if(W.operation.open){let w=W.on.operationClose.subscribe(`state subscription ${Y}`,()=>{w(),X(F)})}else X(F)}let J=v1(W,$);W.logger.info("\uD83D\uDC40",J.type,J.key,`Adding subscription "${Y}"`);let H=J.type==="writable_pure_selector"||J.type==="readonly_pure_selector",T=null,Q=G;if(H)T=v9(W,J),Q=(F)=>{if(T)T.length=0,T.push(...v9(W,J));G(F)};let _=J.subject.subscribe(Y,Q);return()=>{if(W.logger.info("\uD83D\uDE48",J.type,J.key,`Removing subscription "${Y}"`),_(),T)for(let F of T)F()}}var gJ=(W,$,Y,X)=>{let G=v1(W,$);W.logger.info("\uD83D\uDC40","timeline",$.key,`Adding subscription "${Y}"`);let J=G.subject.subscribe(Y,X);return()=>{W.logger.info("\uD83D\uDE48","timeline",$.key,`Removing subscription "${Y}" from timeline`),J()}};class y9{initializeState(W,$){let Y=`*${W.key}`;$.atoms.delete(Y),$.valueMap.delete(Y);let X=W.family?{key:`*${W.family.key}`,subKey:W.family.subKey}:void 0,G=h9($,{key:Y,default:null},X);if($.parent?.valueMap.has(Y)){let J=$.parent.valueMap.get(Y);$.valueMap.set(Y,J)}return G}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(W,$,Y){let X=`tracker:${Y.config.name}:${o1(Y)?Y.transactionMeta.update.key:"main"}:${W.key}`,G=e8(Y,W);this.unsubscribeFromInnerValue=G.subscribe(X,(J)=>{R$(Y,$,J)}),this.unsubscribeFromState=W4(Y,W,X,(J)=>{if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(X,(H)=>{R$(Y,$,H)})})}updateCore(W,$,Y){let X=`tracker:${Y.config.name}:${o1(Y)?Y.transactionMeta.update.key:"main"}:${W.key}`;W4(Y,$,X,({newValue:G,oldValue:J})=>{let H=Y.timelineTopics.getRelatedKey($.key);if(H){if(Y.timelines.get(H)?.timeTraveling){let _=gJ(Y,{key:H,type:"timeline"},X,(z)=>{_(),R$(Y,W,(F)=>{if(z==="redo"&&G)F.do(G);else if(z==="undo"&&J)F.undo(J);return F})});return}}let T=Y.on.operationClose.subscribe(X,()=>{T();let Q=e8(Y,W),_=G===null?-1:Q.getUpdateNumber(G),z=_-Q.cacheUpdateNumber;if(G&&z===1)R$(Y,W,(F)=>(F.do(G),F));else Y.logger.info("\u274C","mutable_atom",W.key,`could not be updated. Expected update number ${Q.cacheUpdateNumber+1}, but got ${_}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(W,$){this.mutableState=W;let Y=s($);this.latestUpdateState=this.initializeState(W,Y),this.observeCore(W,this.latestUpdateState,Y),this.updateCore(W,this.latestUpdateState,Y),Y.trackers.set(W.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),Y.trackers.delete(W.key)}}}var h2=(W,$)=>{if($.family){let X=s(W),J={key:`${$.family.key}:JSON`,type:"writable_pure_selector_family"},H=v1(X,J),T=JSON.parse($.family.subKey);return i1(W,H,T)}return{type:"writable_pure_selector",key:`${$.key}:JSON`}};var vJ=(W)=>{let Y={type:"atom",key:`*${W.key}`};if(W.family)Y.family={key:`*${W.family.key}`,subKey:W.family.subKey};return Y};function SJ(W){return typeof W==="object"&&W!==null&&"do"in W&&"undo"in W&&"subscribe"in W}function a8(W,$,Y){let X=Y.valueMap.get($.key),G=W.valueMap.get($.key);if(X!==G)return G;if(X===void 0)return $.default();Y.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let J=$.toJson(X),H=$.fromJson(J);return W.valueMap.set($.key,H),new y9($,Y),H}function C1(W,$,Y,X){let G=W.valueMap.get($);if(G instanceof i8)G.use(Y);if(Y instanceof Promise){let J=new i8(Y);return W.valueMap.set($,J),J.then((H)=>{C1(W,$,H,X),X.next({newValue:H,oldValue:J})}).catch((H)=>{W.logger.error("\uD83D\uDCA5","state",$,"rejected:",H)}),J}return W.valueMap.set($,Y),Y}var EJ=(W,$)=>{let Y=$.valueMap.get(W.key);if(W.type==="mutable_atom"&&o1($)){let{parent:X}=$;Y=a8($,W,X)}return Y},RJ=(W,$)=>{let Y=$.valueMap.get(W);if(Y instanceof i8){let X=Y,G=$.writableSelectors.get(W)??$.readonlySelectors.get(W);if(G)X.use(G.get());return}if($.operation.open)$.operation.prev.set(W,Y);$.valueMap.delete(W),$.logger.info("\uD83D\uDDD1","state",W,"evicted")};var qJ=(W,$)=>{return s(W).atomsThatAreDefault.has($)},mJ=(W,$)=>{let Y=s(W);Y.atomsThatAreDefault=new Set(Y.atomsThatAreDefault).add($)},CJ=(W,$)=>{let Y=s(W);Y.atomsThatAreDefault=new Set(s(W).atomsThatAreDefault),Y.atomsThatAreDefault.delete($)};function h9(W,$,Y){let{key:G,default:J}=$;W.logger.info("\uD83D\uDD28","atom",G,`creating in store "${W.config.name}"`);let H=s(W),T=H.atoms.get(G);if(T&&T.type==="atom")return W.logger.error("\u274C","atom",G,"Tried to create atom, but it already exists in the store."),r8(T);let Q=new Z0,_={...$,type:"atom",install:(w)=>{return w.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${w.config.name}"`),h9(w,$,Y)},subject:Q};if(Y)_.family=Y;let z=J;if(J instanceof Function)z=J();H.atoms.set(G,_),mJ(W,G),C1(H,G,z,Q);let F=r8(_);if($.effects){let w=0,O=[];for(let V of $.effects){let E=V({setSelf:(I)=>{R$(W,F,I)},onSet:(I)=>W4(W,F,`effect[${w}]`,I)});if(E)O.push(E);++w}_.cleanup=()=>{for(let V of O)V()}}return F}class g2 extends Set{mode="record";subject=new Z0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(W,$=0){super(W);if(W instanceof g2)this.parent=W,this.cacheUpdateNumber=W.cacheUpdateNumber;if($)this.cacheLimit=$,this.cache=new Array($),this.subscribe("auto cache",(Y)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=Y})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(W){let $=new g2(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:${q1(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:${q1(W)}`);return $}parent=null;child=null;transactionUpdates=null;transaction(W){this.mode="transaction",this.transactionUpdates=[],this.child=new g2(this);let $=this.child._subscribe("transaction",(Y)=>{this.transactionUpdates?.push(Y)});try{if(W(this.child)){for(let X of this.transactionUpdates)this.doStep(X);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(Y){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",Y),Y}finally{$(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(W,$){return this.subject.subscribe(W,$)}subscribe(W,$){return this.subject.subscribe(W,(Y)=>{$(`${this.cacheUpdateNumber}=${Y}`)})}emit(W){this.subject.next(W)}doStep(W){let $=W.indexOf(":"),Y=W.substring(0,$),X=W.substring($+1);switch(Y){case"add":this.add(JSON.parse(X));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(X));break;case"tx":for(let G of X.split(";"))this.doStep(G)}}getUpdateNumber(W){let $=W.indexOf("=");return Number(W.substring(0,$))}do(W){let $=W.indexOf("="),Y=Number(W.substring(0,$)),X=Y-this.cacheUpdateNumber;if(X>0){if(X===1){this.mode="playback";let J=W.substring($+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=Y,null}return this.cacheUpdateNumber+1}if(Math.abs(X)<this.cacheLimit){let J=this.cacheIdx+X;if(this.cache[J]===W)return null;this.mode="playback";let T=!1;while(!T){this.cacheIdx%=this.cacheLimit;let _=this.cache[this.cacheIdx];if(this.cacheIdx--,!_)return"OUT_OF_RANGE";this.undo(_),T=this.cacheIdx===J-1}let Q=W.substring($+1);return this.doStep(Q),this.mode="record",this.cacheUpdateNumber=Y,null}return"OUT_OF_RANGE"}undoStep(W){let $=W.indexOf(":"),Y=W.substring(0,$),X=W.substring($+1);switch(Y){case"add":this.delete(JSON.parse(X));break;case"del":this.add(JSON.parse(X));break;case"clear":{let G=JSON.parse(X);for(let J of G)this.add(J);break}case"tx":{let G=X.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 X=W.substring($+1);return this.undoStep(X),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function yJ(W){return W.startsWith("\uD83D\uDD0D ")}class FY{listeners;globalListeners;handleEvent(W,...$){for(let X of this.globalListeners)X(W,...$);let Y=this.listeners.get(W);if(Y)for(let X of Y)X(...$)}id="no_id_retrieved";emit;constructor(W){this.emit=W,this.listeners=new Map,this.globalListeners=new Set}on(W,$){let Y=this.listeners.get(W);if(Y)Y.add($);else this.listeners.set(W,new Set([$]));return this}onAny(W){return this.globalListeners.add(W),this}off(W,$){let Y=this.listeners.get(W);if(Y)if($)Y.delete($);else this.listeners.delete(W);return this}offAny(W){return this.globalListeners.delete(W),this}}class pJ extends FY{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(W){super((...$)=>{return this.out.next($),this});this.id=W,this.in=new Z0,this.out=new Z0,this.in.subscribe("socket",($)=>{this.handleEvent(...$)})}dispose(){for(let W of this.disposalFunctions)W()}}class g9 extends FY{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...W){this.process.stderr.write(q1(W.map(($)=>$ instanceof g2?`{ ${$.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 Y=JSON.stringify([W,...$]);return this.process.stdout.write(Y+"\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 Y=this.unprocessedEvents.shift();this.incompleteData+=Y??"";try{let X=n8(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",X),this.handleEvent(...X);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let J=n8(G);this.handleEvent(...J)}}this.incompleteData=""}catch(X){if(X instanceof Error)this.logger.error("\u2757",X.message,X.cause,X.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 pJ(`user:${W}`);this.relays.set(W,$),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let Y of this.relayServices){let X=Y($);if(X)$.disposalFunctions.push(X)}this.on(`user:${W}`,(...Y)=>{$.in.next(Y)}),$.out.subscribe("socket",(Y)=>{this.emit(...Y)})}),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 cJ=Symbol("Let zodToJsonSchema decide on which parser to use");var uJ={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"},dJ=(W)=>typeof W==="string"?{...uJ,name:W}:{...uJ,...W};var lJ=(W)=>{let $=dJ(W),Y=$.name!==void 0?[...$.basePath,$.definitionPath,$.name]:$.basePath;return{...$,currentPath:Y,propertyPath:void 0,seen:new Map(Object.entries($.definitions).map(([X,G])=>[G._def,{def:G._def,path:[...$.basePath,$.definitionPath,X],jsonSchema:void 0}]))}};function m9(W,$,Y,X){if(!X?.errorMessages)return;if(Y)W.errorMessage={...W.errorMessage,[$]:Y}}function K0(W,$,Y,X,G){W[$]=Y,m9(W,$,X,G)}var V0;(function(W){W.assertEqual=(G)=>{};function $(G){}W.assertIs=$;function Y(G){throw new Error}W.assertNever=Y,W.arrayToEnum=(G)=>{let J={};for(let H of G)J[H]=H;return J},W.getValidEnumValues=(G)=>{let J=W.objectKeys(G).filter((T)=>typeof G[G[T]]!=="number"),H={};for(let T of J)H[T]=G[T];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"&&Number.isFinite(G)&&Math.floor(G)===G;function X(G,J=" | "){return G.map((H)=>typeof H==="string"?`'${H}'`:H).join(J)}W.joinValues=X,W.jsonStringifyReplacer=(G,J)=>{if(typeof J==="bigint")return J.toString();return J}})(V0||(V0={}));var oJ;(function(W){W.mergeShapes=($,Y)=>{return{...$,...Y}}})(oJ||(oJ={}));var f=V0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),lW=(W)=>{switch(typeof W){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(W)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray(W))return f.array;if(W===null)return f.null;if(W.then&&typeof W.then==="function"&&W.catch&&typeof W.catch==="function")return f.promise;if(typeof Map!=="undefined"&&W instanceof Map)return f.map;if(typeof Set!=="undefined"&&W instanceof Set)return f.set;if(typeof Date!=="undefined"&&W instanceof Date)return f.date;return f.object;default:return f.unknown}};var S=V0.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 n1 extends Error{get errors(){return this.issues}constructor(W){super();this.issues=[],this.addIssue=(Y)=>{this.issues=[...this.issues,Y]},this.addIssues=(Y=[])=>{this.issues=[...this.issues,...Y]};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},Y={_errors:[]},X=(G)=>{for(let J of G.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)Y._errors.push($(J));else{let H=Y,T=0;while(T<J.path.length){let Q=J.path[T];if(T!==J.path.length-1)H[Q]=H[Q]||{_errors:[]};else H[Q]=H[Q]||{_errors:[]},H[Q]._errors.push($(J));H=H[Q],T++}}};return X(this),Y}static assert(W){if(!(W instanceof n1))throw new Error(`Not a ZodError: ${W}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(W=($)=>$.message){let $={},Y=[];for(let X of this.issues)if(X.path.length>0)$[X.path[0]]=$[X.path[0]]||[],$[X.path[0]].push(W(X));else Y.push(W(X));return{formErrors:Y,fieldErrors:$}}get formErrors(){return this.flatten()}}n1.create=(W)=>{return new n1(W)};var pD=(W,$)=>{let Y;switch(W.code){case S.invalid_type:if(W.received===f.undefined)Y="Required";else Y=`Expected ${W.expected}, received ${W.received}`;break;case S.invalid_literal:Y=`Invalid literal value, expected ${JSON.stringify(W.expected,V0.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:Y=`Unrecognized key(s) in object: ${V0.joinValues(W.keys,", ")}`;break;case S.invalid_union:Y="Invalid input";break;case S.invalid_union_discriminator:Y=`Invalid discriminator value. Expected ${V0.joinValues(W.options)}`;break;case S.invalid_enum_value:Y=`Invalid enum value. Expected ${V0.joinValues(W.options)}, received '${W.received}'`;break;case S.invalid_arguments:Y="Invalid function arguments";break;case S.invalid_return_type:Y="Invalid function return type";break;case S.invalid_date:Y="Invalid date";break;case S.invalid_string:if(typeof W.validation==="object")if("includes"in W.validation){if(Y=`Invalid input: must include "${W.validation.includes}"`,typeof W.validation.position==="number")Y=`${Y} at one or more positions greater than or equal to ${W.validation.position}`}else if("startsWith"in W.validation)Y=`Invalid input: must start with "${W.validation.startsWith}"`;else if("endsWith"in W.validation)Y=`Invalid input: must end with "${W.validation.endsWith}"`;else V0.assertNever(W.validation);else if(W.validation!=="regex")Y=`Invalid ${W.validation}`;else Y="Invalid";break;case S.too_small:if(W.type==="array")Y=`Array must contain ${W.exact?"exactly":W.inclusive?"at least":"more than"} ${W.minimum} element(s)`;else if(W.type==="string")Y=`String must contain ${W.exact?"exactly":W.inclusive?"at least":"over"} ${W.minimum} character(s)`;else if(W.type==="number")Y=`Number must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${W.minimum}`;else if(W.type==="date")Y=`Date must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(W.minimum))}`;else Y="Invalid input";break;case S.too_big:if(W.type==="array")Y=`Array must contain ${W.exact?"exactly":W.inclusive?"at most":"less than"} ${W.maximum} element(s)`;else if(W.type==="string")Y=`String must contain ${W.exact?"exactly":W.inclusive?"at most":"under"} ${W.maximum} character(s)`;else if(W.type==="number")Y=`Number must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="bigint")Y=`BigInt must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="date")Y=`Date must be ${W.exact?"exactly":W.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(W.maximum))}`;else Y="Invalid input";break;case S.custom:Y="Invalid input";break;case S.invalid_intersection_types:Y="Intersection results could not be merged";break;case S.not_multiple_of:Y=`Number must be a multiple of ${W.multipleOf}`;break;case S.not_finite:Y="Number must be finite";break;default:Y=$.defaultError,V0.assertNever(W)}return{message:Y}},B$=pD;var uD=B$;function $4(){return uD}var wY=(W)=>{let{data:$,path:Y,errorMaps:X,issueData:G}=W,J=[...Y,...G.path||[]],H={...G,path:J};if(G.message!==void 0)return{...G,path:J,message:G.message};let T="",Q=X.filter((_)=>!!_).slice().reverse();for(let _ of Q)T=_(H,{data:$,defaultError:T}).message;return{...G,path:J,message:T}};function h(W,$){let Y=$4(),X=wY({issueData:$,data:W.data,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,Y,Y===B$?void 0:B$].filter((G)=>!!G)});W.common.issues.push(X)}class L1{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(W,$){let Y=[];for(let X of $){if(X.status==="aborted")return $0;if(X.status==="dirty")W.dirty();Y.push(X.value)}return{status:W.value,value:Y}}static async mergeObjectAsync(W,$){let Y=[];for(let X of $){let G=await X.key,J=await X.value;Y.push({key:G,value:J})}return L1.mergeObjectSync(W,Y)}static mergeObjectSync(W,$){let Y={};for(let X of $){let{key:G,value:J}=X;if(G.status==="aborted")return $0;if(J.status==="aborted")return $0;if(G.status==="dirty")W.dirty();if(J.status==="dirty")W.dirty();if(G.value!=="__proto__"&&(typeof J.value!=="undefined"||X.alwaysSet))Y[G.value]=J.value}return{status:W.value,value:Y}}}var $0=Object.freeze({status:"aborted"}),m2=(W)=>({status:"dirty",value:W}),k1=(W)=>({status:"valid",value:W}),p9=(W)=>W.status==="aborted",u9=(W)=>W.status==="dirty",r$=(W)=>W.status==="valid",Y4=(W)=>typeof Promise!=="undefined"&&W instanceof Promise;var l;(function(W){W.errToObj=($)=>typeof $==="string"?{message:$}:$||{},W.toString=($)=>typeof $==="string"?$:$?.message})(l||(l={}));var UY=function(W,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},nJ=function(W,$,Y,X,G){if(X==="m")throw new TypeError("Private method is not writable");if(X==="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 X==="a"?G.call(W,Y):G?G.value=Y:$.set(W,Y),Y},X4,G4;class KW{constructor(W,$,Y,X){this._cachedPath=[],this.parent=W,this.data=$,this._path=Y,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var iJ=(W,$)=>{if(r$($))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 Y=new n1(W.common.issues);return this._error=Y,this._error}}}};function T0(W){if(!W)return{};let{errorMap:$,invalid_type_error:Y,required_error:X,description:G}=W;if($&&(Y||X))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,T)=>{let{message:Q}=W;if(H.code==="invalid_enum_value")return{message:Q??T.defaultError};if(typeof T.data==="undefined")return{message:Q??X??T.defaultError};if(H.code!=="invalid_type")return{message:T.defaultError};return{message:Q??Y??T.defaultError}},description:G}}class F0{get description(){return this._def.description}_getType(W){return lW(W.data)}_getOrReturnCtx(W,$){return $||{common:W.parent.common,data:W.data,parsedType:lW(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}_processInputParams(W){return{status:new L1,ctx:{common:W.parent.common,data:W.data,parsedType:lW(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}}_parseSync(W){let $=this._parse(W);if(Y4($))throw new Error("Synchronous parse encountered promise.");return $}_parseAsync(W){let $=this._parse(W);return Promise.resolve($)}parse(W,$){let Y=this.safeParse(W,$);if(Y.success)return Y.data;throw Y.error}safeParse(W,$){let Y={common:{issues:[],async:$?.async??!1,contextualErrorMap:$?.errorMap},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:lW(W)},X=this._parseSync({data:W,path:Y.path,parent:Y});return iJ(Y,X)}"~validate"(W){let $={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:lW(W)};if(!this["~standard"].async)try{let Y=this._parseSync({data:W,path:[],parent:$});return r$(Y)?{value:Y.value}:{issues:$.common.issues}}catch(Y){if(Y?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;$.common={issues:[],async:!0}}return this._parseAsync({data:W,path:[],parent:$}).then((Y)=>r$(Y)?{value:Y.value}:{issues:$.common.issues})}async parseAsync(W,$){let Y=await this.safeParseAsync(W,$);if(Y.success)return Y.data;throw Y.error}async safeParseAsync(W,$){let Y={common:{issues:[],contextualErrorMap:$?.errorMap,async:!0},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:lW(W)},X=this._parse({data:W,path:Y.path,parent:Y}),G=await(Y4(X)?X:Promise.resolve(X));return iJ(Y,G)}refine(W,$){let Y=(X)=>{if(typeof $==="string"||typeof $==="undefined")return{message:$};else if(typeof $==="function")return $(X);else return $};return this._refinement((X,G)=>{let J=W(X),H=()=>G.addIssue({code:S.custom,...Y(X)});if(typeof Promise!=="undefined"&&J instanceof Promise)return J.then((T)=>{if(!T)return H(),!1;else return!0});if(!J)return H(),!1;else return!0})}refinement(W,$){return this._refinement((Y,X)=>{if(!W(Y))return X.addIssue(typeof $==="function"?$(Y,X):$),!1;else return!0})}_refinement(W){return new xW({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 S$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return bW.create(this)}promise(){return l2.create(this,this._def)}or(W){return _4.create([this,W],this._def)}and(W){return z4.create(this,W,this._def)}transform(W){return new xW({...T0(this._def),schema:this,typeName:q.ZodEffects,effect:{type:"transform",transform:W}})}default(W){let $=typeof W==="function"?W:()=>W;return new D4({...T0(this._def),innerType:this,defaultValue:$,typeName:q.ZodDefault})}brand(){return new o9({typeName:q.ZodBranded,type:this,...T0(this._def)})}catch(W){let $=typeof W==="function"?W:()=>W;return new M4({...T0(this._def),innerType:this,catchValue:$,typeName:q.ZodCatch})}describe(W){return new this.constructor({...this._def,description:W})}pipe(W){return LY.create(this,W)}readonly(){return V4.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var cD=/^c[^\s-]{8,}$/i,dD=/^[0-9a-z]+$/,lD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,oD=/^[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,iD=/^[a-z0-9_-]{21}$/i,nD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rD=/^[-+]?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)?)??$/,tD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",c9,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])$/,eD=/^(?:(?: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])$/,WM=/^(([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]))$/,$M=/^(([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])$/,YM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,XM=/^([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])))",GM=new RegExp(`^${rJ}$`);function tJ(W){let $="[0-5]\\d";if(W.precision)$=`${$}\\.\\d{${W.precision}}`;else if(W.precision==null)$=`${$}(\\.\\d+)?`;let Y=W.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${Y}`}function JM(W){return new RegExp(`^${tJ(W)}$`)}function HM(W){let $=`${rJ}T${tJ(W)}`,Y=[];if(Y.push(W.local?"Z?":"Z"),W.offset)Y.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${Y.join("|")})`,new RegExp(`^${$}$`)}function TM(W,$){if(($==="v4"||!$)&&sD.test(W))return!0;if(($==="v6"||!$)&&WM.test(W))return!0;return!1}function QM(W,$){if(!nD.test(W))return!1;try{let[Y]=W.split("."),X=Y.replace(/-/g,"+").replace(/_/g,"/").padEnd(Y.length+(4-Y.length%4)%4,"="),G=JSON.parse(atob(X));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if($&&G.alg!==$)return!1;return!0}catch{return!1}}function _M(W,$){if(($==="v4"||!$)&&eD.test(W))return!0;if(($==="v6"||!$)&&$M.test(W))return!0;return!1}class iW extends F0{_parse(W){if(this._def.coerce)W.data=String(W.data);if(this._getType(W)!==f.string){let G=this._getOrReturnCtx(W);return h(G,{code:S.invalid_type,expected:f.string,received:G.parsedType}),$0}let Y=new L1,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if(W.data.length<G.value)X=this._getOrReturnCtx(W,X),h(X,{code:S.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),Y.dirty()}else if(G.kind==="max"){if(W.data.length>G.value)X=this._getOrReturnCtx(W,X),h(X,{code:S.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),Y.dirty()}else if(G.kind==="length"){let J=W.data.length>G.value,H=W.data.length<G.value;if(J||H){if(X=this._getOrReturnCtx(W,X),J)h(X,{code:S.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(H)h(X,{code:S.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});Y.dirty()}}else if(G.kind==="email"){if(!tD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"email",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="emoji"){if(!c9)c9=new RegExp(aD,"u");if(!c9.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"emoji",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="uuid"){if(!oD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"uuid",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="nanoid"){if(!iD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"nanoid",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="cuid"){if(!cD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"cuid",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="cuid2"){if(!dD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"cuid2",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="ulid"){if(!lD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"ulid",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="url")try{new URL(W.data)}catch{X=this._getOrReturnCtx(W,X),h(X,{validation:"url",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"regex",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="trim")W.data=W.data.trim();else if(G.kind==="includes"){if(!W.data.includes(G.value,G.position))X=this._getOrReturnCtx(W,X),h(X,{code:S.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),Y.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))X=this._getOrReturnCtx(W,X),h(X,{code:S.invalid_string,validation:{startsWith:G.value},message:G.message}),Y.dirty()}else if(G.kind==="endsWith"){if(!W.data.endsWith(G.value))X=this._getOrReturnCtx(W,X),h(X,{code:S.invalid_string,validation:{endsWith:G.value},message:G.message}),Y.dirty()}else if(G.kind==="datetime"){if(!HM(G).test(W.data))X=this._getOrReturnCtx(W,X),h(X,{code:S.invalid_string,validation:"datetime",message:G.message}),Y.dirty()}else if(G.kind==="date"){if(!GM.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{code:S.invalid_string,validation:"date",message:G.message}),Y.dirty()}else if(G.kind==="time"){if(!JM(G).test(W.data))X=this._getOrReturnCtx(W,X),h(X,{code:S.invalid_string,validation:"time",message:G.message}),Y.dirty()}else if(G.kind==="duration"){if(!rD.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"duration",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="ip"){if(!TM(W.data,G.version))X=this._getOrReturnCtx(W,X),h(X,{validation:"ip",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="jwt"){if(!QM(W.data,G.alg))X=this._getOrReturnCtx(W,X),h(X,{validation:"jwt",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="cidr"){if(!_M(W.data,G.version))X=this._getOrReturnCtx(W,X),h(X,{validation:"cidr",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="base64"){if(!YM.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"base64",code:S.invalid_string,message:G.message}),Y.dirty()}else if(G.kind==="base64url"){if(!XM.test(W.data))X=this._getOrReturnCtx(W,X),h(X,{validation:"base64url",code:S.invalid_string,message:G.message}),Y.dirty()}else V0.assertNever(G);return{status:Y.value,value:W.data}}_regex(W,$,Y){return this.refinement((X)=>W.test(X),{validation:$,code:S.invalid_string,...l.errToObj(Y)})}_addCheck(W){return new iW({...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){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?.precision==="undefined"?null:W?.precision,offset:W?.offset??!1,local:W?.local??!1,...l.errToObj(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?.precision==="undefined"?null:W?.precision,...l.errToObj(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:$?.position,...l.errToObj($?.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 iW({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new iW({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new iW({...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}}iW.create=(W)=>{return new iW({checks:[],typeName:q.ZodString,coerce:W?.coerce??!1,...T0(W)})};function zM(W,$){let Y=(W.toString().split(".")[1]||"").length,X=($.toString().split(".")[1]||"").length,G=Y>X?Y:X,J=Number.parseInt(W.toFixed(G).replace(".","")),H=Number.parseInt($.toFixed(G).replace(".",""));return J%H/10**G}class u2 extends F0{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)!==f.number){let G=this._getOrReturnCtx(W);return h(G,{code:S.invalid_type,expected:f.number,received:G.parsedType}),$0}let Y=void 0,X=new L1;for(let G of this._def.checks)if(G.kind==="int"){if(!V0.isInteger(W.data))Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.invalid_type,expected:"integer",received:"float",message:G.message}),X.dirty()}else if(G.kind==="min"){if(G.inclusive?W.data<G.value:W.data<=G.value)Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?W.data>G.value:W.data>=G.value)Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if(zM(W.data,G.value)!==0)Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else if(G.kind==="finite"){if(!Number.isFinite(W.data))Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.not_finite,message:G.message}),X.dirty()}else V0.assertNever(G);return{status:X.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,$,Y,X){return new u2({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:Y,message:l.toString(X)}]})}_addCheck(W){return new u2({...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"&&V0.isInteger(W.value))}get isFinite(){let W=null,$=null;for(let Y of this._def.checks)if(Y.kind==="finite"||Y.kind==="int"||Y.kind==="multipleOf")return!0;else if(Y.kind==="min"){if($===null||Y.value>$)$=Y.value}else if(Y.kind==="max"){if(W===null||Y.value<W)W=Y.value}return Number.isFinite($)&&Number.isFinite(W)}}u2.create=(W)=>{return new u2({checks:[],typeName:q.ZodNumber,coerce:W?.coerce||!1,...T0(W)})};class c2 extends F0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(W){if(this._def.coerce)try{W.data=BigInt(W.data)}catch{return this._getInvalidInput(W)}if(this._getType(W)!==f.bigint)return this._getInvalidInput(W);let Y=void 0,X=new L1;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?W.data<G.value:W.data<=G.value)Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?W.data>G.value:W.data>=G.value)Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if(W.data%G.value!==BigInt(0))Y=this._getOrReturnCtx(W,Y),h(Y,{code:S.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else V0.assertNever(G);return{status:X.value,value:W.data}}_getInvalidInput(W){let $=this._getOrReturnCtx(W);return h($,{code:S.invalid_type,expected:f.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,$,Y,X){return new c2({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:Y,message:l.toString(X)}]})}_addCheck(W){return new c2({...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}}c2.create=(W)=>{return new c2({checks:[],typeName:q.ZodBigInt,coerce:W?.coerce??!1,...T0(W)})};class DY extends F0{_parse(W){if(this._def.coerce)W.data=Boolean(W.data);if(this._getType(W)!==f.boolean){let Y=this._getOrReturnCtx(W);return h(Y,{code:S.invalid_type,expected:f.boolean,received:Y.parsedType}),$0}return k1(W.data)}}DY.create=(W)=>{return new DY({typeName:q.ZodBoolean,coerce:W?.coerce||!1,...T0(W)})};class H4 extends F0{_parse(W){if(this._def.coerce)W.data=new Date(W.data);if(this._getType(W)!==f.date){let G=this._getOrReturnCtx(W);return h(G,{code:S.invalid_type,expected:f.date,received:G.parsedType}),$0}if(Number.isNaN(W.data.getTime())){let G=this._getOrReturnCtx(W);return h(G,{code:S.invalid_date}),$0}let Y=new L1,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if(W.data.getTime()<G.value)X=this._getOrReturnCtx(W,X),h(X,{code:S.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),Y.dirty()}else if(G.kind==="max"){if(W.data.getTime()>G.value)X=this._getOrReturnCtx(W,X),h(X,{code:S.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),Y.dirty()}else V0.assertNever(G);return{status:Y.value,value:new Date(W.data.getTime())}}_addCheck(W){return new H4({...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}}H4.create=(W)=>{return new H4({checks:[],coerce:W?.coerce||!1,typeName:q.ZodDate,...T0(W)})};class MY extends F0{_parse(W){if(this._getType(W)!==f.symbol){let Y=this._getOrReturnCtx(W);return h(Y,{code:S.invalid_type,expected:f.symbol,received:Y.parsedType}),$0}return k1(W.data)}}MY.create=(W)=>{return new MY({typeName:q.ZodSymbol,...T0(W)})};class T4 extends F0{_parse(W){if(this._getType(W)!==f.undefined){let Y=this._getOrReturnCtx(W);return h(Y,{code:S.invalid_type,expected:f.undefined,received:Y.parsedType}),$0}return k1(W.data)}}T4.create=(W)=>{return new T4({typeName:q.ZodUndefined,...T0(W)})};class Q4 extends F0{_parse(W){if(this._getType(W)!==f.null){let Y=this._getOrReturnCtx(W);return h(Y,{code:S.invalid_type,expected:f.null,received:Y.parsedType}),$0}return k1(W.data)}}Q4.create=(W)=>{return new Q4({typeName:q.ZodNull,...T0(W)})};class VY extends F0{constructor(){super(...arguments);this._any=!0}_parse(W){return k1(W.data)}}VY.create=(W)=>{return new VY({typeName:q.ZodAny,...T0(W)})};class t$ extends F0{constructor(){super(...arguments);this._unknown=!0}_parse(W){return k1(W.data)}}t$.create=(W)=>{return new t$({typeName:q.ZodUnknown,...T0(W)})};class nW extends F0{_parse(W){let $=this._getOrReturnCtx(W);return h($,{code:S.invalid_type,expected:f.never,received:$.parsedType}),$0}}nW.create=(W)=>{return new nW({typeName:q.ZodNever,...T0(W)})};class OY extends F0{_parse(W){if(this._getType(W)!==f.undefined){let Y=this._getOrReturnCtx(W);return h(Y,{code:S.invalid_type,expected:f.void,received:Y.parsedType}),$0}return k1(W.data)}}OY.create=(W)=>{return new OY({typeName:q.ZodVoid,...T0(W)})};class bW extends F0{_parse(W){let{ctx:$,status:Y}=this._processInputParams(W),X=this._def;if($.parsedType!==f.array)return h($,{code:S.invalid_type,expected:f.array,received:$.parsedType}),$0;if(X.exactLength!==null){let J=$.data.length>X.exactLength.value,H=$.data.length<X.exactLength.value;if(J||H)h($,{code:J?S.too_big:S.too_small,minimum:H?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),Y.dirty()}if(X.minLength!==null){if($.data.length<X.minLength.value)h($,{code:S.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),Y.dirty()}if(X.maxLength!==null){if($.data.length>X.maxLength.value)h($,{code:S.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),Y.dirty()}if($.common.async)return Promise.all([...$.data].map((J,H)=>{return X.type._parseAsync(new KW($,J,$.path,H))})).then((J)=>{return L1.mergeArray(Y,J)});let G=[...$.data].map((J,H)=>{return X.type._parseSync(new KW($,J,$.path,H))});return L1.mergeArray(Y,G)}get element(){return this._def.type}min(W,$){return new bW({...this._def,minLength:{value:W,message:l.toString($)}})}max(W,$){return new bW({...this._def,maxLength:{value:W,message:l.toString($)}})}length(W,$){return new bW({...this._def,exactLength:{value:W,message:l.toString($)}})}nonempty(W){return this.min(1,W)}}bW.create=(W,$)=>{return new bW({type:W,minLength:null,maxLength:null,exactLength:null,typeName:q.ZodArray,...T0($)})};function p2(W){if(W instanceof o0){let $={};for(let Y in W.shape){let X=W.shape[Y];$[Y]=GW.create(p2(X))}return new o0({...W._def,shape:()=>$})}else if(W instanceof bW)return new bW({...W._def,type:p2(W.element)});else if(W instanceof GW)return GW.create(p2(W.unwrap()));else if(W instanceof S$)return S$.create(p2(W.unwrap()));else if(W instanceof rW)return rW.create(W.items.map(($)=>p2($)));else return W}class o0 extends F0{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(),$=V0.objectKeys(W);return this._cached={shape:W,keys:$},this._cached}_parse(W){if(this._getType(W)!==f.object){let Q=this._getOrReturnCtx(W);return h(Q,{code:S.invalid_type,expected:f.object,received:Q.parsedType}),$0}let{status:Y,ctx:X}=this._processInputParams(W),{shape:G,keys:J}=this._getCached(),H=[];if(!(this._def.catchall instanceof nW&&this._def.unknownKeys==="strip")){for(let Q in X.data)if(!J.includes(Q))H.push(Q)}let T=[];for(let Q of J){let _=G[Q],z=X.data[Q];T.push({key:{status:"valid",value:Q},value:_._parse(new KW(X,z,X.path,Q)),alwaysSet:Q in X.data})}if(this._def.catchall instanceof nW){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let _ of H)T.push({key:{status:"valid",value:_},value:{status:"valid",value:X.data[_]}});else if(Q==="strict"){if(H.length>0)h(X,{code:S.unrecognized_keys,keys:H}),Y.dirty()}else if(Q==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let _ of H){let z=X.data[_];T.push({key:{status:"valid",value:_},value:Q._parse(new KW(X,z,X.path,_)),alwaysSet:_ in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let _ of T){let z=await _.key,F=await _.value;Q.push({key:z,value:F,alwaysSet:_.alwaysSet})}return Q}).then((Q)=>{return L1.mergeObjectSync(Y,Q)});else return L1.mergeObjectSync(Y,T)}get shape(){return this._def.shape()}strict(W){return l.errToObj,new o0({...this._def,unknownKeys:"strict",...W!==void 0?{errorMap:($,Y)=>{let X=this._def.errorMap?.($,Y).message??Y.defaultError;if($.code==="unrecognized_keys")return{message:l.errToObj(W).message??X};return{message:X}}}:{}})}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 $={};for(let Y of V0.objectKeys(W))if(W[Y]&&this.shape[Y])$[Y]=this.shape[Y];return new o0({...this._def,shape:()=>$})}omit(W){let $={};for(let Y of V0.objectKeys(this.shape))if(!W[Y])$[Y]=this.shape[Y];return new o0({...this._def,shape:()=>$})}deepPartial(){return p2(this)}partial(W){let $={};for(let Y of V0.objectKeys(this.shape)){let X=this.shape[Y];if(W&&!W[Y])$[Y]=X;else $[Y]=X.optional()}return new o0({...this._def,shape:()=>$})}required(W){let $={};for(let Y of V0.objectKeys(this.shape))if(W&&!W[Y])$[Y]=this.shape[Y];else{let G=this.shape[Y];while(G instanceof GW)G=G._def.innerType;$[Y]=G}return new o0({...this._def,shape:()=>$})}keyof(){return aJ(V0.objectKeys(this.shape))}}o0.create=(W,$)=>{return new o0({shape:()=>W,unknownKeys:"strip",catchall:nW.create(),typeName:q.ZodObject,...T0($)})};o0.strictCreate=(W,$)=>{return new o0({shape:()=>W,unknownKeys:"strict",catchall:nW.create(),typeName:q.ZodObject,...T0($)})};o0.lazycreate=(W,$)=>{return new o0({shape:W,unknownKeys:"strip",catchall:nW.create(),typeName:q.ZodObject,...T0($)})};class _4 extends F0{_parse(W){let{ctx:$}=this._processInputParams(W),Y=this._def.options;function X(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 n1(H.ctx.common.issues));return h($,{code:S.invalid_union,unionErrors:J}),$0}if($.common.async)return Promise.all(Y.map(async(G)=>{let J={...$,common:{...$.common,issues:[]},parent:null};return{result:await G._parseAsync({data:$.data,path:$.path,parent:J}),ctx:J}})).then(X);else{let G=void 0,J=[];for(let T of Y){let Q={...$,common:{...$.common,issues:[]},parent:null},_=T._parseSync({data:$.data,path:$.path,parent:Q});if(_.status==="valid")return _;else if(_.status==="dirty"&&!G)G={result:_,ctx:Q};if(Q.common.issues.length)J.push(Q.common.issues)}if(G)return $.common.issues.push(...G.ctx.common.issues),G.result;let H=J.map((T)=>new n1(T));return h($,{code:S.invalid_union,unionErrors:H}),$0}}get options(){return this._def.options}}_4.create=(W,$)=>{return new _4({options:W,typeName:q.ZodUnion,...T0($)})};var oW=(W)=>{if(W instanceof F4)return oW(W.schema);else if(W instanceof xW)return oW(W.innerType());else if(W instanceof w4)return[W.value];else if(W instanceof a$)return W.options;else if(W instanceof U4)return V0.objectValues(W.enum);else if(W instanceof D4)return oW(W._def.innerType);else if(W instanceof T4)return[void 0];else if(W instanceof Q4)return[null];else if(W instanceof GW)return[void 0,...oW(W.unwrap())];else if(W instanceof S$)return[null,...oW(W.unwrap())];else if(W instanceof o9)return oW(W.unwrap());else if(W instanceof V4)return oW(W.unwrap());else if(W instanceof M4)return oW(W._def.innerType);else return[]};class l9 extends F0{_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==f.object)return h($,{code:S.invalid_type,expected:f.object,received:$.parsedType}),$0;let Y=this.discriminator,X=$.data[Y],G=this.optionsMap.get(X);if(!G)return h($,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Y]}),$0;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,$,Y){let X=new Map;for(let G of $){let J=oW(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(X.has(H))throw new Error(`Discriminator property ${String(W)} has duplicate value ${String(H)}`);X.set(H,G)}}return new l9({typeName:q.ZodDiscriminatedUnion,discriminator:W,options:$,optionsMap:X,...T0(Y)})}}function d9(W,$){let Y=lW(W),X=lW($);if(W===$)return{valid:!0,data:W};else if(Y===f.object&&X===f.object){let G=V0.objectKeys($),J=V0.objectKeys(W).filter((T)=>G.indexOf(T)!==-1),H={...W,...$};for(let T of J){let Q=d9(W[T],$[T]);if(!Q.valid)return{valid:!1};H[T]=Q.data}return{valid:!0,data:H}}else if(Y===f.array&&X===f.array){if(W.length!==$.length)return{valid:!1};let G=[];for(let J=0;J<W.length;J++){let H=W[J],T=$[J],Q=d9(H,T);if(!Q.valid)return{valid:!1};G.push(Q.data)}return{valid:!0,data:G}}else if(Y===f.date&&X===f.date&&+W===+$)return{valid:!0,data:W};else return{valid:!1}}class z4 extends F0{_parse(W){let{status:$,ctx:Y}=this._processInputParams(W),X=(G,J)=>{if(p9(G)||p9(J))return $0;let H=d9(G.value,J.value);if(!H.valid)return h(Y,{code:S.invalid_intersection_types}),$0;if(u9(G)||u9(J))$.dirty();return{status:$.value,value:H.data}};if(Y.common.async)return Promise.all([this._def.left._parseAsync({data:Y.data,path:Y.path,parent:Y}),this._def.right._parseAsync({data:Y.data,path:Y.path,parent:Y})]).then(([G,J])=>X(G,J));else return X(this._def.left._parseSync({data:Y.data,path:Y.path,parent:Y}),this._def.right._parseSync({data:Y.data,path:Y.path,parent:Y}))}}z4.create=(W,$,Y)=>{return new z4({left:W,right:$,typeName:q.ZodIntersection,...T0(Y)})};class rW extends F0{_parse(W){let{status:$,ctx:Y}=this._processInputParams(W);if(Y.parsedType!==f.array)return h(Y,{code:S.invalid_type,expected:f.array,received:Y.parsedType}),$0;if(Y.data.length<this._def.items.length)return h(Y,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$0;if(!this._def.rest&&Y.data.length>this._def.items.length)h(Y,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let G=[...Y.data].map((J,H)=>{let T=this._def.items[H]||this._def.rest;if(!T)return null;return T._parse(new KW(Y,J,Y.path,H))}).filter((J)=>!!J);if(Y.common.async)return Promise.all(G).then((J)=>{return L1.mergeArray($,J)});else return L1.mergeArray($,G)}get items(){return this._def.items}rest(W){return new rW({...this._def,rest:W})}}rW.create=(W,$)=>{if(!Array.isArray(W))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rW({items:W,typeName:q.ZodTuple,rest:null,...T0($)})};class KY extends F0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:Y}=this._processInputParams(W);if(Y.parsedType!==f.object)return h(Y,{code:S.invalid_type,expected:f.object,received:Y.parsedType}),$0;let X=[],G=this._def.keyType,J=this._def.valueType;for(let H in Y.data)X.push({key:G._parse(new KW(Y,H,Y.path,H)),value:J._parse(new KW(Y,Y.data[H],Y.path,H)),alwaysSet:H in Y.data});if(Y.common.async)return L1.mergeObjectAsync($,X);else return L1.mergeObjectSync($,X)}get element(){return this._def.valueType}static create(W,$,Y){if($ instanceof F0)return new KY({keyType:W,valueType:$,typeName:q.ZodRecord,...T0(Y)});return new KY({keyType:iW.create(),valueType:W,typeName:q.ZodRecord,...T0($)})}}class EY extends F0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:Y}=this._processInputParams(W);if(Y.parsedType!==f.map)return h(Y,{code:S.invalid_type,expected:f.map,received:Y.parsedType}),$0;let X=this._def.keyType,G=this._def.valueType,J=[...Y.data.entries()].map(([H,T],Q)=>{return{key:X._parse(new KW(Y,H,Y.path,[Q,"key"])),value:G._parse(new KW(Y,T,Y.path,[Q,"value"]))}});if(Y.common.async){let H=new Map;return Promise.resolve().then(async()=>{for(let T of J){let Q=await T.key,_=await T.value;if(Q.status==="aborted"||_.status==="aborted")return $0;if(Q.status==="dirty"||_.status==="dirty")$.dirty();H.set(Q.value,_.value)}return{status:$.value,value:H}})}else{let H=new Map;for(let T of J){let{key:Q,value:_}=T;if(Q.status==="aborted"||_.status==="aborted")return $0;if(Q.status==="dirty"||_.status==="dirty")$.dirty();H.set(Q.value,_.value)}return{status:$.value,value:H}}}}EY.create=(W,$,Y)=>{return new EY({valueType:$,keyType:W,typeName:q.ZodMap,...T0(Y)})};class d2 extends F0{_parse(W){let{status:$,ctx:Y}=this._processInputParams(W);if(Y.parsedType!==f.set)return h(Y,{code:S.invalid_type,expected:f.set,received:Y.parsedType}),$0;let X=this._def;if(X.minSize!==null){if(Y.data.size<X.minSize.value)h(Y,{code:S.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),$.dirty()}if(X.maxSize!==null){if(Y.data.size>X.maxSize.value)h(Y,{code:S.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),$.dirty()}let G=this._def.valueType;function J(T){let Q=new Set;for(let _ of T){if(_.status==="aborted")return $0;if(_.status==="dirty")$.dirty();Q.add(_.value)}return{status:$.value,value:Q}}let H=[...Y.data.values()].map((T,Q)=>G._parse(new KW(Y,T,Y.path,Q)));if(Y.common.async)return Promise.all(H).then((T)=>J(T));else return J(H)}min(W,$){return new d2({...this._def,minSize:{value:W,message:l.toString($)}})}max(W,$){return new d2({...this._def,maxSize:{value:W,message:l.toString($)}})}size(W,$){return this.min(W,$).max(W,$)}nonempty(W){return this.min(1,W)}}d2.create=(W,$)=>{return new d2({valueType:W,minSize:null,maxSize:null,typeName:q.ZodSet,...T0($)})};class J4 extends F0{constructor(){super(...arguments);this.validate=this.implement}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==f.function)return h($,{code:S.invalid_type,expected:f.function,received:$.parsedType}),$0;function Y(H,T){return wY({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,$4(),B$].filter((Q)=>!!Q),issueData:{code:S.invalid_arguments,argumentsError:T}})}function X(H,T){return wY({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,$4(),B$].filter((Q)=>!!Q),issueData:{code:S.invalid_return_type,returnTypeError:T}})}let G={errorMap:$.common.contextualErrorMap},J=$.data;if(this._def.returns instanceof l2){let H=this;return k1(async function(...T){let Q=new n1([]),_=await H._def.args.parseAsync(T,G).catch((w)=>{throw Q.addIssue(Y(T,w)),Q}),z=await Reflect.apply(J,this,_);return await H._def.returns._def.type.parseAsync(z,G).catch((w)=>{throw Q.addIssue(X(z,w)),Q})})}else{let H=this;return k1(function(...T){let Q=H._def.args.safeParse(T,G);if(!Q.success)throw new n1([Y(T,Q.error)]);let _=Reflect.apply(J,this,Q.data),z=H._def.returns.safeParse(_,G);if(!z.success)throw new n1([X(_,z.error)]);return z.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...W){return new J4({...this._def,args:rW.create(W).rest(t$.create())})}returns(W){return new J4({...this._def,returns:W})}implement(W){return this.parse(W)}strictImplement(W){return this.parse(W)}static create(W,$,Y){return new J4({args:W?W:rW.create([]).rest(t$.create()),returns:$||t$.create(),typeName:q.ZodFunction,...T0(Y)})}}class F4 extends F0{get schema(){return this._def.getter()}_parse(W){let{ctx:$}=this._processInputParams(W);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}F4.create=(W,$)=>{return new F4({getter:W,typeName:q.ZodLazy,...T0($)})};class w4 extends F0{_parse(W){if(W.data!==this._def.value){let $=this._getOrReturnCtx(W);return h($,{received:$.data,code:S.invalid_literal,expected:this._def.value}),$0}return{status:"valid",value:W.data}}get value(){return this._def.value}}w4.create=(W,$)=>{return new w4({value:W,typeName:q.ZodLiteral,...T0($)})};function aJ(W,$){return new a$({values:W,typeName:q.ZodEnum,...T0($)})}class a$ extends F0{constructor(){super(...arguments);X4.set(this,void 0)}_parse(W){if(typeof W.data!=="string"){let $=this._getOrReturnCtx(W),Y=this._def.values;return h($,{expected:V0.joinValues(Y),received:$.parsedType,code:S.invalid_type}),$0}if(!UY(this,X4,"f"))nJ(this,X4,new Set(this._def.values),"f");if(!UY(this,X4,"f").has(W.data)){let $=this._getOrReturnCtx(W),Y=this._def.values;return h($,{received:$.data,code:S.invalid_enum_value,options:Y}),$0}return k1(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 a$.create(W,{...this._def,...$})}exclude(W,$=this._def){return a$.create(this.options.filter((Y)=>!W.includes(Y)),{...this._def,...$})}}X4=new WeakMap;a$.create=aJ;class U4 extends F0{constructor(){super(...arguments);G4.set(this,void 0)}_parse(W){let $=V0.getValidEnumValues(this._def.values),Y=this._getOrReturnCtx(W);if(Y.parsedType!==f.string&&Y.parsedType!==f.number){let X=V0.objectValues($);return h(Y,{expected:V0.joinValues(X),received:Y.parsedType,code:S.invalid_type}),$0}if(!UY(this,G4,"f"))nJ(this,G4,new Set(V0.getValidEnumValues(this._def.values)),"f");if(!UY(this,G4,"f").has(W.data)){let X=V0.objectValues($);return h(Y,{received:Y.data,code:S.invalid_enum_value,options:X}),$0}return k1(W.data)}get enum(){return this._def.values}}G4=new WeakMap;U4.create=(W,$)=>{return new U4({values:W,typeName:q.ZodNativeEnum,...T0($)})};class l2 extends F0{unwrap(){return this._def.type}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==f.promise&&$.common.async===!1)return h($,{code:S.invalid_type,expected:f.promise,received:$.parsedType}),$0;let Y=$.parsedType===f.promise?$.data:Promise.resolve($.data);return k1(Y.then((X)=>{return this._def.type.parseAsync(X,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}l2.create=(W,$)=>{return new l2({type:W,typeName:q.ZodPromise,...T0($)})};class xW extends F0{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:Y}=this._processInputParams(W),X=this._def.effect||null,G={addIssue:(J)=>{if(h(Y,J),J.fatal)$.abort();else $.dirty()},get path(){return Y.path}};if(G.addIssue=G.addIssue.bind(G),X.type==="preprocess"){let J=X.transform(Y.data,G);if(Y.common.async)return Promise.resolve(J).then(async(H)=>{if($.value==="aborted")return $0;let T=await this._def.schema._parseAsync({data:H,path:Y.path,parent:Y});if(T.status==="aborted")return $0;if(T.status==="dirty")return m2(T.value);if($.value==="dirty")return m2(T.value);return T});else{if($.value==="aborted")return $0;let H=this._def.schema._parseSync({data:J,path:Y.path,parent:Y});if(H.status==="aborted")return $0;if(H.status==="dirty")return m2(H.value);if($.value==="dirty")return m2(H.value);return H}}if(X.type==="refinement"){let J=(H)=>{let T=X.refinement(H,G);if(Y.common.async)return Promise.resolve(T);if(T instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return H};if(Y.common.async===!1){let H=this._def.schema._parseSync({data:Y.data,path:Y.path,parent:Y});if(H.status==="aborted")return $0;if(H.status==="dirty")$.dirty();return J(H.value),{status:$.value,value:H.value}}else return this._def.schema._parseAsync({data:Y.data,path:Y.path,parent:Y}).then((H)=>{if(H.status==="aborted")return $0;if(H.status==="dirty")$.dirty();return J(H.value).then(()=>{return{status:$.value,value:H.value}})})}if(X.type==="transform")if(Y.common.async===!1){let J=this._def.schema._parseSync({data:Y.data,path:Y.path,parent:Y});if(!r$(J))return J;let H=X.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:Y.data,path:Y.path,parent:Y}).then((J)=>{if(!r$(J))return J;return Promise.resolve(X.transform(J.value,G)).then((H)=>({status:$.value,value:H}))});V0.assertNever(X)}}xW.create=(W,$,Y)=>{return new xW({schema:W,typeName:q.ZodEffects,effect:$,...T0(Y)})};xW.createWithPreprocess=(W,$,Y)=>{return new xW({schema:$,effect:{type:"preprocess",transform:W},typeName:q.ZodEffects,...T0(Y)})};class GW extends F0{_parse(W){if(this._getType(W)===f.undefined)return k1(void 0);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}GW.create=(W,$)=>{return new GW({innerType:W,typeName:q.ZodOptional,...T0($)})};class S$ extends F0{_parse(W){if(this._getType(W)===f.null)return k1(null);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}S$.create=(W,$)=>{return new S$({innerType:W,typeName:q.ZodNullable,...T0($)})};class D4 extends F0{_parse(W){let{ctx:$}=this._processInputParams(W),Y=$.data;if($.parsedType===f.undefined)Y=this._def.defaultValue();return this._def.innerType._parse({data:Y,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}D4.create=(W,$)=>{return new D4({innerType:W,typeName:q.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...T0($)})};class M4 extends F0{_parse(W){let{ctx:$}=this._processInputParams(W),Y={...$,common:{...$.common,issues:[]}},X=this._def.innerType._parse({data:Y.data,path:Y.path,parent:{...Y}});if(Y4(X))return X.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new n1(Y.common.issues)},input:Y.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new n1(Y.common.issues)},input:Y.data})}}removeCatch(){return this._def.innerType}}M4.create=(W,$)=>{return new M4({innerType:W,typeName:q.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...T0($)})};class AY extends F0{_parse(W){if(this._getType(W)!==f.nan){let Y=this._getOrReturnCtx(W);return h(Y,{code:S.invalid_type,expected:f.nan,received:Y.parsedType}),$0}return{status:"valid",value:W.data}}}AY.create=(W)=>{return new AY({typeName:q.ZodNaN,...T0(W)})};var FS=Symbol("zod_brand");class o9 extends F0{_parse(W){let{ctx:$}=this._processInputParams(W),Y=$.data;return this._def.type._parse({data:Y,path:$.path,parent:$})}unwrap(){return this._def.type}}class LY extends F0{_parse(W){let{status:$,ctx:Y}=this._processInputParams(W);if(Y.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:Y.data,path:Y.path,parent:Y});if(G.status==="aborted")return $0;if(G.status==="dirty")return $.dirty(),m2(G.value);else return this._def.out._parseAsync({data:G.value,path:Y.path,parent:Y})})();else{let X=this._def.in._parseSync({data:Y.data,path:Y.path,parent:Y});if(X.status==="aborted")return $0;if(X.status==="dirty")return $.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:Y.path,parent:Y})}}static create(W,$){return new LY({in:W,out:$,typeName:q.ZodPipeline})}}class V4 extends F0{_parse(W){let $=this._def.innerType._parse(W),Y=(X)=>{if(r$(X))X.value=Object.freeze(X.value);return X};return Y4($)?$.then((X)=>Y(X)):Y($)}unwrap(){return this._def.innerType}}V4.create=(W,$)=>{return new V4({innerType:W,typeName:q.ZodReadonly,...T0($)})};var wS={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 US=iW.create,DS=u2.create,MS=AY.create,VS=c2.create,OS=DY.create,KS=H4.create,ES=MY.create,AS=T4.create,LS=Q4.create,ZS=VY.create,NS=t$.create,RS=nW.create,BS=OY.create,SS=bW.create,qS=o0.create,CS=o0.strictCreate,kS=_4.create,jS=l9.create,IS=z4.create,PS=rW.create,fS=KY.create,bS=EY.create,xS=d2.create,vS=J4.create,yS=F4.create,hS=w4.create,gS=a$.create,mS=U4.create,pS=l2.create,uS=xW.create,cS=GW.create,dS=S$.create,lS=xW.createWithPreprocess,oS=LY.create;function sJ(){return{}}function eJ(W,$){let Y={type:"array"};if(W.type?._def&&W.type?._def?.typeName!==q.ZodAny)Y.items=W0(W.type._def,{...$,currentPath:[...$.currentPath,"items"]});if(W.minLength)K0(Y,"minItems",W.minLength.value,W.minLength.message,$);if(W.maxLength)K0(Y,"maxItems",W.maxLength.value,W.maxLength.message,$);if(W.exactLength)K0(Y,"minItems",W.exactLength.value,W.exactLength.message,$),K0(Y,"maxItems",W.exactLength.value,W.exactLength.message,$);return Y}function W3(W,$){let Y={type:"integer",format:"int64"};if(!W.checks)return Y;for(let X of W.checks)switch(X.kind){case"min":if($.target==="jsonSchema7")if(X.inclusive)K0(Y,"minimum",X.value,X.message,$);else K0(Y,"exclusiveMinimum",X.value,X.message,$);else{if(!X.inclusive)Y.exclusiveMinimum=!0;K0(Y,"minimum",X.value,X.message,$)}break;case"max":if($.target==="jsonSchema7")if(X.inclusive)K0(Y,"maximum",X.value,X.message,$);else K0(Y,"exclusiveMaximum",X.value,X.message,$);else{if(!X.inclusive)Y.exclusiveMaximum=!0;K0(Y,"maximum",X.value,X.message,$)}break;case"multipleOf":K0(Y,"multipleOf",X.value,X.message,$);break}return Y}function $3(){return{type:"boolean"}}function ZY(W,$){return W0(W.type._def,$)}var Y3=(W,$)=>{return W0(W.innerType._def,$)};function i9(W,$,Y){let X=Y??$.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((G,J)=>i9(W,$,G))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return FM(W,$)}}var FM=(W,$)=>{let Y={type:"integer",format:"unix-time"};if($.target==="openApi3")return Y;for(let X of W.checks)switch(X.kind){case"min":K0(Y,"minimum",X.value,X.message,$);break;case"max":K0(Y,"maximum",X.value,X.message,$);break}return Y};function X3(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 wM=(W)=>{if("type"in W&&W.type==="string")return!1;return"allOf"in W};function H3(W,$){let Y=[W0(W.left._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),W0(W.right._def,{...$,currentPath:[...$.currentPath,"allOf","1"]})].filter((J)=>!!J),X=$.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,G=[];return Y.forEach((J)=>{if(wM(J)){if(G.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let H=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:T,...Q}=J;H=Q}else X=void 0;G.push(H)}}),G.length?{allOf:G,...X}:void 0}function T3(W,$){let Y=typeof W.value;if(Y!=="bigint"&&Y!=="number"&&Y!=="boolean"&&Y!=="string")return{type:Array.isArray(W.value)?"array":"object"};if($.target==="openApi3")return{type:Y==="bigint"?"integer":Y,enum:[W.value]};return{type:Y==="bigint"?"integer":Y,const:W.value}}var n9=void 0,EW={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(n9===void 0)n9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return n9},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 NY(W,$){let Y={type:"string"};if(W.checks)for(let X of W.checks)switch(X.kind){case"min":K0(Y,"minLength",typeof Y.minLength==="number"?Math.max(Y.minLength,X.value):X.value,X.message,$);break;case"max":K0(Y,"maxLength",typeof Y.maxLength==="number"?Math.min(Y.maxLength,X.value):X.value,X.message,$);break;case"email":switch($.emailStrategy){case"format:email":AW(Y,"email",X.message,$);break;case"format:idn-email":AW(Y,"idn-email",X.message,$);break;case"pattern:zod":j1(Y,EW.email,X.message,$);break}break;case"url":AW(Y,"uri",X.message,$);break;case"uuid":AW(Y,"uuid",X.message,$);break;case"regex":j1(Y,X.regex,X.message,$);break;case"cuid":j1(Y,EW.cuid,X.message,$);break;case"cuid2":j1(Y,EW.cuid2,X.message,$);break;case"startsWith":j1(Y,RegExp(`^${r9(X.value,$)}`),X.message,$);break;case"endsWith":j1(Y,RegExp(`${r9(X.value,$)}$`),X.message,$);break;case"datetime":AW(Y,"date-time",X.message,$);break;case"date":AW(Y,"date",X.message,$);break;case"time":AW(Y,"time",X.message,$);break;case"duration":AW(Y,"duration",X.message,$);break;case"length":K0(Y,"minLength",typeof Y.minLength==="number"?Math.max(Y.minLength,X.value):X.value,X.message,$),K0(Y,"maxLength",typeof Y.maxLength==="number"?Math.min(Y.maxLength,X.value):X.value,X.message,$);break;case"includes":{j1(Y,RegExp(r9(X.value,$)),X.message,$);break}case"ip":{if(X.version!=="v6")AW(Y,"ipv4",X.message,$);if(X.version!=="v4")AW(Y,"ipv6",X.message,$);break}case"base64url":j1(Y,EW.base64url,X.message,$);break;case"jwt":j1(Y,EW.jwt,X.message,$);break;case"cidr":{if(X.version!=="v6")j1(Y,EW.ipv4Cidr,X.message,$);if(X.version!=="v4")j1(Y,EW.ipv6Cidr,X.message,$);break}case"emoji":j1(Y,EW.emoji(),X.message,$);break;case"ulid":{j1(Y,EW.ulid,X.message,$);break}case"base64":{switch($.base64Strategy){case"format:binary":{AW(Y,"binary",X.message,$);break}case"contentEncoding:base64":{K0(Y,"contentEncoding","base64",X.message,$);break}case"pattern:zod":{j1(Y,EW.base64,X.message,$);break}}break}case"nanoid":j1(Y,EW.nanoid,X.message,$);case"toLowerCase":case"toUpperCase":case"trim":break;default:((G)=>{})(X)}return Y}function r9(W,$){return $.patternStrategy==="escape"?DM(W):W}var UM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function DM(W){let $="";for(let Y=0;Y<W.length;Y++){if(!UM.has(W[Y]))$+="\\";$+=W[Y]}return $}function AW(W,$,Y,X){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&&X.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:$,...Y&&X.errorMessages&&{errorMessage:{format:Y}}})}else K0(W,"format",$,Y,X)}function j1(W,$,Y,X){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&&X.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:Q3($,X),...Y&&X.errorMessages&&{errorMessage:{pattern:Y}}})}else K0(W,"pattern",Q3($,X),Y,X)}function Q3(W,$){if(!$.applyRegexFlags||!W.flags)return W.source;let Y={i:W.flags.includes("i"),m:W.flags.includes("m"),s:W.flags.includes("s")},X=Y.i?W.source.toLowerCase():W.source,G="",J=!1,H=!1,T=!1;for(let Q=0;Q<X.length;Q++){if(J){G+=X[Q],J=!1;continue}if(Y.i){if(H){if(X[Q].match(/[a-z]/)){if(T)G+=X[Q],G+=`${X[Q-2]}-${X[Q]}`.toUpperCase(),T=!1;else if(X[Q+1]==="-"&&X[Q+2]?.match(/[a-z]/))G+=X[Q],T=!0;else G+=`${X[Q]}${X[Q].toUpperCase()}`;continue}}else if(X[Q].match(/[a-z]/)){G+=`[${X[Q]}${X[Q].toUpperCase()}]`;continue}}if(Y.m){if(X[Q]==="^"){G+=`(^|(?<=[\r
|
|
6
|
-
]))`;continue}else if(X[Q]==="$"){G+=`($|(?=[\r
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
]`;continue}if(G+=X[Q],X[Q]==="\\")J=!0;else if(H&&X[Q]==="]")H=!1;else if(!H&&X[Q]==="[")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 RY(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((X,G)=>({...X,[G]:W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"properties",G]})??{}}),{}),additionalProperties:$.rejectedAdditionalProperties};let Y={type:"object",additionalProperties:W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]})??$.allowedAdditionalProperties};if($.target==="openApi3")return Y;if(W.keyType?._def.typeName===q.ZodString&&W.keyType._def.checks?.length){let{type:X,...G}=NY(W.keyType._def,$);return{...Y,propertyNames:G}}else if(W.keyType?._def.typeName===q.ZodEnum)return{...Y,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:X,...G}=ZY(W.keyType._def,$);return{...Y,propertyNames:G}}return Y}function _3(W,$){if($.mapStrategy==="record")return RY(W,$);let Y=W0(W.keyType._def,{...$,currentPath:[...$.currentPath,"items","items","0"]})||{},X=W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[Y,X],minItems:2,maxItems:2}}}function z3(W){let $=W.values,X=Object.keys(W.values).filter((J)=>{return typeof $[$[J]]!=="number"}).map((J)=>$[J]),G=Array.from(new Set(X.map((J)=>typeof J)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:X}}function F3(){return{not:{}}}function w3(W){return W.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var O4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function D3(W,$){if($.target==="openApi3")return U3(W,$);let Y=W.options instanceof Map?Array.from(W.options.values()):W.options;if(Y.every((X)=>(X._def.typeName in O4)&&(!X._def.checks||!X._def.checks.length))){let X=Y.reduce((G,J)=>{let H=O4[J._def.typeName];return H&&!G.includes(H)?[...G,H]:G},[]);return{type:X.length>1?X:X[0]}}else if(Y.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Y.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(X.length===Y.length){let G=X.filter((J,H,T)=>T.indexOf(J)===H);return{type:G.length>1?G:G[0],enum:Y.reduce((J,H)=>{return J.includes(H._def.value)?J:[...J,H._def.value]},[])}}}else if(Y.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((X,G)=>[...X,...G._def.values.filter((J)=>!X.includes(J))],[])};return U3(W,$)}var U3=(W,$)=>{let Y=(W.options instanceof Map?Array.from(W.options.values()):W.options).map((X,G)=>W0(X._def,{...$,currentPath:[...$.currentPath,"anyOf",`${G}`]})).filter((X)=>!!X&&(!$.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Y.length?{anyOf:Y}:void 0};function M3(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:O4[W.innerType._def.typeName],nullable:!0};return{type:[O4[W.innerType._def.typeName],"null"]}}if($.target==="openApi3"){let X=W0(W.innerType._def,{...$,currentPath:[...$.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let Y=W0(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function V3(W,$){let Y={type:"number"};if(!W.checks)return Y;for(let X of W.checks)switch(X.kind){case"int":Y.type="integer",m9(Y,"type",X.message,$);break;case"min":if($.target==="jsonSchema7")if(X.inclusive)K0(Y,"minimum",X.value,X.message,$);else K0(Y,"exclusiveMinimum",X.value,X.message,$);else{if(!X.inclusive)Y.exclusiveMinimum=!0;K0(Y,"minimum",X.value,X.message,$)}break;case"max":if($.target==="jsonSchema7")if(X.inclusive)K0(Y,"maximum",X.value,X.message,$);else K0(Y,"exclusiveMaximum",X.value,X.message,$);else{if(!X.inclusive)Y.exclusiveMaximum=!0;K0(Y,"maximum",X.value,X.message,$)}break;case"multipleOf":K0(Y,"multipleOf",X.value,X.message,$);break}return Y}function O3(W,$){let Y=$.target==="openAi",X={type:"object",properties:{}},G=[],J=W.shape();for(let T in J){let Q=J[T];if(Q===void 0||Q._def===void 0)continue;let _=VM(Q);if(_&&Y){if(Q instanceof GW)Q=Q._def.innerType;if(!Q.isNullable())Q=Q.nullable();_=!1}let z=W0(Q._def,{...$,currentPath:[...$.currentPath,"properties",T],propertyPath:[...$.currentPath,"properties",T]});if(z===void 0)continue;if(X.properties[T]=z,!_)G.push(T)}if(G.length)X.required=G;let H=MM(W,$);if(H!==void 0)X.additionalProperties=H;return X}function MM(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 VM(W){try{return W.isOptional()}catch{return!0}}var K3=(W,$)=>{if($.currentPath.toString()===$.propertyPath?.toString())return W0(W.innerType._def,$);let Y=W0(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","1"]});return Y?{anyOf:[{not:{}},Y]}:{}};var E3=(W,$)=>{if($.pipeStrategy==="input")return W0(W.in._def,$);else if($.pipeStrategy==="output")return W0(W.out._def,$);let Y=W0(W.in._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),X=W0(W.out._def,{...$,currentPath:[...$.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,X].filter((G)=>G!==void 0)}};function A3(W,$){return W0(W.type._def,$)}function L3(W,$){let X={type:"array",uniqueItems:!0,items:W0(W.valueType._def,{...$,currentPath:[...$.currentPath,"items"]})};if(W.minSize)K0(X,"minItems",W.minSize.value,W.minSize.message,$);if(W.maxSize)K0(X,"maxItems",W.maxSize.value,W.maxSize.message,$);return X}function Z3(W,$){if(W.rest)return{type:"array",minItems:W.items.length,items:W.items.map((Y,X)=>W0(Y._def,{...$,currentPath:[...$.currentPath,"items",`${X}`]})).reduce((Y,X)=>X===void 0?Y:[...Y,X],[]),additionalItems:W0(W.rest._def,{...$,currentPath:[...$.currentPath,"additionalItems"]})};else return{type:"array",minItems:W.items.length,maxItems:W.items.length,items:W.items.map((Y,X)=>W0(Y._def,{...$,currentPath:[...$.currentPath,"items",`${X}`]})).reduce((Y,X)=>X===void 0?Y:[...Y,X],[])}}function N3(){return{not:{}}}function R3(){return{}}var B3=(W,$)=>{return W0(W.innerType._def,$)};var S3=(W,$,Y)=>{switch($){case q.ZodString:return NY(W,Y);case q.ZodNumber:return V3(W,Y);case q.ZodObject:return O3(W,Y);case q.ZodBigInt:return W3(W,Y);case q.ZodBoolean:return $3();case q.ZodDate:return i9(W,Y);case q.ZodUndefined:return N3();case q.ZodNull:return w3(Y);case q.ZodArray:return eJ(W,Y);case q.ZodUnion:case q.ZodDiscriminatedUnion:return D3(W,Y);case q.ZodIntersection:return H3(W,Y);case q.ZodTuple:return Z3(W,Y);case q.ZodRecord:return RY(W,Y);case q.ZodLiteral:return T3(W,Y);case q.ZodEnum:return J3(W);case q.ZodNativeEnum:return z3(W);case q.ZodNullable:return M3(W,Y);case q.ZodOptional:return K3(W,Y);case q.ZodMap:return _3(W,Y);case q.ZodSet:return L3(W,Y);case q.ZodLazy:return()=>W.getter()._def;case q.ZodPromise:return A3(W,Y);case q.ZodNaN:case q.ZodNever:return F3();case q.ZodEffects:return G3(W,Y);case q.ZodAny:return sJ();case q.ZodUnknown:return R3();case q.ZodDefault:return X3(W,Y);case q.ZodBranded:return ZY(W,Y);case q.ZodReadonly:return B3(W,Y);case q.ZodCatch:return Y3(W,Y);case q.ZodPipeline:return E3(W,Y);case q.ZodFunction:case q.ZodVoid:case q.ZodSymbol:return;default:return((X)=>{return})($)}};function W0(W,$,Y=!1){let X=$.seen.get(W);if($.override){let T=$.override?.(W,$,X,Y);if(T!==cJ)return T}if(X&&!Y){let T=OM(X,$);if(T!==void 0)return T}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)EM(W,$,H);if($.postProcess){let T=$.postProcess(H,W,$);return G.jsonSchema=H,T}return G.jsonSchema=H,H}var OM=(W,$)=>{switch($.$refStrategy){case"root":return{$ref:W.path.join("/")};case"relative":return{$ref:KM($.currentPath,W.path)};case"none":case"seen":{if(W.path.length<$.currentPath.length&&W.path.every((Y,X)=>$.currentPath[X]===Y))return console.warn(`Recursive reference detected at ${$.currentPath.join("/")}! Defaulting to any`),{};return $.$refStrategy==="seen"?{}:void 0}}},KM=(W,$)=>{let Y=0;for(;Y<W.length&&Y<$.length;Y++)if(W[Y]!==$[Y])break;return[(W.length-Y).toString(),...$.slice(Y)].join("/")},EM=(W,$,Y)=>{if(W.description){if(Y.description=W.description,$.markdownDescription)Y.markdownDescription=W.description}return Y};var q3=(W,$)=>{let Y=lJ($),X=typeof $==="object"&&$.definitions?Object.entries($.definitions).reduce((Q,[_,z])=>({...Q,[_]:W0(z._def,{...Y,currentPath:[...Y.basePath,Y.definitionPath,_]},!0)??{}}),{}):void 0,G=typeof $==="string"?$:$?.nameStrategy==="title"?void 0:$?.name,J=W0(W._def,G===void 0?Y:{...Y,currentPath:[...Y.basePath,Y.definitionPath,G]},!1)??{},H=typeof $==="object"&&$.name!==void 0&&$.nameStrategy==="title"?$.name:void 0;if(H!==void 0)J.title=H;let T=G===void 0?X?{...J,[Y.definitionPath]:X}:J:{$ref:[...Y.$refStrategy==="relative"?[]:Y.basePath,Y.definitionPath,G].join("/"),[Y.definitionPath]:{...X,[G]:J}};if(Y.target==="jsonSchema7")T.$schema="http://json-schema.org/draft-07/schema#";else if(Y.target==="jsonSchema2019-09"||Y.target==="openAi")T.$schema="https://json-schema.org/draft/2019-09/schema#";if(Y.target==="openAi"&&(("anyOf"in T)||("oneOf"in T)||("allOf"in T)||("type"in T)&&Array.isArray(T.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return T};var C3=q3;function k3(W,$){return function Y({schema:X,fallback:G,toJsonSchema:J=C3}){let H=J(X);return async function T(Q,_=3){let z,F=[];while(F.length<_){z=await W(Q,H,G,F);let w=await X["~standard"].validate(z);if("value"in w)return w.value;$?.warn(`safegen failed to generate well-formed data.
|
|
3
|
+
var HA=Object.create;var{getPrototypeOf:FA,defineProperty:dU,getOwnPropertyNames:QA}=Object;var ZA=Object.prototype.hasOwnProperty;var DA=($,T,W)=>{W=$!=null?HA(FA($)):{};let X=T||!$||!$.__esModule?dU(W,"default",{value:$,enumerable:!0}):W;for(let Y of QA($))if(!ZA.call(X,Y))dU(X,Y,{get:()=>$[Y],enumerable:!0});return X};var OA=($,T)=>()=>(T||$((T={exports:{}}).exports,T),T.exports);var M1=($,T)=>{for(var W in T)dU($,W,{get:T[W],enumerable:!0,configurable:!0,set:(X)=>T[W]=()=>X})};var Xj=($,T)=>()=>($&&(T=$($=0)),T);var y5=import.meta.require;var ZF=OA((ch,QF)=>{var oW=y5("os"),lW=y5("path");function FF($){let T=process.env.XDG_CACHE_HOME||lW.join(oW.homedir(),".cache");return lW.join(T,$)}function zR($){return lW.join(oW.homedir(),"Library","Caches",$)}function _R($){let T=process.env.LOCALAPPDATA||lW.join(oW.homedir(),"AppData","Local");return lW.join(T,$,"Cache")}var HR=function(){switch(oW.platform()){case"darwin":return zR;case"win32":return _R;case"aix":case"android":case"freebsd":case"linux":case"netbsd":case"openbsd":case"sunos":return FF;default:return console.error(`(node:${process.pid}) [cachedir] Warning: the platform "${oW.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`),FF}}();QF.exports=function $(T){if(typeof T!=="string")throw new TypeError("id is not a string");if(T.length===0)throw new Error("id cannot be empty");if(/[^0-9a-zA-Z-]/.test(T))throw new Error("id cannot contain special characters");return HR(T)}});class TW extends Promise{fate;resolve;reject;done=!1;constructor($){let T,W;super((X,Y)=>{T=X,W=Y});this.resolve=T,this.reject=W,this.use($ instanceof Promise?$:new Promise($))}pass($,T){if($===this.fate)this.resolve(T),this.done=!0}fail($,T){if($===this.fate)this.reject(T),this.done=!0}use($){if($ instanceof Promise){let T=$;this.fate=T,T.then((W)=>{this.pass(T,W)},(W)=>{this.fail(T,W)})}else this.resolve($),this.fate=void 0}}var Jj=($,T,W=g5.STORE)=>{return h5(W,{key:`${$.key}:JSON`,get:({get:X})=>T.toJson(X($)),set:({set:X},Y)=>{X($,T.fromJson(Y))}})};function _j($,T,W){return oU($,{key:`${T.key}:JSON`,get:(Y)=>({get:U})=>{let G=U(T,Y);return W.toJson(G)},set:(Y)=>({set:U},G)=>{U(T,Y,W.fromJson(G))}},["mutable","json"])}var WW=($)=>JSON.parse($),R4=($)=>JSON.stringify($),Fj=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function s($){while($.child!==null)$=$.child;return $}class bX{_buffer;_index=0;constructor($){let T;if(typeof $==="number")T=$;else T=$.length;this._buffer=Array.from({length:T})}get buffer(){return this._buffer}get index(){return this._index}add($){this._buffer[this._index]=$,this._index=(this._index+1)%this._buffer.length}copy(){let $=new bX([...this._buffer]);return $._index=this._index,$}}var VA={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 m5($,T){let W=R4(T),X=`${$.key}(${W})`,Y=VA[$.type],U={key:X,type:Y};return Object.assign(U,{family:{key:$.key,subKey:W}}),Object.assign(U,{counterfeit:!0}),U}function XW($){let T={key:$.key,type:$.type};if("family"in $)T.family=$.family;return T}var lU=($)=>(T,W,X,Y,...U)=>{console[$](`${T} ${W} "${X}" ${Y}`,...U)},KA={error:lU("error"),info:lU("info"),warn:lU("warn")};class rU{logLevel;filter;logger;constructor($,T,W=KA){this.logLevel=$,this.filter=T,this.logger=W}error=(...$)=>{let T=this.filter?.(...$)??!0;if(this.logLevel!==null){if(T===!0)this.logger.error(...$);else if(T!==!1)this.logger.error(...T)}};info=(...$)=>{let T=this.filter?.(...$)??!0;if(this.logLevel==="info"){if(T===!0)this.logger.info(...$);else if(T!==!1)this.logger.info(...T)}};warn=(...$)=>{let T=this.filter?.(...$)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(T===!0)this.logger.warn(...$);else if(T!==!1)this.logger.warn(...T)}}}class P6{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=($,T)=>`${$}:${T}`;warn;getRelatedKeys($){return this.relations.get($)}addRelation($,T){let W=this.relations.get($),X=this.relations.get(T);if(W)W.add(T);else W=new Set([T]),this.relations.set($,W);if(X)X.add($);else X=new Set([$]),this.relations.set(T,X)}deleteRelation($,T){let W=this.relations.get($);if(W){if(W.delete(T),W.size===0)this.relations.delete($);let X=this.relations.get(T);if(X){if(X.delete($),X.size===0)this.relations.delete(T)}}}replaceRelationsUnsafely($,T){this.relations.set($,new Set(T));for(let W of T){let X=new Set().add($);this.relations.set(W,X)}}replaceRelationsSafely($,T){let W=this.relations.get($),X=this.isAType?.($)?$:void 0,Y=X===void 0?$:void 0;if(W)for(let U of W){X??=U,Y??=U;let G=this.relations.get(U);if(G){if(G.size===1)this.relations.delete(U);else G.delete($);this.contents.delete(this.makeContentKey(X,Y))}}this.relations.set($,new Set(T));for(let U of T){let G=this.relations.get(U);if(G)G.add($);else G=new Set().add($),this.relations.set(U,G)}}getContentInternal($){return this.contents.get($)}setContent($,T){this.contents.set($,T)}deleteContent($){this.contents.delete($)}constructor($,T){if(this.a=$.between[0],this.b=$.between[1],this.cardinality=$.cardinality,!T?.externalStore)this.relations=new Map($.relations?.map(([W,X])=>[W,new Set(X)])),this.contents=new Map($.contents);if(this.isAType=T?.isAType??null,this.isBType=T?.isBType??null,this.isContent=T?.isContent??null,T?.makeContentKey)this.makeContentKey=T.makeContentKey;if(T?.externalStore){let W=T.externalStore;if(this.has=(X,Y)=>W.has(X,Y),this.addRelation=(X,Y)=>{W.addRelation(X,Y)},this.deleteRelation=(X,Y)=>{W.deleteRelation(X,Y)},this.replaceRelationsSafely=(X,Y)=>{W.replaceRelationsSafely(X,Y)},this.replaceRelationsUnsafely=(X,Y)=>{W.replaceRelationsUnsafely(X,Y)},this.getRelatedKeys=(X)=>W.getRelatedKeys(X),W.getContent)this.getContentInternal=(X)=>{return W.getContent(X)},this.setContent=(X,Y)=>{W.setContent(X,Y)},this.deleteContent=(X)=>{W.deleteContent(X)};for(let[X,Y]of $.relations??[]){let U=this.isAType?.(X)?X:void 0,G=U===void 0?X:void 0;for(let J of Y)U??=J,G??=J,this.addRelation(U,G)}for(let[X,Y]of $.contents??[])this.setContent(X,Y)}if(T?.warn)this.warn=T.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([$,T])=>[$,[...T]]),contents:[...this.contents.entries()]}}set(...$){let T,W,X;switch($.length){case 1:{let Y=$[0];T=Y[this.a],W=Y[this.b],X=void 0;break}case 2:{let Y=$[0];if(typeof Y==="string")[T,W]=$;else T=Y[this.a],W=Y[this.b],X=$[1];break}default:{T=$[0],W=$[1],X=$[2];break}}switch(this.cardinality){case"1:1":{let Y=this.getRelatedKey(T);if(Y&&Y!==W)this.delete(T,Y)}case"1:n":{let Y=this.getRelatedKey(W);if(Y&&Y!==T)this.delete(Y,W)}break;case"n:n":}if(X){let Y=this.makeContentKey(T,W);this.setContent(Y,X)}return this.addRelation(T,W),this}delete($,T){T=typeof T==="string"?T:$[this.b];let W=typeof $==="string"?$:$[this.a];if(W===void 0&&typeof T==="string"){let X=this.getRelatedKeys(T);if(X)for(let Y of X)this.delete(Y,T)}if(typeof W==="string"&&T===void 0){let X=this.getRelatedKeys(W);if(X)for(let Y of X)this.delete(W,Y)}if(typeof W==="string"&&typeof T==="string"){this.deleteRelation(W,T);let X=this.makeContentKey(W,T);this.deleteContent(X)}return this}getRelatedKey($){let T=this.getRelatedKeys($);if(T){if(T.size>1)this.warn?.(`${T.size} related keys were found for key "${$}": (${[...T].map((X)=>`"${X}"`).join(", ")}). Only one related key was expected.`);let W;for(let X of T){W=X;break}return W}}replaceRelations($,T,W){let X=!Array.isArray(T),Y=X?Object.keys(T):T;if(W?.reckless)this.replaceRelationsUnsafely($,Y);else this.replaceRelationsSafely($,Y);if(X)for(let U of Y){let G=this.makeContentKey($,U),J=T[U];this.setContent(G,J)}return this}getContent($,T){let W=this.makeContentKey($,T);return this.getContentInternal(W)}getRelationEntries($){let T=$[this.a],W=$[this.b];if(T!==void 0&&W===void 0){let X=this.getRelatedKeys(T);if(X)return[...X].map((Y)=>{return[Y,this.getContent(T,Y)]})}if(T===void 0&&W!==void 0){let X=this.getRelatedKeys(W);if(X)return[...X].map((Y)=>{return[Y,this.getContent(Y,W)]})}return[]}has($,T){if(T)return this.getRelatedKeys($)?.has(T)??!1;return this.relations.has($)}}class K${Subscriber;subscribers=new Map;subscribe($,T){return this.subscribers.set($,T),()=>{this.unsubscribe($)}}unsubscribe($){this.subscribers.delete($)}next($){let T=this.subscribers.values();for(let W of T)W($)}}class iU extends K${state;constructor($){super();this.state=$}next($){this.state=$,super.next($)}}function A1($){return"epoch"in $.transactionMeta}function l4($){return"phase"in $.transactionMeta}function c5($){return $[0].toUpperCase()+$.slice(1)}function fX($){return $.type.split("_").map(c5).join(" ")}class YW extends Error{constructor($,T){super(`${fX($)} ${R4($.key)} not found in store "${T.config.name}".`)}}var u0=($)=>(T)=>$ instanceof Function?$(T):$;var N1=($,T)=>{if($.valueMap.has(T.key))return $.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),u5(T,$);switch(T.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return $.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();case"atom":case"mutable_atom":{let W=T.default,X;if(W instanceof Function)X=W();else X=W;return $.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",X),X}}};var p5=($,T)=>{if($.operation.open){let W=performance.now();return $.logger.info("\u2757",T.type,T.key,`deferring setState at T-${W} until setState for "${$.operation.token.key}" is done`),W}$.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:T},$.logger.info("\u2B55",T.type,T.key,`operation start in store "${$.config.name}"${!l4($)?"":` ${$.transactionMeta.phase} "${$.transactionMeta.update.key}"`}`)},d5=($)=>{if($.operation.open)$.logger.info("\uD83D\uDD34",$.operation.token.type,$.operation.token.key,`operation done in store "${$.config.name}"`);$.operation={open:!1},$.on.operationClose.next($.operation)},o5=($,T)=>{if(!$.operation.open)return $.logger.error("\uD83D\uDC1E","unknown",T,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return $.operation.done.has(T)},L1=($,T)=>{if(!$.operation.open){$.logger.error("\uD83D\uDC1E","unknown",T,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}$.operation.done.add(T)};var l5=($,T,W)=>{switch(T.type){case"mutable_atom":$.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",W.newValue,") subscribers:",T.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":$.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",W.oldValue,"->",W.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(W)};var nU=($,T)=>{let W=s($),X=W.selectorAtoms.getRelatedKeys(T.key);if(W.logger.info("\uD83E\uDDF9",T.type,T.key,X?`evicting ${X.size} states downstream:`:"no downstream states",X??"to evict"),X){if(W.operation.open)W.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...W.operation.done].join(", ")} ] already done`);for(let Y of X){if(o5(W,Y))continue;r5(Y,W),L1(W,Y)}}};var i5=($,T,W)=>{let X=N1($,T),Y=X;if(T.type==="mutable_atom"&&l4($)){let{parent:G}=$;Y=UW($,T,G)}if(Y=u0(W)(Y),$.logger.info("\uD83D\uDCDD","atom",T.key,"set to",Y),Y=I4($,T.key,Y,T.subject),t5($,T.key))a5($,T.key);L1($,T.key),nU($,T);let U={oldValue:X,newValue:Y};if(!l4($)){l5($,T,U);return}if($.on.transactionApplying.state===null){let{key:G}=T;if(n5(U.newValue))return;let J={type:"atom_update",key:G,...U};if(T.family)J.family=T.family;$.transactionMeta.update.updates.push(J),$.logger.info("\uD83D\uDCC1","atom",G,"stowed (",U.oldValue,"->",U.newValue,")")}else if(T.key.startsWith("*")){let G=T.key.slice(1),J=$.atoms.get(G),z=$.valueMap.get(G);if(J.type==="mutable_atom"&&l4($)){let{parent:H}=$;z=UW($,J,H)}if(z.do(U.newValue)===null)nU($,J)}};var yX=($,T,W)=>{switch(T.type){case"atom":case"mutable_atom":i5($,T,W);break;case"writable_pure_selector":case"writable_held_selector":T.set(W);break}};var hX=($,T)=>s($).atoms.has(T),EA=($,T)=>s($).writableSelectors.has(T),MA=($,T)=>s($).readonlySelectors.has(T),s5=($,T)=>hX($,T)||EA($,T)||MA($,T);var gX=($,T)=>{return s($).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([X,{source:Y}])=>Y!==T).map(([X,{source:Y}])=>Y).filter((X)=>s5($,X))};var tU=($,T,W)=>{let X=[],Y=gX($,T);while(Y.length>0){let U=Y.shift();if(W.has(U))continue;if(W.add(U),!hX($,U))Y.push(...gX($,U));else if(!X.includes(U))X.push(U)}return X},e5=($,T)=>{let W=$.key,X=gX(T,W),Y=new Set;return X.flatMap((U)=>hX(T,U)?U:tU(T,U,Y))};var $3=($,T,W,X,Y)=>{let U=s($),{type:G,key:J}=X;if(G==="atom"||G==="mutable_atom")U.selectorAtoms.set({selectorKey:W,atomKey:J}),$.logger.info("\uD83D\uDD0D",T,W,`discovers root atom "${J}"`);else{let z=tU($,J,Y);$.logger.info("\uD83D\uDD0D",T,W,`discovers root atoms: [ ${z.map((w)=>`"${w}"`).join(", ")} ]`);for(let w of z)U.selectorAtoms=U.selectorAtoms.set({selectorKey:W,atomKey:w})}Y.add(J)};var S1=($,T,W,X)=>({get:(...Y)=>{let U=s($),G;if(Y.length===2){let[H,_]=Y;G=r4($,H,_)}else[G]=Y;let J=j4($,G),z=N1($,J),w=G.key;return $.logger.info("\uD83D\uDD0C",T,W,`registers dependency ( "${w}" =`,z,")"),U.selectorGraph.set({upstreamSelectorKey:w,downstreamSelectorKey:W},{source:G.key}),$3($,T,W,G,X),z},set:(...Y)=>{let U,G;if(Y.length===2)U=Y[0],G=Y[1];else{let w=Y[0],H=Y[1];G=Y[2],U=r4($,w,H)}let J=s($),z=j4(J,U);yX(J,z,G)},find:(...Y)=>r4($,...Y),json:(Y)=>p0($,Y)});var aU=($,T,W)=>{let X=s($),Y=new K$,U=new Set,{key:G,const:J}=T,z="readonly_held_selector",{get:w,find:H,json:_}=S1(X,"readonly_held_selector",G,U),D={...T,type:"readonly_held_selector",subject:Y,install:(E)=>aU(E,T,W),get:()=>{return T.get({get:w,find:H,json:_},J),I4(s($),G,J,Y),U.clear(),J},...W&&{family:W}};X.readonlySelectors.set(G,D),$.logger.info("\u2728","readonly_held_selector",G,"=",J);let V={key:G,type:"readonly_held_selector"};if(W)V.family=W;return V};var sU=($,T,W)=>{let X=s($),Y=new K$,U=new Set,G=T.key,J="readonly_pure_selector",{get:z,find:w,json:H}=S1(X,"readonly_pure_selector",G,U),_=()=>{let E=T.get({get:z,find:w,json:H});return I4(s($),G,E,Y),U.clear(),E},F={...T,type:"readonly_pure_selector",subject:Y,install:(E)=>sU(E,T,W),get:_,...W&&{family:W}};X.readonlySelectors.set(G,F);let D=_();$.logger.info("\u2728","readonly_pure_selector",G,"=",D);let V={key:G,type:"readonly_pure_selector"};if(W)V.family=W;return V};var eU=($,T,W)=>{let X=s($),Y=new K$,U=new Set,{key:G,const:J}=T,z="writable_held_selector",w=S1(X,"writable_held_selector",G,U),{find:H,get:_,json:F}=w,D={find:H,get:_,json:F},V=(N=T.get,k=s($))=>{return N(D,J),I4(k,G,J,Y),U.clear(),J},R={...T,type:"writable_held_selector",subject:Y,install:(N)=>eU(N,T,W),get:V,set:(N)=>{let k=s($),y=V(T.get,k),x=u0(N)(y);if($.logger.info("\uD83D\uDCDD","writable_held_selector",G,"set (",y,"->",x,")"),I4(k,G,x,Y),L1(k,G),A1(k))Y.next({newValue:x,oldValue:y});T.set(w,x)},...W&&{family:W}};X.writableSelectors.set(G,R);let P=V();$.logger.info("\u2728","writable_held_selector",G,"=",P);let A={key:G,type:"writable_held_selector"};if(W)A.family=W;return A};var GW=($,T,W)=>{let X=s($),Y=new K$,U=new Set,G=T.key,J="writable_pure_selector",z=S1(X,"writable_pure_selector",G,U),{find:w,get:H,json:_}=z,F={find:w,get:H,json:_},D=(A=T.get,N=s($))=>{let k=A(F);return I4(N,G,k,Y),U.clear(),k},E={...T,type:"writable_pure_selector",subject:Y,install:(A)=>GW(A,T,W),get:D,set:(A)=>{let N=s($),k=D(T.get,N),y=u0(A)(k);if($.logger.info("\uD83D\uDCDD","writable_pure_selector",G,"set (",k,"->",y,")"),I4(N,T.key,y,Y),L1(N,T.key),A1(N))Y.next({newValue:y,oldValue:k});T.set(z,y)},...W&&{family:W}};X.writableSelectors.set(G,E);let R=D();$.logger.info("\u2728",E.type,E.key,"=",R);let P={key:G,type:"writable_pure_selector"};if(W)P.family=W;return P};function h5($,T){let W="set"in T,X="const"in T;if(X&&W){let U=eU($,T,void 0);return $.on.selectorCreation.next(U),U}if(X){let U=aU($,T,void 0);return $.on.selectorCreation.next(U),U}if(W){let U=GW($,T,void 0);return $.on.selectorCreation.next(U),U}let Y=sU($,T,void 0);return $.on.selectorCreation.next(Y),Y}function oU($,T,W){let X=T.key,Y="writable_pure_selector_family",U={key:X,type:"writable_pure_selector_family"},G=$.families.get(X);if(G)$.logger.error("\u2757","writable_pure_selector_family",X,`Overwriting an existing ${fX(G)} "${G.key}" in store "${$.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new K$,w=Object.assign((H)=>{let _=R4(H),F={key:X,subKey:_},D=`${X}(${_})`,V=s($),E=GW(V,{key:D,get:T.get(H),set:T.set(H)},F);return J.next({type:"state_creation",token:E}),E},U,{internalRoles:W,subject:J,install:(H)=>oU(H,T),default:(H)=>{return T.get(H)({get:(...F)=>JW($,...F),find:(...F)=>r4($,...F),json:(F)=>p0($,F)})}});return $.families.set(X,w),U}function T3($,T,W){let X=$.families.get(T.key);if(X===void 0)throw new YW(T,$);let Y=X(W),U=s($);if(Y.family){if(A1(U))switch(Y.type){case"atom":case"mutable_atom":$.on.atomCreation.next(Y);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":$.on.selectorCreation.next(Y);break}else if(l4(U)&&U.on.transactionApplying.state===null)U.transactionMeta.update.updates.push({type:"state_creation",token:Y})}return Y}function W3($,T,W){let X=R4(W),Y=`${T.key}(${X})`,U=s($),G;switch(T.type){case"atom_family":case"mutable_atom_family":G=U.atoms.get(Y);break;case"writable_held_selector_family":case"writable_pure_selector_family":G=U.writableSelectors.get(Y);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":G=U.readonlySelectors.get(Y);break}if(G)return XW(G);return G}function r4($,T,W){let X=W3($,T,W);if(X)return X;let Y=R4(W),U=$.molecules.get(Y);if(!U&&$.config.lifespan==="immortal"){let G=m5(T,W);return $.logger.error("\u274C",G.type,G.key,`was not found in store "${$.config.name}"; returned a counterfeit token.`),G}if(X=T3($,T,W),U)s($).moleculeData.set(Y,T.key);return X}function X3($,T){if(T.family){let W=$.families.get(T.family.key);if(W)return W}}function B1($,...T){let W,X,Y,U;if(T.length===2){if(W=T[0],U=T[1],X=X3($,W)??null,X)Y=W.family?WW(W.family.subKey):null,W=r4($,X,Y)}else X=T[0],Y=T[1],U=T[2],W=r4($,X,Y);if("counterfeit"in W&&"family"in W){let z=W.family.subKey,w=$.disposalTraces.buffer.find((H)=>H?.key===z);$.logger.error("\u274C",W.type,W.key,`could not be set because it was not found in the store "${$.config.name}".`,w?`This state was previously disposed:
|
|
4
|
+
${w.trace}`:"No previous disposal trace was found.");return}let G=p5($,W);if(G){let z=$.on.operationClose.subscribe(`waiting to set "${W.key}" at T-${G}`,()=>{z(),$.logger.info("\uD83D\uDFE2",W.type,W.key,`resuming deferred setState from T-${G}`),B1($,W,U)});return}let J=j4($,W);yX($,J,U),d5($)}function JW($,...T){let W,X,Y;if(T.length===1)W=T[0];else X=T[0],Y=T[1],W=r4($,X,Y);if("counterfeit"in W&&"family"in W){X=$.families.get(W.family.key);let U=W.family.subKey,G=$.disposalTraces.buffer.find((J)=>J?.key===U);switch($.logger.error("\u274C",W.type,W.key,`could not be retrieved because it was not found in the store "${$.config.name}".`,G?`This state was previously disposed:
|
|
5
|
+
${G.trace}`:"No previous disposal trace was found."),X.type){case"atom_family":case"mutable_atom_family":return $.defaults.get(X.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if($.defaults.has(X.key))return $.defaults.get(W.family.key);let J=j4($,X).default(U);return $.defaults.set(X.key,J),J}}}return N1($,j4($,W))}class Y3{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new P6({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new P6({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...$)=>$.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new P6({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new P6({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new bX(100);molecules=new Map;moleculeJoins=new P6({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...$)=>$.sort().join(":")});moleculeGraph=new P6({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...$)=>$.sort().join(":")});moleculeData=new P6({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...$)=>$.sort().join(":")});miscResources=new Map;on={atomCreation:new K$,atomDisposal:new K$,selectorCreation:new K$,selectorDisposal:new K$,timelineCreation:new K$,transactionCreation:new K$,transactionApplying:new iU(null),operationClose:new K$,moleculeCreation:new K$,moleculeDisposal:new K$};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new rU("warn",($,T,W)=>!G3(W))];logger={error:(...$)=>{for(let T of this.loggers)T.error(...$)},info:(...$)=>{for(let T of this.loggers)T.info(...$)},warn:(...$)=>{for(let T of this.loggers)T.warn(...$)}};constructor($,T=null){if(this.config={...T?.config,...$},T!==null){if(this.valueMap=new Map(T?.valueMap),this.operation={...T?.operation},A1(T))this.transactionMeta={epoch:new Map(T?.transactionMeta.epoch),actionContinuities:new P6(T?.transactionMeta.actionContinuities.toJSON())};for(let[,X]of T.families){if(X.internalRoles?.includes("mutable")||X.internalRoles?.includes("join"))continue;X.install(this)}let W=new Set;for(let[,X]of T.atoms){if(W.has(X.key))continue;if(X.install(this),X.type==="mutable_atom"){let Y=p0(T,X),U=U3(X);W.add(Y.key),W.add(U.key)}}for(let[,X]of T.readonlySelectors)X.install(this);for(let[,X]of T.writableSelectors){if(W.has(X.key))continue;X.install(this)}for(let[,X]of T.transactions)X.install(this);for(let[,X]of T.timelines)X.install(this)}}}var g5={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new Y3({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function j4($,T){let W,X=$;while(X!==null){switch(T.type){case"atom":case"mutable_atom":W=X.atoms.get(T.key);break;case"writable_pure_selector":case"writable_held_selector":W=X.writableSelectors.get(T.key);break;case"readonly_pure_selector":case"readonly_held_selector":W=X.readonlySelectors.get(T.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":W=X.families.get(T.key);break;case"timeline":W=X.timelines.get(T.key);break;case"transaction":W=X.transactions.get(T.key);break}if(W)return W;X=X.child}throw new YW(T,$)}var J3=($,T)=>{let W=s($);if(W.operation.open)return W.operation.prev.get(T.key);return W.valueMap.get(T.key)};var $G=($,T)=>{let W=s($);return e5(T,$).map((Y)=>{let U=W.atoms.get(Y);if(U===void 0)throw new Error(`Atom "${Y}", a dependency of selector "${T.key}", not found in store "${$.config.name}".`);return U.subject.subscribe(`${T.type}:${T.key}`,(G)=>{$.logger.info("\uD83D\uDCE2",T.type,T.key,"root",Y,"went",G.oldValue,"->",G.newValue);let J=J3(W,T),z=N1(W,T);$.logger.info("\u2728",T.type,T.key,"went",J,"->",z),T.subject.next({newValue:z,oldValue:J})})})};function wW($,T,W,X){function Y(_){if($.operation.open){let F=$.on.operationClose.subscribe(`state subscription ${W}`,()=>{F(),X(_)})}else X(_)}let U=j4($,T);$.logger.info("\uD83D\uDC40",U.type,U.key,`Adding subscription "${W}"`);let G=U.type==="writable_pure_selector"||U.type==="readonly_pure_selector",J=null,z=Y;if(G)J=$G($,U),z=(_)=>{if(J)J.length=0,J.push(...$G($,U));Y(_)};let w=U.subject.subscribe(W,z);return()=>{if($.logger.info("\uD83D\uDE48",U.type,U.key,`Removing subscription "${W}"`),w(),J)for(let _ of J)_()}}var w3=($,T,W,X)=>{let Y=j4($,T);$.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${W}"`);let U=Y.subject.subscribe(W,X);return()=>{$.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${W}" from timeline`),U()}};class TG{initializeState($,T){let W=`*${$.key}`;T.atoms.delete(W),T.valueMap.delete(W);let X=$.family?{key:`*${$.family.key}`,subKey:$.family.subKey}:void 0,Y=WG(T,{key:W,default:null},X);if(T.parent?.valueMap.has(W)){let U=T.parent.valueMap.get(W);T.valueMap.set(W,U)}return Y}unsubscribeFromInnerValue;unsubscribeFromState;observeCore($,T,W){let X=`tracker:${W.config.name}:${l4(W)?W.transactionMeta.update.key:"main"}:${$.key}`,Y=JW(W,$);this.unsubscribeFromInnerValue=Y.subscribe(X,(U)=>{B1(W,T,U)}),this.unsubscribeFromState=wW(W,$,X,(U)=>{if(U.newValue!==U.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=U.newValue.subscribe(X,(G)=>{B1(W,T,G)})})}updateCore($,T,W){let X=`tracker:${W.config.name}:${l4(W)?W.transactionMeta.update.key:"main"}:${$.key}`;wW(W,T,X,({newValue:Y,oldValue:U})=>{let G=W.timelineTopics.getRelatedKey(T.key);if(G){if(W.timelines.get(G)?.timeTraveling){let w=w3(W,{key:G,type:"timeline"},X,(H)=>{w(),B1(W,$,(_)=>{if(H==="redo"&&Y)_.do(Y);else if(H==="undo"&&U)_.undo(U);return _})});return}}let J=W.on.operationClose.subscribe(X,()=>{J();let z=JW(W,$),w=Y===null?-1:z.getUpdateNumber(Y),H=w-z.cacheUpdateNumber;if(Y&&H===1)B1(W,$,(_)=>(_.do(Y),_));else W.logger.info("\u274C","mutable_atom",$.key,`could not be updated. Expected update number ${z.cacheUpdateNumber+1}, but got ${w}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor($,T){this.mutableState=$;let W=s(T);this.latestUpdateState=this.initializeState($,W),this.observeCore($,this.latestUpdateState,W),this.updateCore($,this.latestUpdateState,W),W.trackers.set($.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),W.trackers.delete($.key)}}}var p0=($,T)=>{if(T.family){let X=s($),U={key:`${T.family.key}:JSON`,type:"writable_pure_selector_family"},G=j4(X,U),J=JSON.parse(T.family.subKey);return r4($,G,J)}return{type:"writable_pure_selector",key:`${T.key}:JSON`}};var U3=($)=>{let W={type:"atom",key:`*${$.key}`};if($.family)W.family={key:`*${$.family.key}`,subKey:$.family.subKey};return W};function n5($){return typeof $==="object"&&$!==null&&"do"in $&&"undo"in $&&"subscribe"in $}function UW($,T,W){let X=W.valueMap.get(T.key),Y=$.valueMap.get(T.key);if(X!==Y)return Y;if(X===void 0)return T.default();W.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let U=T.toJson(X),G=T.fromJson(U);return $.valueMap.set(T.key,G),new TG(T,W),G}function I4($,T,W,X){let Y=$.valueMap.get(T);if(Y instanceof TW)Y.use(W);if(W instanceof Promise){let U=new TW(W);return $.valueMap.set(T,U),U.then((G)=>{I4($,T,G,X),X.next({newValue:G,oldValue:U})}).catch((G)=>{$.logger.error("\uD83D\uDCA5","state",T,"rejected:",G)}),U}return $.valueMap.set(T,W),W}var u5=($,T)=>{let W=T.valueMap.get($.key);if($.type==="mutable_atom"&&l4(T)){let{parent:X}=T;W=UW(T,$,X)}return W},r5=($,T)=>{let W=T.valueMap.get($);if(W instanceof TW){let X=W,Y=T.writableSelectors.get($)??T.readonlySelectors.get($);if(Y)X.use(Y.get());return}if(T.operation.open)T.operation.prev.set($,W);T.valueMap.delete($),T.logger.info("\uD83D\uDDD1","state",$,"evicted")};var t5=($,T)=>{return s($).atomsThatAreDefault.has(T)},z3=($,T)=>{let W=s($);W.atomsThatAreDefault=new Set(W.atomsThatAreDefault).add(T)},a5=($,T)=>{let W=s($);W.atomsThatAreDefault=new Set(s($).atomsThatAreDefault),W.atomsThatAreDefault.delete(T)};function WG($,T,W){let{key:Y,default:U}=T;$.logger.info("\uD83D\uDD28","atom",Y,`creating in store "${$.config.name}"`);let G=s($),J=G.atoms.get(Y);if(J&&J.type==="atom")return $.logger.error("\u274C","atom",Y,"Tried to create atom, but it already exists in the store."),XW(J);let z=new K$,w={...T,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",Y,`installing in store "${F.config.name}"`),WG(F,T,W)},subject:z};if(W)w.family=W;let H=U;if(U instanceof Function)H=U();G.atoms.set(Y,w),z3($,Y),I4(G,Y,H,z);let _=XW(w);if(T.effects){let F=0,D=[];for(let V of T.effects){let E=V({setSelf:(R)=>{B1($,_,R)},onSet:(R)=>wW($,_,`effect[${F}]`,R)});if(E)D.push(E);++F}w.cleanup=()=>{for(let V of D)V()}}return _}class d0 extends Set{mode="record";subject=new K$;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor($,T=0){super($);if($ instanceof d0)this.parent=$,this.cacheUpdateNumber=$.cacheUpdateNumber;if(T)this.cacheLimit=T,this.cache=new Array(T),this.subscribe("auto cache",(W)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=W})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON($){let T=new d0($.members,$.cacheLimit);return T.cache=$.cache,T.cacheIdx=$.cacheIdx,T.cacheUpdateNumber=$.cacheUpdateNumber,T}add($){let T=super.add($);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${R4($)}`);return T}clear(){let $=this.mode==="record"?[...this]:null;if(super.clear(),$)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify($)}`)}delete($){let T=super.delete($);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${R4($)}`);return T}parent=null;child=null;transactionUpdates=null;transaction($){this.mode="transaction",this.transactionUpdates=[],this.child=new d0(this);let T=this.child._subscribe("transaction",(W)=>{this.transactionUpdates?.push(W)});try{if($(this.child)){for(let X of this.transactionUpdates)this.doStep(X);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(W){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",W),W}finally{T(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe($,T){return this.subject.subscribe($,T)}subscribe($,T){return this.subject.subscribe($,(W)=>{T(`${this.cacheUpdateNumber}=${W}`)})}emit($){this.subject.next($)}doStep($){let T=$.indexOf(":"),W=$.substring(0,T),X=$.substring(T+1);switch(W){case"add":this.add(JSON.parse(X));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(X));break;case"tx":for(let Y of X.split(";"))this.doStep(Y)}}getUpdateNumber($){let T=$.indexOf("=");return Number($.substring(0,T))}do($){let T=$.indexOf("="),W=Number($.substring(0,T)),X=W-this.cacheUpdateNumber;if(X>0){if(X===1){this.mode="playback";let U=$.substring(T+1);return this.doStep(U),this.mode="record",this.cacheUpdateNumber=W,null}return this.cacheUpdateNumber+1}if(Math.abs(X)<this.cacheLimit){let U=this.cacheIdx+X;if(this.cache[U]===$)return null;this.mode="playback";let J=!1;while(!J){this.cacheIdx%=this.cacheLimit;let w=this.cache[this.cacheIdx];if(this.cacheIdx--,!w)return"OUT_OF_RANGE";this.undo(w),J=this.cacheIdx===U-1}let z=$.substring(T+1);return this.doStep(z),this.mode="record",this.cacheUpdateNumber=W,null}return"OUT_OF_RANGE"}undoStep($){let T=$.indexOf(":"),W=$.substring(0,T),X=$.substring(T+1);switch(W){case"add":this.delete(JSON.parse(X));break;case"del":this.add(JSON.parse(X));break;case"clear":{let Y=JSON.parse(X);for(let U of Y)this.add(U);break}case"tx":{let Y=X.split(";");for(let U=Y.length-1;U>=0;U--)this.undoStep(Y[U])}}}undo($){let T=$.indexOf("=");if(Number($.substring(0,T))===this.cacheUpdateNumber){this.mode="playback";let X=$.substring(T+1);return this.undoStep(X),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function G3($){return $.startsWith("\uD83D\uDD0D ")}class mX{listeners;globalListeners;handleEvent($,...T){for(let X of this.globalListeners)X($,...T);let W=this.listeners.get($);if(W)for(let X of W)X(...T)}id="no_id_retrieved";emit;constructor($){this.emit=$,this.listeners=new Map,this.globalListeners=new Set}on($,T){let W=this.listeners.get($);if(W)W.add(T);else this.listeners.set($,new Set([T]));return this}onAny($){return this.globalListeners.add($),this}off($,T){let W=this.listeners.get($);if(W)if(T)W.delete(T);else this.listeners.delete($);return this}offAny($){return this.globalListeners.delete($),this}}class _3 extends mX{in;out;id="no_id_retrieved";disposalFunctions=[];constructor($){super((...T)=>{return this.out.next(T),this});this.id=$,this.in=new K$,this.out=new K$,this.in.subscribe("socket",(T)=>{this.handleEvent(...T)})}dispose(){for(let $ of this.disposalFunctions)$()}}class XG extends mX{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...$){this.process.stderr.write(R4($.map((T)=>T instanceof d0?`{ ${T.toJSON().members.join(" | ")} }`:T))+"\x03")}logger={info:(...$)=>{this.log("i",...$)},warn:(...$)=>{this.log("w",...$)},error:(...$)=>{this.log("e",...$)}};constructor(){super(($,...T)=>{let W=JSON.stringify([$,...T]);return this.process.stdout.write(W+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",($)=>{let T=$.toString();this.unprocessedEvents.push(...T.split("\x03"));let W=this.unprocessedEvents.shift();this.incompleteData+=W??"";try{let X=WW(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",X),this.handleEvent(...X);while(this.unprocessedEvents.length>0){let Y=this.unprocessedEvents.shift();if(Y){if(this.unprocessedEvents.length===0)this.incompleteData=Y;let U=WW(Y);this.handleEvent(...U)}}this.incompleteData=""}catch(X){if(X instanceof Error)this.logger.error("\u2757",X.message,X.cause,X.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",($)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${$}`)}),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",($)=>{this.logger.info("\uD83D\uDC64","user",$,"joined");let T=new _3(`user:${$}`);this.relays.set($,T),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let W of this.relayServices){let X=W(T);if(X)T.disposalFunctions.push(X)}this.on(`user:${$}`,(...W)=>{T.in.next(W)}),T.out.subscribe("socket",(W)=>{this.emit(...W)})}),this.on("user-leaves",($)=>{let T=this.relays.get($);if(this.off(`relay:${$}`),T)T.dispose(),this.relays.delete($)}),process.stdout.write("ALIVE")}relay($){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push($)}}var cY={};M1(cY,{xid:()=>DB,void:()=>bB,uuidv7:()=>wB,uuidv6:()=>JB,uuidv4:()=>GB,uuid:()=>UB,url:()=>zB,uppercase:()=>CW,unknown:()=>jY,union:()=>gY,undefined:()=>jB,ulid:()=>ZB,uint64:()=>CB,uint32:()=>kB,tuple:()=>uB,trim:()=>yW,treeifyError:()=>DG,transform:()=>Oz,toUpperCase:()=>gW,toLowerCase:()=>hW,toJSONSchema:()=>bw,templateLiteral:()=>aB,symbol:()=>vB,superRefine:()=>zF,success:()=>nB,stringbool:()=>TR,string:()=>ow,strictObject:()=>gB,startsWith:()=>jW,size:()=>kW,setErrorMap:()=>JR,set:()=>oB,safeParseAsync:()=>pw,safeParse:()=>uw,registry:()=>GY,regexes:()=>s1,regex:()=>qW,refine:()=>wF,record:()=>yH,readonly:()=>WF,property:()=>qw,promise:()=>sB,prettifyError:()=>OG,preprocess:()=>XR,prefault:()=>nH,positive:()=>Bw,pipe:()=>fY,partialRecord:()=>pB,parseAsync:()=>cw,parse:()=>mw,overwrite:()=>o6,optional:()=>xY,object:()=>hB,number:()=>LH,nullish:()=>iB,nullable:()=>bY,null:()=>kH,normalize:()=>fW,nonpositive:()=>Iw,nonoptional:()=>tH,nonnegative:()=>kw,never:()=>yY,negative:()=>Rw,nativeEnum:()=>lB,nanoid:()=>HB,nan:()=>tB,multipleOf:()=>$0,minSize:()=>T0,minLength:()=>I1,mime:()=>bW,maxSize:()=>r0,maxLength:()=>i0,map:()=>dB,lte:()=>U6,lt:()=>p6,lowercase:()=>PW,looseObject:()=>mB,locales:()=>BW,literal:()=>uH,length:()=>n0,lazy:()=>UF,ksuid:()=>OB,keyof:()=>yB,jwt:()=>SB,json:()=>WR,iso:()=>qY,ipv6:()=>KB,ipv4:()=>VB,intersection:()=>bH,int64:()=>PB,int32:()=>IB,int:()=>lw,instanceof:()=>$R,includes:()=>vW,guid:()=>YB,gte:()=>b4,gt:()=>d6,globalRegistry:()=>v6,getErrorMap:()=>wR,function:()=>xw,formatError:()=>EW,float64:()=>RB,float32:()=>BB,flattenError:()=>KW,file:()=>rB,enum:()=>mH,endsWith:()=>xW,emoji:()=>_B,email:()=>XB,e164:()=>LB,discriminatedUnion:()=>cB,date:()=>fB,custom:()=>eB,cuid2:()=>QB,cuid:()=>FB,core:()=>l6,config:()=>n$,coerce:()=>dw,clone:()=>i4,cidrv6:()=>MB,cidrv4:()=>EB,check:()=>JF,catch:()=>eH,boolean:()=>SH,bigint:()=>qB,base64url:()=>NB,base64:()=>AB,array:()=>Qz,any:()=>xB,_default:()=>rH,_ZodString:()=>rw,ZodXID:()=>Tz,ZodVoid:()=>CH,ZodUnknown:()=>Fz,ZodUnion:()=>Zz,ZodUndefined:()=>RH,ZodUUID:()=>r6,ZodURL:()=>nw,ZodULID:()=>$z,ZodType:()=>z$,ZodTuple:()=>fH,ZodTransform:()=>dH,ZodTemplateLiteral:()=>XF,ZodSymbol:()=>BH,ZodSuccess:()=>aH,ZodStringFormat:()=>f$,ZodString:()=>PY,ZodSet:()=>gH,ZodRecord:()=>Dz,ZodRealError:()=>a0,ZodReadonly:()=>TF,ZodPromise:()=>GF,ZodPrefault:()=>iH,ZodPipe:()=>Ez,ZodOptional:()=>Vz,ZodObject:()=>hY,ZodNumberFormat:()=>s0,ZodNumber:()=>cW,ZodNullable:()=>oH,ZodNull:()=>IH,ZodNonOptional:()=>Kz,ZodNever:()=>PH,ZodNanoID:()=>aw,ZodNaN:()=>$F,ZodMap:()=>hH,ZodLiteral:()=>cH,ZodLazy:()=>YF,ZodKSUID:()=>Wz,ZodJWT:()=>_z,ZodIssueCode:()=>YR,ZodIntersection:()=>xH,ZodIPv6:()=>Yz,ZodIPv4:()=>Xz,ZodGUID:()=>vY,ZodFile:()=>pH,ZodError:()=>tS,ZodEnum:()=>dW,ZodEmoji:()=>tw,ZodEmail:()=>iw,ZodE164:()=>zz,ZodDiscriminatedUnion:()=>jH,ZodDefault:()=>lH,ZodDate:()=>CY,ZodCustom:()=>mY,ZodCatch:()=>sH,ZodCUID2:()=>ew,ZodCUID:()=>sw,ZodCIDRv6:()=>Gz,ZodCIDRv4:()=>Uz,ZodBoolean:()=>uW,ZodBigIntFormat:()=>Hz,ZodBigInt:()=>pW,ZodBase64URL:()=>wz,ZodBase64:()=>Jz,ZodArray:()=>vH,ZodAny:()=>qH,NEVER:()=>GR,$output:()=>i9,$input:()=>n9,$brand:()=>YG});var l6={};M1(l6,{version:()=>_J,util:()=>g,treeifyError:()=>DG,toJSONSchema:()=>bw,toDotPath:()=>Q3,safeParseAsync:()=>KG,safeParse:()=>VG,registry:()=>GY,regexes:()=>s1,prettifyError:()=>OG,parseAsync:()=>lX,parse:()=>dX,locales:()=>BW,isValidJWT:()=>C3,isValidBase64URL:()=>P3,isValidBase64:()=>CJ,globalRegistry:()=>v6,globalConfig:()=>zW,function:()=>xw,formatError:()=>EW,flattenError:()=>KW,config:()=>n$,clone:()=>i4,_xid:()=>KY,_void:()=>Aw,_uuidv7:()=>HY,_uuidv6:()=>_Y,_uuidv4:()=>zY,_uuid:()=>wY,_url:()=>FY,_uppercase:()=>CW,_unknown:()=>Ew,_union:()=>RS,_undefined:()=>Ow,_ulid:()=>VY,_uint64:()=>Zw,_uint32:()=>ww,_tuple:()=>Cw,_trim:()=>yW,_transform:()=>bS,_toUpperCase:()=>gW,_toLowerCase:()=>hW,_templateLiteral:()=>dS,_symbol:()=>Dw,_success:()=>mS,_stringbool:()=>jw,_string:()=>t9,_startsWith:()=>jW,_size:()=>kW,_set:()=>CS,_safeParseAsync:()=>iX,_safeParse:()=>rX,_regex:()=>qW,_refine:()=>rS,_record:()=>qS,_readonly:()=>pS,_property:()=>qw,_promise:()=>lS,_positive:()=>Bw,_pipe:()=>uS,_parseAsync:()=>oX,_parse:()=>pX,_overwrite:()=>o6,_optional:()=>fS,_number:()=>Ww,_nullable:()=>yS,_null:()=>Vw,_normalize:()=>fW,_nonpositive:()=>Iw,_nonoptional:()=>gS,_nonnegative:()=>kw,_never:()=>Mw,_negative:()=>Rw,_nativeEnum:()=>jS,_nanoid:()=>ZY,_nan:()=>Sw,_multipleOf:()=>$0,_minSize:()=>T0,_minLength:()=>I1,_min:()=>b4,_mime:()=>bW,_maxSize:()=>r0,_maxLength:()=>i0,_max:()=>U6,_map:()=>PS,_lte:()=>U6,_lt:()=>p6,_lowercase:()=>PW,_literal:()=>xS,_length:()=>n0,_lazy:()=>oS,_ksuid:()=>EY,_jwt:()=>IY,_isoTime:()=>$w,_isoDuration:()=>Tw,_isoDateTime:()=>s9,_isoDate:()=>e9,_ipv6:()=>AY,_ipv4:()=>MY,_intersection:()=>kS,_int64:()=>Qw,_int32:()=>Jw,_int:()=>Yw,_includes:()=>vW,_guid:()=>IW,_gte:()=>b4,_gt:()=>d6,_float64:()=>Gw,_float32:()=>Uw,_file:()=>vw,_enum:()=>vS,_endsWith:()=>xW,_emoji:()=>QY,_email:()=>JY,_e164:()=>RY,_discriminatedUnion:()=>IS,_default:()=>hS,_date:()=>Nw,_custom:()=>mW,_cuid2:()=>OY,_cuid:()=>DY,_coercedString:()=>a9,_coercedNumber:()=>Xw,_coercedDate:()=>Lw,_coercedBoolean:()=>_w,_coercedBigint:()=>Fw,_cidrv6:()=>LY,_cidrv4:()=>NY,_catch:()=>cS,_boolean:()=>zw,_bigint:()=>Hw,_base64url:()=>BY,_base64:()=>SY,_array:()=>Pw,_any:()=>Kw,JSONSchemaGenerator:()=>kY,JSONSchema:()=>OH,Doc:()=>$Y,$output:()=>i9,$input:()=>n9,$constructor:()=>K,$brand:()=>YG,$ZodXID:()=>AJ,$ZodVoid:()=>pJ,$ZodUnknown:()=>NW,$ZodUnion:()=>UY,$ZodUndefined:()=>gJ,$ZodUUID:()=>QJ,$ZodURL:()=>DJ,$ZodULID:()=>MJ,$ZodType:()=>W$,$ZodTuple:()=>e1,$ZodTransform:()=>T9,$ZodTemplateLiteral:()=>H9,$ZodSymbol:()=>hJ,$ZodSuccess:()=>J9,$ZodStringFormat:()=>q$,$ZodString:()=>MW,$ZodSet:()=>aJ,$ZodRegistry:()=>RW,$ZodRecord:()=>nJ,$ZodRealError:()=>o0,$ZodReadonly:()=>_9,$ZodPromise:()=>F9,$ZodPrefault:()=>U9,$ZodPipe:()=>LW,$ZodOptional:()=>W9,$ZodObject:()=>lJ,$ZodNumberFormat:()=>fJ,$ZodNumber:()=>XY,$ZodNullable:()=>X9,$ZodNull:()=>mJ,$ZodNonOptional:()=>G9,$ZodNever:()=>uJ,$ZodNanoID:()=>VJ,$ZodNaN:()=>z9,$ZodMap:()=>tJ,$ZodLiteral:()=>eJ,$ZodLazy:()=>Q9,$ZodKSUID:()=>NJ,$ZodJWT:()=>bJ,$ZodIntersection:()=>iJ,$ZodISOTime:()=>BJ,$ZodISODuration:()=>RJ,$ZodISODateTime:()=>LJ,$ZodISODate:()=>SJ,$ZodIPv6:()=>kJ,$ZodIPv4:()=>IJ,$ZodGUID:()=>FJ,$ZodFunction:()=>t0,$ZodFile:()=>$9,$ZodError:()=>VW,$ZodEnum:()=>sJ,$ZodEmoji:()=>OJ,$ZodEmail:()=>ZJ,$ZodE164:()=>xJ,$ZodDiscriminatedUnion:()=>rJ,$ZodDefault:()=>Y9,$ZodDate:()=>dJ,$ZodCustom:()=>Z9,$ZodCheckUpperCase:()=>XJ,$ZodCheckStringFormat:()=>l0,$ZodCheckStartsWith:()=>UJ,$ZodCheckSizeEquals:()=>aG,$ZodCheckRegex:()=>TJ,$ZodCheckProperty:()=>JJ,$ZodCheckOverwrite:()=>zJ,$ZodCheckNumberFormat:()=>rG,$ZodCheckMultipleOf:()=>lG,$ZodCheckMinSize:()=>tG,$ZodCheckMinLength:()=>eG,$ZodCheckMimeType:()=>wJ,$ZodCheckMaxSize:()=>nG,$ZodCheckMaxLength:()=>sG,$ZodCheckLowerCase:()=>WJ,$ZodCheckLessThan:()=>sX,$ZodCheckLengthEquals:()=>$J,$ZodCheckIncludes:()=>YJ,$ZodCheckGreaterThan:()=>eX,$ZodCheckEndsWith:()=>GJ,$ZodCheckBigIntFormat:()=>iG,$ZodCheck:()=>u$,$ZodCatch:()=>w9,$ZodCUID2:()=>EJ,$ZodCUID:()=>KJ,$ZodCIDRv6:()=>PJ,$ZodCIDRv4:()=>qJ,$ZodBoolean:()=>AW,$ZodBigIntFormat:()=>yJ,$ZodBigInt:()=>YY,$ZodBase64URL:()=>jJ,$ZodBase64:()=>vJ,$ZodAsyncError:()=>u6,$ZodArray:()=>oJ,$ZodAny:()=>cJ});function K($,T,W){function X(J,z){var w;Object.defineProperty(J,"_zod",{value:J._zod??{},enumerable:!1}),(w=J._zod).traits??(w.traits=new Set),J._zod.traits.add($),T(J,z);for(let H in G.prototype)Object.defineProperty(J,H,{value:G.prototype[H].bind(J)});J._zod.constr=G,J._zod.def=z}let Y=W?.Parent??Object;class U extends Y{}Object.defineProperty(U,"name",{value:$});function G(J){var z;let w=W?.Parent?new U:this;X(w,J),(z=w._zod).deferred??(z.deferred=[]);for(let H of w._zod.deferred)H();return w}return Object.defineProperty(G,"init",{value:X}),Object.defineProperty(G,Symbol.hasInstance,{value:(J)=>{if(W?.Parent&&J instanceof W.Parent)return!0;return J?._zod?.traits?.has($)}}),Object.defineProperty(G,"name",{value:$}),G}var YG=Symbol("zod_brand");class u6 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}var zW={};function n$($){if($)Object.assign(zW,$);return zW}var g={};M1(g,{unwrapMessage:()=>_W,stringifyPrimitive:()=>u,required:()=>yA,randomString:()=>cX,propertyKeyTypes:()=>ZW,promiseAllObject:()=>kA,primitiveTypes:()=>_G,prefixIssues:()=>x4,pick:()=>vA,partial:()=>fA,optionalKeys:()=>HG,omit:()=>jA,numKeys:()=>qA,nullish:()=>R1,normalizeParams:()=>j,merge:()=>bA,jsonStringifyReplacer:()=>GG,joinValues:()=>q,issue:()=>ZG,isPlainObject:()=>QW,isObject:()=>uX,getValidEnumValues:()=>RA,getSizableOrigin:()=>DW,getParsedType:()=>PA,getLengthableOrigin:()=>OW,getElementAtPath:()=>IA,floatSafeRemainder:()=>JG,finalizeIssue:()=>n4,extend:()=>xA,escapeRegex:()=>C6,esc:()=>n1,defineLazy:()=>N$,createTransparentProxy:()=>CA,clone:()=>i4,cleanRegex:()=>FW,cleanEnum:()=>hA,cached:()=>HW,assignProp:()=>wG,assertNotEqual:()=>NA,assertNever:()=>SA,assertIs:()=>LA,assertEqual:()=>AA,assert:()=>BA,allowsEval:()=>zG,aborted:()=>t1,NUMBER_FORMAT_RANGES:()=>FG,Class:()=>H3,BIGINT_FORMAT_RANGES:()=>QG});function AA($){return $}function NA($){return $}function LA($){}function SA($){throw new Error}function BA($){}function RA($){let T=Object.keys($).filter((X)=>typeof $[$[X]]!=="number"),W={};for(let X of T)W[X]=$[X];return Object.values(W)}function q($,T="|"){return $.map((W)=>u(W)).join(T)}function GG($,T){if(typeof T==="bigint")return T.toString();return T}function HW($){return{get value(){{let W=$();return Object.defineProperty(this,"value",{value:W}),W}throw new Error("cached value already set")}}}function R1($){return $===null||$===void 0}function FW($){let T=$.startsWith("^")?1:0,W=$.endsWith("$")?$.length-1:$.length;return $.slice(T,W)}function JG($,T){let W=($.toString().split(".")[1]||"").length,X=(T.toString().split(".")[1]||"").length,Y=W>X?W:X,U=Number.parseInt($.toFixed(Y).replace(".","")),G=Number.parseInt(T.toFixed(Y).replace(".",""));return U%G/10**Y}function N$($,T,W){Object.defineProperty($,T,{get(){{let Y=W();return $[T]=Y,Y}throw new Error("cached value already set")},set(Y){Object.defineProperty($,T,{value:Y})},configurable:!0})}function wG($,T,W){Object.defineProperty($,T,{value:W,writable:!0,enumerable:!0,configurable:!0})}function IA($,T){if(!T)return $;return T.reduce((W,X)=>W?.[X],$)}function kA($){let T=Object.keys($),W=T.map((X)=>$[X]);return Promise.all(W).then((X)=>{let Y={};for(let U=0;U<T.length;U++)Y[T[U]]=X[U];return Y})}function cX($=10){let W="";for(let X=0;X<$;X++)W+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return W}function n1($){return JSON.stringify($)}function uX($){return typeof $==="object"&&$!==null}var zG=HW(()=>{try{return new Function(""),!0}catch($){return!1}});function QW($){return typeof $==="object"&&$!==null&&Object.getPrototypeOf($)===Object.prototype}function qA($){let T=0;for(let W in $)if(Object.prototype.hasOwnProperty.call($,W))T++;return T}var PA=($)=>{let T=typeof $;switch(T){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map!=="undefined"&&$ instanceof Map)return"map";if(typeof Set!=="undefined"&&$ instanceof Set)return"set";if(typeof Date!=="undefined"&&$ instanceof Date)return"date";if(typeof File!=="undefined"&&$ instanceof File)return"file";return"object";default:throw new Error(`Unknown data type: ${T}`)}},ZW=new Set(["string","number","symbol"]),_G=new Set(["string","number","bigint","boolean","symbol","undefined"]);function C6($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i4($,T,W){let X=new $._zod.constr(T??$._zod.def);if(!T||W?.parent)X._zod.parent=$;return X}function j($){let T=$;if(!T)return{};if(typeof T==="string")return{error:()=>T};if(T?.message!==void 0){if(T?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");T.error=T.message}if(delete T.message,typeof T.error==="string")return{...T,error:()=>T.error};return T}function CA($){let T;return new Proxy({},{get(W,X,Y){return T??(T=$()),Reflect.get(T,X,Y)},set(W,X,Y,U){return T??(T=$()),Reflect.set(T,X,Y,U)},has(W,X){return T??(T=$()),Reflect.has(T,X)},deleteProperty(W,X){return T??(T=$()),Reflect.deleteProperty(T,X)},ownKeys(W){return T??(T=$()),Reflect.ownKeys(T)},getOwnPropertyDescriptor(W,X){return T??(T=$()),Reflect.getOwnPropertyDescriptor(T,X)},defineProperty(W,X,Y){return T??(T=$()),Reflect.defineProperty(T,X,Y)}})}function u($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function HG($){return Object.keys($).filter((T)=>{return $[T]._zod.optin==="optional"})}var FG={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},QG={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vA($,T){let W={},X=$._zod.def;for(let Y in T){if(!(Y in X.shape))throw new Error(`Unrecognized key: "${Y}"`);if(!T[Y])continue;W[Y]=X.shape[Y]}return i4($,{...$._zod.def,shape:W,checks:[]})}function jA($,T){let W={...$._zod.def.shape},X=$._zod.def;for(let Y in T){if(!(Y in X.shape))throw new Error(`Unrecognized key: "${Y}"`);if(!T[Y])continue;delete W[Y]}return i4($,{...$._zod.def,shape:W,checks:[]})}function xA($,T){let W={...$._zod.def,get shape(){let X={...$._zod.def.shape,...T};return wG(this,"shape",X),X},checks:[]};return i4($,W)}function bA($,T){return i4($,{...$._zod.def,get shape(){let W={...$._zod.def.shape,...T._zod.def.shape};return wG(this,"shape",W),W},catchall:T._zod.def.catchall,checks:[]})}function fA($,T,W){let X=T._zod.def.shape,Y={...X};if(W)for(let U in W){if(!(U in X))throw new Error(`Unrecognized key: "${U}"`);if(!W[U])continue;Y[U]=$?new $({type:"optional",innerType:X[U]}):X[U]}else for(let U in X)Y[U]=$?new $({type:"optional",innerType:X[U]}):X[U];return i4(T,{...T._zod.def,shape:Y,checks:[]})}function yA($,T,W){let X=T._zod.def.shape,Y={...X};if(W)for(let U in W){if(!(U in Y))throw new Error(`Unrecognized key: "${U}"`);if(!W[U])continue;Y[U]=new $({type:"nonoptional",innerType:X[U]})}else for(let U in X)Y[U]=new $({type:"nonoptional",innerType:X[U]});return i4(T,{...T._zod.def,shape:Y,checks:[]})}function t1($,T=0){for(let W=T;W<$.issues.length;W++)if($.issues[W].continue!==!0)return!0;return!1}function x4($,T){return T.map((W)=>{var X;return(X=W).path??(X.path=[]),W.path.unshift($),W})}function _W($){return typeof $==="string"?$:$?.message}function n4($,T,W){let X={...$,path:$.path??[]};if(!$.message){let Y=_W($.inst?._zod.def?.error?.($))??_W(T?.error?.($))??_W(W.customError?.($))??_W(W.localeError?.($))??"Invalid input";X.message=Y}if(delete X.inst,delete X.continue,!T?.reportInput)delete X.input;return X}function DW($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function OW($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function ZG(...$){let[T,W,X]=$;if(typeof T==="string")return{message:T,code:"custom",input:W,inst:X};return{...T}}function hA($){return Object.entries($).filter(([T,W])=>{return Number.isNaN(Number.parseInt(T,10))}).map((T)=>T[1])}class H3{constructor(...$){}}var F3=($,T)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:T,enumerable:!1}),Object.defineProperty($,"message",{get(){return JSON.stringify(T,GG,2)},enumerable:!0})},VW=K("$ZodError",F3),o0=K("$ZodError",F3,{Parent:Error});function KW($,T=(W)=>W.message){let W={},X=[];for(let Y of $.issues)if(Y.path.length>0)W[Y.path[0]]=W[Y.path[0]]||[],W[Y.path[0]].push(T(Y));else X.push(T(Y));return{formErrors:X,fieldErrors:W}}function EW($,T){let W=T||function(U){return U.message},X={_errors:[]},Y=(U)=>{for(let G of U.issues)if(G.code==="invalid_union")G.errors.map((J)=>Y({issues:J}));else if(G.code==="invalid_key")Y({issues:G.issues});else if(G.code==="invalid_element")Y({issues:G.issues});else if(G.path.length===0)X._errors.push(W(G));else{let J=X,z=0;while(z<G.path.length){let w=G.path[z];if(z!==G.path.length-1)J[w]=J[w]||{_errors:[]};else J[w]=J[w]||{_errors:[]},J[w]._errors.push(W(G));J=J[w],z++}}};return Y($),X}function DG($,T){let W=T||function(U){return U.message},X={errors:[]},Y=(U,G=[])=>{var J,z;for(let w of U.issues)if(w.code==="invalid_union")w.errors.map((H)=>Y({issues:H},w.path));else if(w.code==="invalid_key")Y({issues:w.issues},w.path);else if(w.code==="invalid_element")Y({issues:w.issues},w.path);else{let H=[...G,...w.path];if(H.length===0){X.errors.push(W(w));continue}let _=X,F=0;while(F<H.length){let D=H[F],V=F===H.length-1;if(typeof D==="string")_.properties??(_.properties={}),(J=_.properties)[D]??(J[D]={errors:[]}),_=_.properties[D];else _.items??(_.items=[]),(z=_.items)[D]??(z[D]={errors:[]}),_=_.items[D];if(V)_.errors.push(W(w));F++}}};return Y($),X}function Q3($){let T=[];for(let W of $)if(typeof W==="number")T.push(`[${W}]`);else if(typeof W==="symbol")T.push(`[${JSON.stringify(String(W))}]`);else if(/[^\w$]/.test(W))T.push(`[${JSON.stringify(W)}]`);else{if(T.length)T.push(".");T.push(W)}return T.join("")}function OG($){let T=[],W=[...$.issues].sort((X,Y)=>X.path.length-Y.path.length);for(let X of W)if(T.push(`\u2716 ${X.message}`),X.path?.length)T.push(` \u2192 at ${Q3(X.path)}`);return T.join(`
|
|
6
|
+
`)}var pX=($)=>(T,W,X,Y)=>{let U=X?Object.assign(X,{async:!1}):{async:!1},G=T._zod.run({value:W,issues:[]},U);if(G instanceof Promise)throw new u6;if(G.issues.length){let J=new(Y?.Err??$)(G.issues.map((z)=>n4(z,U,n$())));throw Error.captureStackTrace(J,Y?.callee),J}return G.value},dX=pX(o0),oX=($)=>async(T,W,X,Y)=>{let U=X?Object.assign(X,{async:!0}):{async:!0},G=T._zod.run({value:W,issues:[]},U);if(G instanceof Promise)G=await G;if(G.issues.length){let J=new(Y?.Err??$)(G.issues.map((z)=>n4(z,U,n$())));throw Error.captureStackTrace(J,Y?.callee),J}return G.value},lX=oX(o0),rX=($)=>(T,W,X)=>{let Y=X?{...X,async:!1}:{async:!1},U=T._zod.run({value:W,issues:[]},Y);if(U instanceof Promise)throw new u6;return U.issues.length?{success:!1,error:new($??VW)(U.issues.map((G)=>n4(G,Y,n$())))}:{success:!0,data:U.value}},VG=rX(o0),iX=($)=>async(T,W,X)=>{let Y=X?Object.assign(X,{async:!0}):{async:!0},U=T._zod.run({value:W,issues:[]},Y);if(U instanceof Promise)U=await U;return U.issues.length?{success:!1,error:new $(U.issues.map((G)=>n4(G,Y,n$())))}:{success:!0,data:U.value}},KG=iX(o0);var s1={};M1(s1,{xid:()=>NG,uuid7:()=>pA,uuid6:()=>uA,uuid4:()=>cA,uuid:()=>a1,uppercase:()=>oG,unicodeEmail:()=>lA,undefined:()=>pG,ulid:()=>AG,time:()=>bG,string:()=>yG,rfc5322Email:()=>oA,number:()=>mG,null:()=>uG,nanoid:()=>SG,lowercase:()=>dG,ksuid:()=>LG,ipv6:()=>tX,ipv4:()=>nX,ip:()=>nA,integer:()=>gG,html5Email:()=>dA,hostname:()=>vG,guid:()=>RG,extendedDuration:()=>mA,emoji:()=>kG,email:()=>IG,e164:()=>jG,duration:()=>BG,domain:()=>tA,datetime:()=>fG,date:()=>xG,cuid2:()=>MG,cuid:()=>EG,cidrv6:()=>PG,cidrv4:()=>qG,browserEmail:()=>rA,boolean:()=>cG,bigint:()=>hG,base64url:()=>aX,base64:()=>CG,_emoji:()=>iA});var EG=/^[cC][^\s-]{8,}$/,MG=/^[0-9a-z]+$/,AG=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,NG=/^[0-9a-vA-V]{20}$/,LG=/^[A-Za-z0-9]{27}$/,SG=/^[a-zA-Z0-9_-]{21}$/,BG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mA=/^[-+]?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)?)??$/,RG=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,a1=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},cA=a1(4),uA=a1(6),pA=a1(7),IG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,dA=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,oA=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,lA=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,rA=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,iA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function kG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var nX=/^(?:(?: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])$/,tX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,qG=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,PG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nA=new RegExp(`(${nX.source})|(${tX.source})`),CG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,aX=/^[A-Za-z0-9_-]*$/,vG=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,tA=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,jG=/^\+(?:[0-9]){6,14}[0-9]$/,Z3="((\\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])))",xG=new RegExp(`^${Z3}$`);function D3($){let T="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if($.precision)T=`${T}\\.\\d{${$.precision}}`;else if($.precision==null)T=`${T}(\\.\\d+)?`;return T}function bG($){return new RegExp(`^${D3($)}$`)}function fG($){let T=`${Z3}T${D3($)}`,W=[];if(W.push($.local?"Z?":"Z"),$.offset)W.push("([+-]\\d{2}:?\\d{2})");return T=`${T}(${W.join("|")})`,new RegExp(`^${T}$`)}var yG=($)=>{let T=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${T}$`)},hG=/^\d+n?$/,gG=/^\d+$/,mG=/^-?\d+(?:\.\d+)?/i,cG=/true|false/i,uG=/null/i;var pG=/undefined/i;var dG=/^[^A-Z]*$/,oG=/^[^a-z]*$/;var u$=K("$ZodCheck",($,T)=>{var W;$._zod??($._zod={}),$._zod.def=T,(W=$._zod).onattach??(W.onattach=[])}),V3={number:"number",bigint:"bigint",object:"date"},sX=K("$ZodCheckLessThan",($,T)=>{u$.init($,T);let W=V3[typeof T.value];$._zod.onattach.push((X)=>{let Y=X._zod.bag,U=(T.inclusive?Y.maximum:Y.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(T.value<U)if(T.inclusive)Y.maximum=T.value;else Y.exclusiveMaximum=T.value}),$._zod.check=(X)=>{if(T.inclusive?X.value<=T.value:X.value<T.value)return;X.issues.push({origin:W,code:"too_big",maximum:T.value,input:X.value,inclusive:T.inclusive,inst:$,continue:!T.abort})}}),eX=K("$ZodCheckGreaterThan",($,T)=>{u$.init($,T);let W=V3[typeof T.value];$._zod.onattach.push((X)=>{let Y=X._zod.bag,U=(T.inclusive?Y.minimum:Y.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(T.value>U)if(T.inclusive)Y.minimum=T.value;else Y.exclusiveMinimum=T.value}),$._zod.check=(X)=>{if(T.inclusive?X.value>=T.value:X.value>T.value)return;X.issues.push({origin:W,code:"too_small",minimum:T.value,input:X.value,inclusive:T.inclusive,inst:$,continue:!T.abort})}}),lG=K("$ZodCheckMultipleOf",($,T)=>{u$.init($,T),$._zod.onattach.push((W)=>{var X;(X=W._zod.bag).multipleOf??(X.multipleOf=T.value)}),$._zod.check=(W)=>{if(typeof W.value!==typeof T.value)throw new Error("Cannot mix number and bigint in multiple_of check.");if(typeof W.value==="bigint"?W.value%T.value===BigInt(0):JG(W.value,T.value)===0)return;W.issues.push({origin:typeof W.value,code:"not_multiple_of",divisor:T.value,input:W.value,inst:$,continue:!T.abort})}}),rG=K("$ZodCheckNumberFormat",($,T)=>{u$.init($,T),T.format=T.format||"float64";let W=T.format?.includes("int"),X=W?"int":"number",[Y,U]=FG[T.format];$._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=T.format,J.minimum=Y,J.maximum=U,W)J.pattern=gG}),$._zod.check=(G)=>{let J=G.value;if(W){if(!Number.isInteger(J)){G.issues.push({expected:X,format:T.format,code:"invalid_type",input:J,inst:$});return}if(!Number.isSafeInteger(J)){if(J>0)G.issues.push({input:J,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!T.abort});else G.issues.push({input:J,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!T.abort});return}}if(J<Y)G.issues.push({origin:"number",input:J,code:"too_small",minimum:Y,inclusive:!0,inst:$,continue:!T.abort});if(J>U)G.issues.push({origin:"number",input:J,code:"too_big",maximum:U,inst:$})}}),iG=K("$ZodCheckBigIntFormat",($,T)=>{u$.init($,T);let[W,X]=QG[T.format];$._zod.onattach.push((Y)=>{let U=Y._zod.bag;U.format=T.format,U.minimum=W,U.maximum=X}),$._zod.check=(Y)=>{let U=Y.value;if(U<W)Y.issues.push({origin:"bigint",input:U,code:"too_small",minimum:W,inclusive:!0,inst:$,continue:!T.abort});if(U>X)Y.issues.push({origin:"bigint",input:U,code:"too_big",maximum:X,inst:$})}}),nG=K("$ZodCheckMaxSize",($,T)=>{u$.init($,T),$._zod.when=(W)=>{let X=W.value;return!R1(X)&&X.size!==void 0},$._zod.onattach.push((W)=>{let X=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(T.maximum<X)W._zod.bag.maximum=T.maximum}),$._zod.check=(W)=>{let X=W.value;if(X.size<=T.maximum)return;W.issues.push({origin:DW(X),code:"too_big",maximum:T.maximum,input:X,inst:$,continue:!T.abort})}}),tG=K("$ZodCheckMinSize",($,T)=>{u$.init($,T),$._zod.when=(W)=>{let X=W.value;return!R1(X)&&X.size!==void 0},$._zod.onattach.push((W)=>{let X=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(T.minimum>X)W._zod.bag.minimum=T.minimum}),$._zod.check=(W)=>{let X=W.value;if(X.size>=T.minimum)return;W.issues.push({origin:DW(X),code:"too_small",minimum:T.minimum,input:X,inst:$,continue:!T.abort})}}),aG=K("$ZodCheckSizeEquals",($,T)=>{u$.init($,T),$._zod.when=(W)=>{let X=W.value;return!R1(X)&&X.size!==void 0},$._zod.onattach.push((W)=>{let X=W._zod.bag;X.minimum=T.size,X.maximum=T.size,X.size=T.size}),$._zod.check=(W)=>{let X=W.value,Y=X.size;if(Y===T.size)return;let U=Y>T.size;W.issues.push({origin:DW(X),...U?{code:"too_big",maximum:T.size}:{code:"too_small",minimum:T.size},input:W.value,inst:$,continue:!T.abort})}}),sG=K("$ZodCheckMaxLength",($,T)=>{u$.init($,T),$._zod.when=(W)=>{let X=W.value;return!R1(X)&&X.length!==void 0},$._zod.onattach.push((W)=>{let X=W._zod.bag.maximum??Number.POSITIVE_INFINITY;if(T.maximum<X)W._zod.bag.maximum=T.maximum}),$._zod.check=(W)=>{let X=W.value;if(X.length<=T.maximum)return;let U=OW(X);W.issues.push({origin:U,code:"too_big",maximum:T.maximum,input:X,inst:$,continue:!T.abort})}}),eG=K("$ZodCheckMinLength",($,T)=>{u$.init($,T),$._zod.when=(W)=>{let X=W.value;return!R1(X)&&X.length!==void 0},$._zod.onattach.push((W)=>{let X=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(T.minimum>X)W._zod.bag.minimum=T.minimum}),$._zod.check=(W)=>{let X=W.value;if(X.length>=T.minimum)return;let U=OW(X);W.issues.push({origin:U,code:"too_small",minimum:T.minimum,input:X,inst:$,continue:!T.abort})}}),$J=K("$ZodCheckLengthEquals",($,T)=>{u$.init($,T),$._zod.when=(W)=>{let X=W.value;return!R1(X)&&X.length!==void 0},$._zod.onattach.push((W)=>{let X=W._zod.bag;X.minimum=T.length,X.maximum=T.length,X.length=T.length}),$._zod.check=(W)=>{let X=W.value,Y=X.length;if(Y===T.length)return;let U=OW(X),G=Y>T.length;W.issues.push({origin:U,...G?{code:"too_big",maximum:T.length}:{code:"too_small",minimum:T.length},input:W.value,inst:$,continue:!T.abort})}}),l0=K("$ZodCheckStringFormat",($,T)=>{var W;u$.init($,T),$._zod.onattach.push((X)=>{if(X._zod.bag.format=T.format,T.pattern)X._zod.bag.pattern=T.pattern}),(W=$._zod).check??(W.check=(X)=>{if(!T.pattern)throw new Error("Not implemented.");if(T.pattern.lastIndex=0,T.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:T.format,input:X.value,...T.pattern?{pattern:T.pattern.toString()}:{},inst:$,continue:!T.abort})})}),TJ=K("$ZodCheckRegex",($,T)=>{l0.init($,T),$._zod.check=(W)=>{if(T.pattern.lastIndex=0,T.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:"regex",input:W.value,pattern:T.pattern.toString(),inst:$,continue:!T.abort})}}),WJ=K("$ZodCheckLowerCase",($,T)=>{T.pattern??(T.pattern=dG),l0.init($,T)}),XJ=K("$ZodCheckUpperCase",($,T)=>{T.pattern??(T.pattern=oG),l0.init($,T)}),YJ=K("$ZodCheckIncludes",($,T)=>{u$.init($,T);let W=new RegExp(C6(T.includes));T.pattern=W,$._zod.onattach.push((X)=>{X._zod.bag.pattern=W}),$._zod.check=(X)=>{if(X.value.includes(T.includes,T.position))return;X.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:T.includes,input:X.value,inst:$,continue:!T.abort})}}),UJ=K("$ZodCheckStartsWith",($,T)=>{u$.init($,T);let W=new RegExp(`^${C6(T.prefix)}.*`);T.pattern??(T.pattern=W),$._zod.onattach.push((X)=>{X._zod.bag.pattern=W}),$._zod.check=(X)=>{if(X.value.startsWith(T.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:T.prefix,input:X.value,inst:$,continue:!T.abort})}}),GJ=K("$ZodCheckEndsWith",($,T)=>{u$.init($,T);let W=new RegExp(`.*${C6(T.suffix)}$`);T.pattern??(T.pattern=W),$._zod.onattach.push((X)=>{X._zod.bag.pattern=new RegExp(`.*${C6(T.suffix)}$`)}),$._zod.check=(X)=>{if(X.value.endsWith(T.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:T.suffix,input:X.value,inst:$,continue:!T.abort})}});function O3($,T,W){if($.issues.length)T.issues.push(...x4(W,$.issues))}var JJ=K("$ZodCheckProperty",($,T)=>{u$.init($,T),$._zod.check=(W)=>{let X=T.schema._zod.run({value:W.value[T.property],issues:[]},{});if(X instanceof Promise)return X.then((Y)=>O3(Y,W,T.property));O3(X,W,T.property);return}}),wJ=K("$ZodCheckMimeType",($,T)=>{u$.init($,T);let W=new Set(T.mime);$._zod.onattach.push((X)=>{X._zod.bag.mime=T.mime}),$._zod.check=(X)=>{if(W.has(X.value.type))return;X.issues.push({code:"invalid_value",values:T.mime,input:X.value.type,path:["type"],inst:$})}}),zJ=K("$ZodCheckOverwrite",($,T)=>{u$.init($,T),$._zod.check=(W)=>{W.value=T.tx(W.value)}});class $Y{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let W=$.split(`
|
|
7
|
+
`).filter((U)=>U),X=Math.min(...W.map((U)=>U.length-U.trimStart().length)),Y=W.map((U)=>U.slice(X)).map((U)=>" ".repeat(this.indent*2)+U);for(let U of Y)this.content.push(U)}compile(){let $=Function,T=this?.args,X=[...(this?.content??[""]).map((Y)=>` ${Y}`)];return new $(...T,X.join(`
|
|
8
|
+
`))}}var _J={major:4,minor:0,patch:0};var W$=K("$ZodType",($,T)=>{var W;$??($={}),$._zod.id=T.type+"_"+cX(10),$._zod.def=T,$._zod.bag=$._zod.bag||{},$._zod.version=_J;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let Y of X)for(let U of Y._zod.onattach)U($);if(X.length===0)(W=$._zod).deferred??(W.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let Y=(U,G,J)=>{let z=t1(U),w;for(let H of G){if(H._zod.when){if(!H._zod.when(U))continue}else if(z)continue;let _=U.issues.length,F=H._zod.check(U);if(F instanceof Promise&&J?.async===!1)throw new u6;if(w||F instanceof Promise)w=(w??Promise.resolve()).then(async()=>{if(await F,U.issues.length===_)return;if(!z)z=t1(U,_)});else{if(U.issues.length===_)continue;if(!z)z=t1(U,_)}}if(w)return w.then(()=>{return U});return U};$._zod.run=(U,G)=>{let J=$._zod.parse(U,G);if(J instanceof Promise){if(G.async===!1)throw new u6;return J.then((z)=>Y(z,X,G))}return Y(J,X,G)}}$["~standard"]={validate:(Y)=>{try{let U=VG($,Y);return U.success?{value:U.data}:{issues:U.error?.issues}}catch(U){return KG($,Y).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}}),MW=K("$ZodString",($,T)=>{W$.init($,T),$._zod.pattern=$?._zod.bag?.pattern??yG($._zod.bag),$._zod.parse=(W,X)=>{if(T.coerce)try{W.value=String(W.value)}catch(Y){}if(typeof W.value==="string")return W;return W.issues.push({expected:"string",code:"invalid_type",input:W.value,inst:$}),W}}),q$=K("$ZodStringFormat",($,T)=>{l0.init($,T),MW.init($,T)}),FJ=K("$ZodGUID",($,T)=>{T.pattern??(T.pattern=RG),q$.init($,T)}),QJ=K("$ZodUUID",($,T)=>{if(T.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[T.version];if(X===void 0)throw new Error(`Invalid UUID version: "${T.version}"`);T.pattern??(T.pattern=a1(X))}else T.pattern??(T.pattern=a1());q$.init($,T)}),ZJ=K("$ZodEmail",($,T)=>{T.pattern??(T.pattern=IG),q$.init($,T)}),DJ=K("$ZodURL",($,T)=>{q$.init($,T),$._zod.check=(W)=>{try{let X=new URL(W.value);if(T.hostname){if(T.hostname.lastIndex=0,!T.hostname.test(X.hostname))W.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:vG.source,input:W.value,inst:$})}if(T.protocol){if(T.protocol.lastIndex=0,!T.protocol.test(X.protocol.endsWith(":")?X.protocol.slice(0,-1):X.protocol))W.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:T.protocol.source,input:W.value,inst:$})}return}catch(X){W.issues.push({code:"invalid_format",format:"url",input:W.value,inst:$})}}}),OJ=K("$ZodEmoji",($,T)=>{T.pattern??(T.pattern=kG()),q$.init($,T)}),VJ=K("$ZodNanoID",($,T)=>{T.pattern??(T.pattern=SG),q$.init($,T)}),KJ=K("$ZodCUID",($,T)=>{T.pattern??(T.pattern=EG),q$.init($,T)}),EJ=K("$ZodCUID2",($,T)=>{T.pattern??(T.pattern=MG),q$.init($,T)}),MJ=K("$ZodULID",($,T)=>{T.pattern??(T.pattern=AG),q$.init($,T)}),AJ=K("$ZodXID",($,T)=>{T.pattern??(T.pattern=NG),q$.init($,T)}),NJ=K("$ZodKSUID",($,T)=>{T.pattern??(T.pattern=LG),q$.init($,T)}),LJ=K("$ZodISODateTime",($,T)=>{T.pattern??(T.pattern=fG(T)),q$.init($,T)}),SJ=K("$ZodISODate",($,T)=>{T.pattern??(T.pattern=xG),q$.init($,T)}),BJ=K("$ZodISOTime",($,T)=>{T.pattern??(T.pattern=bG(T)),q$.init($,T)}),RJ=K("$ZodISODuration",($,T)=>{T.pattern??(T.pattern=BG),q$.init($,T)}),IJ=K("$ZodIPv4",($,T)=>{T.pattern??(T.pattern=nX),q$.init($,T),$._zod.onattach.push((W)=>{W._zod.bag.format="ipv4"})}),kJ=K("$ZodIPv6",($,T)=>{T.pattern??(T.pattern=tX),q$.init($,T),$._zod.onattach.push((W)=>{W._zod.bag.format="ipv6"}),$._zod.check=(W)=>{try{new URL(`http://[${W.value}]`)}catch{W.issues.push({code:"invalid_format",format:"ipv6",input:W.value,inst:$})}}}),qJ=K("$ZodCIDRv4",($,T)=>{T.pattern??(T.pattern=qG),q$.init($,T)}),PJ=K("$ZodCIDRv6",($,T)=>{T.pattern??(T.pattern=PG),q$.init($,T),$._zod.check=(W)=>{let[X,Y]=W.value.split("/");try{if(!Y)throw new Error;let U=Number(Y);if(`${U}`!==Y)throw new Error;if(U<0||U>128)throw new Error;new URL(`http://[${X}]`)}catch{W.issues.push({code:"invalid_format",format:"cidrv6",input:W.value,inst:$})}}});function CJ($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var vJ=K("$ZodBase64",($,T)=>{T.pattern??(T.pattern=CG),q$.init($,T),$._zod.onattach.push((W)=>{W._zod.bag.contentEncoding="base64"}),$._zod.check=(W)=>{if(CJ(W.value))return;W.issues.push({code:"invalid_format",format:"base64",input:W.value,inst:$})}});function P3($){if(!aX.test($))return!1;let T=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),W=T.padEnd(Math.ceil(T.length/4)*4,"=");return CJ(W)}var jJ=K("$ZodBase64URL",($,T)=>{T.pattern??(T.pattern=aX),q$.init($,T),$._zod.onattach.push((W)=>{W._zod.bag.contentEncoding="base64url"}),$._zod.check=(W)=>{if(P3(W.value))return;W.issues.push({code:"invalid_format",format:"base64url",input:W.value,inst:$})}}),xJ=K("$ZodE164",($,T)=>{T.pattern??(T.pattern=jG),q$.init($,T)});function C3($,T=null){try{let W=$.split(".");if(W.length!==3)return!1;let[X]=W,Y=JSON.parse(atob(X));if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(T&&(!("alg"in Y)||Y.alg!==T))return!1;return!0}catch{return!1}}var bJ=K("$ZodJWT",($,T)=>{q$.init($,T),$._zod.check=(W)=>{if(C3(W.value,T.alg))return;W.issues.push({code:"invalid_format",format:"jwt",input:W.value,inst:$})}}),XY=K("$ZodNumber",($,T)=>{W$.init($,T),$._zod.pattern=$._zod.bag.pattern??mG,$._zod.parse=(W,X)=>{if(T.coerce)try{W.value=Number(W.value)}catch(G){}let Y=W.value;if(typeof Y==="number"&&!Number.isNaN(Y)&&Number.isFinite(Y))return W;let U=typeof Y==="number"?Number.isNaN(Y)?"NaN":!Number.isFinite(Y)?"Infinity":void 0:void 0;return W.issues.push({expected:"number",code:"invalid_type",input:Y,inst:$,...U?{received:U}:{}}),W}}),fJ=K("$ZodNumber",($,T)=>{rG.init($,T),XY.init($,T)}),AW=K("$ZodBoolean",($,T)=>{W$.init($,T),$._zod.pattern=cG,$._zod.parse=(W,X)=>{if(T.coerce)try{W.value=Boolean(W.value)}catch(U){}let Y=W.value;if(typeof Y==="boolean")return W;return W.issues.push({expected:"boolean",code:"invalid_type",input:Y,inst:$}),W}}),YY=K("$ZodBigInt",($,T)=>{W$.init($,T),$._zod.pattern=hG,$._zod.parse=(W,X)=>{if(T.coerce)try{W.value=BigInt(W.value)}catch(U){}let{value:Y}=W;if(typeof Y==="bigint")return W;return W.issues.push({expected:"bigint",code:"invalid_type",input:Y,inst:$}),W}}),yJ=K("$ZodBigInt",($,T)=>{iG.init($,T),YY.init($,T)}),hJ=K("$ZodSymbol",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let{value:Y}=W;if(typeof Y==="symbol")return W;return W.issues.push({expected:"symbol",code:"invalid_type",input:Y,inst:$}),W}}),gJ=K("$ZodUndefined",($,T)=>{W$.init($,T),$._zod.pattern=pG,$._zod.values=new Set([void 0]),$._zod.parse=(W,X)=>{let{value:Y}=W;if(typeof Y==="undefined")return W;return W.issues.push({expected:"undefined",code:"invalid_type",input:Y,inst:$}),W}}),mJ=K("$ZodNull",($,T)=>{W$.init($,T),$._zod.pattern=uG,$._zod.values=new Set([null]),$._zod.parse=(W,X)=>{let{value:Y}=W;if(Y===null)return W;return W.issues.push({expected:"null",code:"invalid_type",input:Y,inst:$}),W}}),cJ=K("$ZodAny",($,T)=>{W$.init($,T),$._zod.parse=(W)=>W}),NW=K("$ZodUnknown",($,T)=>{W$.init($,T),$._zod.parse=(W)=>W}),uJ=K("$ZodNever",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{return W.issues.push({expected:"never",code:"invalid_type",input:W.value,inst:$}),W}}),pJ=K("$ZodVoid",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let{value:Y}=W;if(typeof Y==="undefined")return W;return W.issues.push({expected:"void",code:"invalid_type",input:Y,inst:$}),W}}),dJ=K("$ZodDate",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{if(T.coerce)try{W.value=new Date(W.value)}catch(J){}let Y=W.value,U=Y instanceof Date;if(U&&!Number.isNaN(Y.getTime()))return W;return W.issues.push({expected:"date",code:"invalid_type",input:Y,...U?{received:"Invalid Date"}:{},inst:$}),W}});function E3($,T,W){if($.issues.length)T.issues.push(...x4(W,$.issues));T.value[W]=$.value}var oJ=K("$ZodArray",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=W.value;if(!Array.isArray(Y))return W.issues.push({expected:"array",code:"invalid_type",input:Y,inst:$}),W;W.value=Array(Y.length);let U=[];for(let G=0;G<Y.length;G++){let J=Y[G],z=T.element._zod.run({value:J,issues:[]},X);if(z instanceof Promise)U.push(z.then((w)=>E3(w,W,G)));else E3(z,W,G)}if(U.length)return Promise.all(U).then(()=>W);return W}});function TY($,T,W){if($.issues.length)T.issues.push(...x4(W,$.issues));T.value[W]=$.value}function M3($,T,W,X){if($.issues.length)if(X[W]===void 0)if(W in X)T.value[W]=void 0;else T.value[W]=$.value;else T.issues.push(...x4(W,$.issues));else if($.value===void 0){if(W in X)T.value[W]=void 0}else T.value[W]=$.value}var lJ=K("$ZodObject",($,T)=>{W$.init($,T);let W=HW(()=>{let _=Object.keys(T.shape),F=HG(T.shape);return{shape:T.shape,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(F)}});N$($._zod,"disc",()=>{let _=T.shape,F=new Map,D=!1;for(let V in _){let E=_[V]._zod;if(E.values||E.disc){D=!0;let R={values:new Set(E.values??[]),maps:E.disc?[E.disc]:[]};F.set(V,R)}}if(!D)return;return F});let X=(_)=>{let F=new $Y(["shape","payload","ctx"]),{keys:D,optionalKeys:V}=W.value,E=(A)=>{let N=n1(A);return`shape[${N}]._zod.run({ value: input[${N}], issues: [] }, ctx)`};F.write("const input = payload.value;");let R=Object.create(null);for(let A of D)R[A]=cX(15);F.write("const newResult = {}");for(let A of D)if(V.has(A)){let N=R[A];F.write(`const ${N} = ${E(A)};`);let k=n1(A);F.write(`
|
|
9
|
+
if (${N}.issues.length) {
|
|
10
|
+
if (input[${k}] === undefined) {
|
|
11
|
+
if (${k} in input) {
|
|
12
|
+
newResult[${k}] = undefined;
|
|
13
|
+
}
|
|
14
|
+
} else {
|
|
15
|
+
payload.issues = payload.issues.concat(
|
|
16
|
+
${N}.issues.map((iss) => ({
|
|
17
|
+
...iss,
|
|
18
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}],
|
|
19
|
+
}))
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
} else if (${N}.value === undefined) {
|
|
23
|
+
if (${k} in input) newResult[${k}] = undefined;
|
|
24
|
+
} else {
|
|
25
|
+
newResult[${k}] = ${N}.value;
|
|
26
|
+
}
|
|
27
|
+
`)}else{let N=R[A];F.write(`const ${N} = ${E(A)};`),F.write(`
|
|
28
|
+
if (${N}.issues.length) payload.issues = payload.issues.concat(${N}.issues.map(iss => ({
|
|
29
|
+
...iss,
|
|
30
|
+
path: iss.path ? [${n1(A)}, ...iss.path] : [${n1(A)}]
|
|
31
|
+
})));`),F.write(`newResult[${n1(A)}] = ${N}.value`)}F.write("payload.value = newResult;"),F.write("return payload;");let P=F.compile();return(A,N)=>P(_,A,N)},Y,U=uX,G=!zW.jitless,z=G&&zG.value,{catchall:w}=T,H;$._zod.parse=(_,F)=>{H??(H=W.value);let D=_.value;if(!U(D))return _.issues.push({expected:"object",code:"invalid_type",input:D,inst:$}),_;let V=[];if(G&&z&&F?.async===!1&&F.jitless!==!0){if(!Y)Y=X(T.shape);_=Y(_,F)}else{_.value={};let N=H.shape;for(let k of H.keys){let y=N[k],x=y._zod.run({value:D[k],issues:[]},F),m=y._zod.optin==="optional";if(x instanceof Promise)V.push(x.then((J$)=>m?M3(J$,_,k,D):TY(J$,_,k)));else if(m)M3(x,_,k,D);else TY(x,_,k)}}if(!w)return V.length?Promise.all(V).then(()=>_):_;let E=[],R=H.keySet,P=w._zod,A=P.def.type;for(let N of Object.keys(D)){if(R.has(N))continue;if(A==="never"){E.push(N);continue}let k=P.run({value:D[N],issues:[]},F);if(k instanceof Promise)V.push(k.then((y)=>TY(y,_,N)));else TY(k,_,N)}if(E.length)_.issues.push({code:"unrecognized_keys",keys:E,input:D,inst:$});if(!V.length)return _;return Promise.all(V).then(()=>{return _})}});function A3($,T,W,X){for(let Y of $)if(Y.issues.length===0)return T.value=Y.value,T;return T.issues.push({code:"invalid_union",input:T.value,inst:W,errors:$.map((Y)=>Y.issues.map((U)=>n4(U,X,n$())))}),T}var UY=K("$ZodUnion",($,T)=>{W$.init($,T),N$($._zod,"values",()=>{if(T.options.every((W)=>W._zod.values))return new Set(T.options.flatMap((W)=>Array.from(W._zod.values)));return}),N$($._zod,"pattern",()=>{if(T.options.every((W)=>W._zod.pattern)){let W=T.options.map((X)=>X._zod.pattern);return new RegExp(`^(${W.map((X)=>FW(X.source)).join("|")})$`)}return}),$._zod.parse=(W,X)=>{let Y=!1,U=[];for(let G of T.options){let J=G._zod.run({value:W.value,issues:[]},X);if(J instanceof Promise)U.push(J),Y=!0;else{if(J.issues.length===0)return J;U.push(J)}}if(!Y)return A3(U,W,$,X);return Promise.all(U).then((G)=>{return A3(G,W,$,X)})}});function v3($,T,W){let X=!0,Y=$?.[T];if(W.values.size&&!W.values.has(Y))X=!1;if(W.maps.length>0){for(let U of W.maps)if(!aA(Y,U))X=!1}return X}function aA($,T){let W=!0;for(let[X,Y]of T)if(!v3($,X,Y))W=!1;return W}var rJ=K("$ZodDiscriminatedUnion",($,T)=>{UY.init($,T);let W=$._zod.parse;N$($._zod,"disc",()=>{let Y=new Map;for(let U of T.options){let G=U._zod.disc;if(!G)throw new Error(`Invalid discriminated union option at index "${T.options.indexOf(U)}"`);for(let[J,z]of G){if(!Y.has(J))Y.set(J,{values:new Set,maps:[]});let w=Y.get(J);for(let H of z.values)w.values.add(H);for(let H of z.maps)w.maps.push(H)}}return Y});let X=HW(()=>{let Y=new Map;for(let U of T.options){let G=U._zod.disc?.get(T.discriminator);if(!G)throw new Error("Invalid discriminated union option");Y.set(U,G)}return Y});$._zod.parse=(Y,U)=>{let G=Y.value;if(!uX(G))return Y.issues.push({code:"invalid_type",expected:"object",input:G,inst:$}),Y;let J=[],z=X.value;for(let w of T.options){let H=z.get(w);if(v3(G,T.discriminator,H))J.push(w)}if(J.length===1)return J[0]._zod.run(Y,U);if(T.unionFallback)return W(Y,U);return Y.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:G,path:[T.discriminator],inst:$}),Y}}),iJ=K("$ZodIntersection",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let{value:Y}=W,U=T.left._zod.run({value:Y,issues:[]},X),G=T.right._zod.run({value:Y,issues:[]},X);if(U instanceof Promise||G instanceof Promise)return Promise.all([U,G]).then(([z,w])=>{return N3(W,z,w)});return N3(W,U,G)}});function HJ($,T){if($===T)return{valid:!0,data:$};if($ instanceof Date&&T instanceof Date&&+$===+T)return{valid:!0,data:$};if(QW($)&&QW(T)){let W=Object.keys(T),X=Object.keys($).filter((U)=>W.indexOf(U)!==-1),Y={...$,...T};for(let U of X){let G=HJ($[U],T[U]);if(!G.valid)return{valid:!1,mergeErrorPath:[U,...G.mergeErrorPath]};Y[U]=G.data}return{valid:!0,data:Y}}if(Array.isArray($)&&Array.isArray(T)){if($.length!==T.length)return{valid:!1,mergeErrorPath:[]};let W=[];for(let X=0;X<$.length;X++){let Y=$[X],U=T[X],G=HJ(Y,U);if(!G.valid)return{valid:!1,mergeErrorPath:[X,...G.mergeErrorPath]};W.push(G.data)}return{valid:!0,data:W}}return{valid:!1,mergeErrorPath:[]}}function N3($,T,W){if(T.issues.length)$.issues.push(...T.issues);if(W.issues.length)$.issues.push(...W.issues);if(t1($))return $;let X=HJ(T.value,W.value);if(!X.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}var e1=K("$ZodTuple",($,T)=>{W$.init($,T);let W=T.items,X=W.length-[...W].reverse().findIndex((Y)=>Y._zod.optin!=="optional");$._zod.parse=(Y,U)=>{let G=Y.value;if(!Array.isArray(G))return Y.issues.push({input:G,inst:$,expected:"tuple",code:"invalid_type"}),Y;Y.value=[];let J=[];if(!T.rest){let w=G.length>W.length,H=G.length<X-1;if(w||H)return Y.issues.push({input:G,inst:$,origin:"array",...w?{code:"too_big",maximum:W.length}:{code:"too_small",minimum:W.length}}),Y}let z=-1;for(let w of W){if(z++,z>=G.length){if(z>=X)continue}let H=w._zod.run({value:G[z],issues:[]},U);if(H instanceof Promise)J.push(H.then((_)=>WY(_,Y,z)));else WY(H,Y,z)}if(T.rest){let w=G.slice(W.length);for(let H of w){z++;let _=T.rest._zod.run({value:H,issues:[]},U);if(_ instanceof Promise)J.push(_.then((F)=>WY(F,Y,z)));else WY(_,Y,z)}}if(J.length)return Promise.all(J).then(()=>Y);return Y}});function WY($,T,W){if($.issues.length)T.issues.push(...x4(W,$.issues));T.value[W]=$.value}var nJ=K("$ZodRecord",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=W.value;if(!QW(Y))return W.issues.push({expected:"record",code:"invalid_type",input:Y,inst:$}),W;let U=[];if(T.keyType._zod.values){let G=T.keyType._zod.values;W.value={};for(let z of G)if(typeof z==="string"||typeof z==="number"||typeof z==="symbol"){let w=T.valueType._zod.run({value:Y[z],issues:[]},X);if(w instanceof Promise)U.push(w.then((H)=>{if(H.issues.length)W.issues.push(...x4(z,H.issues));W.value[z]=H.value}));else{if(w.issues.length)W.issues.push(...x4(z,w.issues));W.value[z]=w.value}}let J;for(let z in Y)if(!G.has(z))J=J??[],J.push(z);if(J&&J.length>0)W.issues.push({code:"unrecognized_keys",input:Y,inst:$,keys:J})}else{W.value={};for(let G of Reflect.ownKeys(Y)){if(G==="__proto__")continue;let J=T.keyType._zod.run({value:G,issues:[]},X);if(J instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(J.issues.length){W.issues.push({origin:"record",code:"invalid_key",issues:J.issues.map((w)=>n4(w,X,n$())),input:G,path:[G],inst:$}),W.value[J.value]=J.value;continue}let z=T.valueType._zod.run({value:Y[G],issues:[]},X);if(z instanceof Promise)U.push(z.then((w)=>{if(w.issues.length)W.issues.push(...x4(G,w.issues));W.value[J.value]=w.value}));else{if(z.issues.length)W.issues.push(...x4(G,z.issues));W.value[J.value]=z.value}}}if(U.length)return Promise.all(U).then(()=>W);return W}}),tJ=K("$ZodMap",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=W.value;if(!(Y instanceof Map))return W.issues.push({expected:"map",code:"invalid_type",input:Y,inst:$}),W;let U=[];W.value=new Map;for(let[G,J]of Y){let z=T.keyType._zod.run({value:G,issues:[]},X),w=T.valueType._zod.run({value:J,issues:[]},X);if(z instanceof Promise||w instanceof Promise)U.push(Promise.all([z,w]).then(([H,_])=>{L3(H,_,W,G,Y,$,X)}));else L3(z,w,W,G,Y,$,X)}if(U.length)return Promise.all(U).then(()=>W);return W}});function L3($,T,W,X,Y,U,G){if($.issues.length)if(ZW.has(typeof X))W.issues.push(...x4(X,$.issues));else W.issues.push({origin:"map",code:"invalid_key",input:Y,inst:U,issues:$.issues.map((J)=>n4(J,G,n$()))});if(T.issues.length)if(ZW.has(typeof X))W.issues.push(...x4(X,T.issues));else W.issues.push({origin:"map",code:"invalid_element",input:Y,inst:U,key:X,issues:T.issues.map((J)=>n4(J,G,n$()))});W.value.set($.value,T.value)}var aJ=K("$ZodSet",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=W.value;if(!(Y instanceof Set))return W.issues.push({input:Y,inst:$,expected:"set",code:"invalid_type"}),W;let U=[];W.value=new Set;for(let G of Y){let J=T.valueType._zod.run({value:G,issues:[]},X);if(J instanceof Promise)U.push(J.then((z)=>S3(z,W)));else S3(J,W)}if(U.length)return Promise.all(U).then(()=>W);return W}});function S3($,T){if($.issues.length)T.issues.push(...$.issues);T.value.add($.value)}var sJ=K("$ZodEnum",($,T)=>{W$.init($,T);let W=Object.values(T.entries).filter((Y)=>typeof Y==="number"),X=Object.entries(T.entries).filter(([Y,U])=>W.indexOf(+Y)===-1).map(([Y,U])=>U);$._zod.values=new Set(X),$._zod.pattern=new RegExp(`^(${X.filter((Y)=>ZW.has(typeof Y)).map((Y)=>typeof Y==="string"?C6(Y):Y.toString()).join("|")})$`),$._zod.parse=(Y,U)=>{let G=Y.value;if($._zod.values.has(G))return Y;return Y.issues.push({code:"invalid_value",values:X,input:G,inst:$}),Y}}),eJ=K("$ZodLiteral",($,T)=>{W$.init($,T),$._zod.values=new Set(T.values),$._zod.pattern=new RegExp(`^(${T.values.map((W)=>typeof W==="string"?C6(W):W?W.toString():String(W)).join("|")})$`),$._zod.parse=(W,X)=>{let Y=W.value;if($._zod.values.has(Y))return W;return W.issues.push({code:"invalid_value",values:T.values,input:Y,inst:$}),W}}),$9=K("$ZodFile",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=W.value;if(Y instanceof File)return W;return W.issues.push({expected:"file",code:"invalid_type",input:Y,inst:$}),W}}),T9=K("$ZodTransform",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=T.transform(W.value,W);if(X.async)return(Y instanceof Promise?Y:Promise.resolve(Y)).then((G)=>{return W.value=G,W});if(Y instanceof Promise)throw new u6;return W.value=Y,W}}),W9=K("$ZodOptional",($,T)=>{W$.init($,T),$._zod.optin="optional",$._zod.optout="optional",N$($._zod,"values",()=>{return T.innerType._zod.values?new Set([...T.innerType._zod.values,void 0]):void 0}),N$($._zod,"pattern",()=>{let W=T.innerType._zod.pattern;return W?new RegExp(`^(${FW(W.source)})?$`):void 0}),$._zod.parse=(W,X)=>{if(W.value===void 0)return W;return T.innerType._zod.run(W,X)}}),X9=K("$ZodNullable",($,T)=>{W$.init($,T),N$($._zod,"optin",()=>T.innerType._zod.optin),N$($._zod,"optout",()=>T.innerType._zod.optout),N$($._zod,"pattern",()=>{let W=T.innerType._zod.pattern;return W?new RegExp(`^(${FW(W.source)}|null)$`):void 0}),N$($._zod,"values",()=>{return T.innerType._zod.values?new Set([...T.innerType._zod.values,null]):void 0}),$._zod.parse=(W,X)=>{if(W.value===null)return W;return T.innerType._zod.run(W,X)}}),Y9=K("$ZodDefault",($,T)=>{W$.init($,T),$._zod.optin="optional",N$($._zod,"values",()=>T.innerType._zod.values),$._zod.parse=(W,X)=>{if(W.value===void 0)return W.value=T.defaultValue,W;let Y=T.innerType._zod.run(W,X);if(Y instanceof Promise)return Y.then((U)=>B3(U,T));return B3(Y,T)}});function B3($,T){if($.value===void 0)$.value=T.defaultValue;return $}var U9=K("$ZodPrefault",($,T)=>{W$.init($,T),$._zod.optin="optional",N$($._zod,"values",()=>T.innerType._zod.values),$._zod.parse=(W,X)=>{if(W.value===void 0)W.value=T.defaultValue;return T.innerType._zod.run(W,X)}}),G9=K("$ZodNonOptional",($,T)=>{W$.init($,T),N$($._zod,"values",()=>{let W=T.innerType._zod.values;return W?new Set([...W].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(W,X)=>{let Y=T.innerType._zod.run(W,X);if(Y instanceof Promise)return Y.then((U)=>R3(U,$));return R3(Y,$)}});function R3($,T){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:T});return $}var J9=K("$ZodSuccess",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{let Y=T.innerType._zod.run(W,X);if(Y instanceof Promise)return Y.then((U)=>{return W.value=U.issues.length===0,W});return W.value=Y.issues.length===0,W}}),w9=K("$ZodCatch",($,T)=>{W$.init($,T),N$($._zod,"optin",()=>T.innerType._zod.optin),N$($._zod,"optout",()=>T.innerType._zod.optout),N$($._zod,"values",()=>T.innerType._zod.values),$._zod.parse=(W,X)=>{let Y=T.innerType._zod.run(W,X);if(Y instanceof Promise)return Y.then((U)=>{if(W.value=U.value,U.issues.length)W.value=T.catchValue({...W,error:{issues:U.issues.map((G)=>n4(G,X,n$()))},input:W.value}),W.issues=[];return W});if(W.value=Y.value,Y.issues.length)W.value=T.catchValue({...W,error:{issues:Y.issues.map((U)=>n4(U,X,n$()))},input:W.value}),W.issues=[];return W}}),z9=K("$ZodNaN",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{if(typeof W.value!=="number"||!Number.isNaN(W.value))return W.issues.push({input:W.value,inst:$,expected:"nan",code:"invalid_type"}),W;return W}}),LW=K("$ZodPipe",($,T)=>{W$.init($,T),N$($._zod,"values",()=>T.in._zod.values),N$($._zod,"optin",()=>T.in._zod.optin),N$($._zod,"optout",()=>T.out._zod.optout),$._zod.parse=(W,X)=>{let Y=T.in._zod.run(W,X);if(Y instanceof Promise)return Y.then((U)=>I3(U,T,X));return I3(Y,T,X)}});function I3($,T,W){if(t1($))return $;return T.out._zod.run({value:$.value,issues:$.issues},W)}var _9=K("$ZodReadonly",($,T)=>{W$.init($,T),N$($._zod,"disc",()=>T.innerType._zod.disc),N$($._zod,"optin",()=>T.innerType._zod.optin),N$($._zod,"optout",()=>T.innerType._zod.optout),$._zod.parse=(W,X)=>{let Y=T.innerType._zod.run(W,X);if(Y instanceof Promise)return Y.then(k3);return k3(Y)}});function k3($){return $.value=Object.freeze($.value),$}var H9=K("$ZodTemplateLiteral",($,T)=>{W$.init($,T);let W=[];for(let X of T.parts)if(X instanceof W$){if(!X._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...X._zod.traits].shift()}`);let Y=X._zod.pattern instanceof RegExp?X._zod.pattern.source:X._zod.pattern;if(!Y)throw new Error(`Invalid template literal part: ${X._zod.traits}`);let U=Y.startsWith("^")?1:0,G=Y.endsWith("$")?Y.length-1:Y.length;W.push(Y.slice(U,G))}else if(X===null||_G.has(typeof X))W.push(C6(`${X}`));else throw new Error(`Invalid template literal part: ${X}`);$._zod.pattern=new RegExp(`^${W.join("")}$`),$._zod.parse=(X,Y)=>{if(typeof X.value!=="string")return X.issues.push({input:X.value,inst:$,expected:"template_literal",code:"invalid_type"}),X;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(X.value))return X.issues.push({input:X.value,inst:$,code:"invalid_format",format:"template_literal",pattern:$._zod.pattern.source}),X;return X}}),F9=K("$ZodPromise",($,T)=>{W$.init($,T),$._zod.parse=(W,X)=>{return Promise.resolve(W.value).then((Y)=>T.innerType._zod.run({value:Y,issues:[]},X))}}),Q9=K("$ZodLazy",($,T)=>{W$.init($,T),N$($._zod,"innerType",()=>T.getter()),N$($._zod,"pattern",()=>$._zod.innerType._zod.pattern),N$($._zod,"disc",()=>$._zod.innerType._zod.disc),N$($._zod,"optin",()=>$._zod.innerType._zod.optin),N$($._zod,"optout",()=>$._zod.innerType._zod.optout),$._zod.parse=(W,X)=>{return $._zod.innerType._zod.run(W,X)}}),Z9=K("$ZodCustom",($,T)=>{u$.init($,T),W$.init($,T),$._zod.parse=(W,X)=>{return W},$._zod.check=(W)=>{let X=W.value,Y=T.fn(X);if(Y instanceof Promise)return Y.then((U)=>q3(U,W,X,$));q3(Y,W,X,$);return}});function q3($,T,W,X){if(!$){let Y={code:"custom",input:W,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)Y.params=X._zod.def.params;T.issues.push(ZG(Y))}}var BW={};M1(BW,{zhTW:()=>r9,zhCN:()=>l9,vi:()=>o9,ur:()=>d9,ua:()=>p9,tr:()=>u9,th:()=>c9,ta:()=>m9,sl:()=>g9,ru:()=>h9,pt:()=>y9,pl:()=>f9,ota:()=>b9,no:()=>x9,ms:()=>j9,mk:()=>v9,ko:()=>C9,ja:()=>P9,it:()=>q9,id:()=>k9,hu:()=>I9,he:()=>R9,frCA:()=>B9,fr:()=>S9,fi:()=>L9,fa:()=>N9,es:()=>A9,en:()=>SW,de:()=>M9,cs:()=>E9,ca:()=>K9,be:()=>V9,az:()=>O9,ar:()=>D9});var sA={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function x3($){return sA[$]??null}var eA=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},$N={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},TN=($)=>{switch($.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${$.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${eA($.input)}`;case"invalid_value":if($.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${u($.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=x3($.origin);if(W)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${$.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${T} ${$.maximum.toString()} ${W.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${$.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${T} ${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=x3($.origin);if(W)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${$.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${T} ${$.minimum.toString()} ${W.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${$.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${T} ${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${$.prefix}"`;if(T.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${T.suffix}"`;if(T.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${T.includes}"`;if(T.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${T.pattern}`;return`${$N[T.format]??$.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${$.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${$.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${$.keys.length>1?"\u0629":""}: ${q($.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${$.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${$.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}};function D9(){return{localeError:TN}}var WN={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function b3($){return WN[$]??null}var XN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},YN={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},UN=($)=>{switch($.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${$.expected}, daxil olan ${XN($.input)}`;case"invalid_value":if($.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${u($.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=b3($.origin);if(W)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${$.origin??"d\u0259y\u0259r"} ${T}${$.maximum.toString()} ${W.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${$.origin??"d\u0259y\u0259r"} ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=b3($.origin);if(W)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${$.origin} ${T}${$.minimum.toString()} ${W.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${$.origin} ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${T.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(T.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${T.suffix}" il\u0259 bitm\u0259lidir`;if(T.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${T.includes}" daxil olmal\u0131d\u0131r`;if(T.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${T.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${YN[T.format]??$.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${$.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${$.keys.length>1?"lar":""}: ${q($.keys,", ")}`;case"invalid_key":return`${$.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${$.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}};function O9(){return{localeError:UN}}function f3($,T,W,X){let Y=Math.abs($),U=Y%10,G=Y%100;if(G>=11&&G<=19)return X;if(U===1)return T;if(U>=2&&U<=4)return W;return X}var GN={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function y3($){return GN[$]??null}var JN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray($))return"\u043C\u0430\u0441\u0456\u045E";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},wN={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},zN=($)=>{switch($.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${$.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${JN($.input)}`;case"invalid_value":if($.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${u($.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=y3($.origin);if(W){let X=Number($.maximum),Y=f3(X,W.unit.one,W.unit.few,W.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${$.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${W.verb} ${T}${$.maximum.toString()} ${Y}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${$.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=y3($.origin);if(W){let X=Number($.minimum),Y=f3(X,W.unit.one,W.unit.few,W.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${$.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${W.verb} ${T}${$.minimum.toString()} ${Y}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${$.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${T.prefix}"`;if(T.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${T.suffix}"`;if(T.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${T.includes}"`;if(T.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${T.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${wN[T.format]??$.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${$.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${$.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${q($.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${$.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${$.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}};function V9(){return{localeError:zN}}var _N={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function h3($){return _N[$]??null}var HN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},FN={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},QN=($)=>{switch($.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${$.expected}, s'ha rebut ${HN($.input)}`;case"invalid_value":if($.values.length===1)return`Valor inv\xE0lid: s'esperava ${u($.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${q($.values," o ")}`;case"too_big":{let T=$.inclusive?"com a m\xE0xim":"menys de",W=h3($.origin);if(W)return`Massa gran: s'esperava que ${$.origin??"el valor"} contingu\xE9s ${T} ${$.maximum.toString()} ${W.unit??"elements"}`;return`Massa gran: s'esperava que ${$.origin??"el valor"} fos ${T} ${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?"com a m\xEDnim":"m\xE9s de",W=h3($.origin);if(W)return`Massa petit: s'esperava que ${$.origin} contingu\xE9s ${T} ${$.minimum.toString()} ${W.unit}`;return`Massa petit: s'esperava que ${$.origin} fos ${T} ${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${T.prefix}"`;if(T.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${T.suffix}"`;if(T.format==="includes")return`Format inv\xE0lid: ha d'incloure "${T.includes}"`;if(T.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${T.pattern}`;return`Format inv\xE0lid per a ${FN[T.format]??$.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${$.divisor}`;case"unrecognized_keys":return`Clau${$.keys.length>1?"s":""} no reconeguda${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${$.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${$.origin}`;default:return"Entrada inv\xE0lida"}};function K9(){return{localeError:QN}}var ZN={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function g3($){return ZN[$]??null}var DN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray($))return"pole";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},ON={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},VN=($)=>{switch($.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${$.expected}, obdr\u017Eeno ${DN($.input)}`;case"invalid_value":if($.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${u($.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=g3($.origin);if(W)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${$.origin??"hodnota"} mus\xED m\xEDt ${T}${$.maximum.toString()} ${W.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${$.origin??"hodnota"} mus\xED b\xFDt ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=g3($.origin);if(W)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${$.origin??"hodnota"} mus\xED m\xEDt ${T}${$.minimum.toString()} ${W.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${$.origin??"hodnota"} mus\xED b\xFDt ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${T.prefix}"`;if(T.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${T.suffix}"`;if(T.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${T.includes}"`;if(T.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${T.pattern}`;return`Neplatn\xFD form\xE1t ${ON[T.format]??$.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${$.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${q($.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${$.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${$.origin}`;default:return"Neplatn\xFD vstup"}};function E9(){return{localeError:VN}}var KN={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function m3($){return KN[$]??null}var EN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"Zahl";case"object":{if(Array.isArray($))return"Array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},MN={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},AN=($)=>{switch($.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${$.expected}, erhalten ${EN($.input)}`;case"invalid_value":if($.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${u($.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=m3($.origin);if(W)return`Zu gro\xDF: erwartet, dass ${$.origin??"Wert"} ${T}${$.maximum.toString()} ${W.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${$.origin??"Wert"} ${T}${$.maximum.toString()} ist`}case"too_small":{let T=$.inclusive?">=":">",W=m3($.origin);if(W)return`Zu klein: erwartet, dass ${$.origin} ${T}${$.minimum.toString()} ${W.unit} hat`;return`Zu klein: erwartet, dass ${$.origin} ${T}${$.minimum.toString()} ist`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Ung\xFCltiger String: muss mit "${T.prefix}" beginnen`;if(T.format==="ends_with")return`Ung\xFCltiger String: muss mit "${T.suffix}" enden`;if(T.format==="includes")return`Ung\xFCltiger String: muss "${T.includes}" enthalten`;if(T.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${T.pattern} entsprechen`;return`Ung\xFCltig: ${MN[T.format]??$.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${$.divisor} sein`;case"unrecognized_keys":return`${$.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${q($.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${$.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${$.origin}`;default:return"Ung\xFCltige Eingabe"}};function M9(){return{localeError:AN}}var NN={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function c3($){return NN[$]??null}var LN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},SN={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},BN=($)=>{switch($.code){case"invalid_type":return`Invalid input: expected ${$.expected}, received ${LN($.input)}`;case"invalid_value":if($.values.length===1)return`Invalid input: expected ${u($.values[0])}`;return`Invalid option: expected one of ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=c3($.origin);if(W)return`Too big: expected ${$.origin??"value"} to have ${T}${$.maximum.toString()} ${W.unit??"elements"}`;return`Too big: expected ${$.origin??"value"} to be ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=c3($.origin);if(W)return`Too small: expected ${$.origin} to have ${T}${$.minimum.toString()} ${W.unit}`;return`Too small: expected ${$.origin} to be ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Invalid string: must start with "${T.prefix}"`;if(T.format==="ends_with")return`Invalid string: must end with "${T.suffix}"`;if(T.format==="includes")return`Invalid string: must include "${T.includes}"`;if(T.format==="regex")return`Invalid string: must match pattern ${T.pattern}`;return`Invalid ${SN[T.format]??$.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${$.divisor}`;case"unrecognized_keys":return`Unrecognized key${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`Invalid key in ${$.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${$.origin}`;default:return"Invalid input"}};function SW(){return{localeError:BN}}var RN={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function u3($){return RN[$]??null}var IN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"n\xFAmero";case"object":{if(Array.isArray($))return"arreglo";if($===null)return"nulo";if(Object.getPrototypeOf($)!==Object.prototype)return $.constructor.name}}return T},kN={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},qN=($)=>{switch($.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${$.expected}, recibido ${IN($.input)}`;case"invalid_value":if($.values.length===1)return`Entrada inv\xE1lida: se esperaba ${u($.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=u3($.origin);if(W)return`Demasiado grande: se esperaba que ${$.origin??"valor"} tuviera ${T}${$.maximum.toString()} ${W.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${$.origin??"valor"} fuera ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=u3($.origin);if(W)return`Demasiado peque\xF1o: se esperaba que ${$.origin} tuviera ${T}${$.minimum.toString()} ${W.unit}`;return`Demasiado peque\xF1o: se esperaba que ${$.origin} fuera ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${T.prefix}"`;if(T.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${T.suffix}"`;if(T.format==="includes")return`Cadena inv\xE1lida: debe incluir "${T.includes}"`;if(T.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${T.pattern}`;return`Inv\xE1lido ${kN[T.format]??$.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${$.divisor}`;case"unrecognized_keys":return`Llave${$.keys.length>1?"s":""} desconocida${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${$.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${$.origin}`;default:return"Entrada inv\xE1lida"}};function A9(){return{localeError:qN}}var PN={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function p3($){return PN[$]??null}var CN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray($))return"\u0622\u0631\u0627\u06CC\u0647";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},vN={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},jN=($)=>{switch($.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${$.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${CN($.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":if($.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${u($.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${q($.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let T=$.inclusive?"<=":"<",W=p3($.origin);if(W)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${$.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${T}${$.maximum.toString()} ${W.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${$.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${T}${$.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let T=$.inclusive?">=":">",W=p3($.origin);if(W)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${$.origin} \u0628\u0627\u06CC\u062F ${T}${$.minimum.toString()} ${W.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${$.origin} \u0628\u0627\u06CC\u062F ${T}${$.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${T.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(T.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${T.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(T.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${T.includes}" \u0628\u0627\u0634\u062F`;if(T.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${T.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${vN[T.format]??$.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${$.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${$.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${q($.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${$.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${$.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}};function N9(){return{localeError:jN}}var xN={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function d3($){return xN[$]??null}var bN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},fN={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},yN=($)=>{switch($.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${$.expected}, oli ${bN($.input)}`;case"invalid_value":if($.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${u($.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=d3($.origin);if(W)return`Liian suuri: ${W.subject} t\xE4ytyy olla ${T}${$.maximum.toString()} ${W.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=d3($.origin);if(W)return`Liian pieni: ${W.subject} t\xE4ytyy olla ${T}${$.minimum.toString()} ${W.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${T.prefix}"`;if(T.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${T.suffix}"`;if(T.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${T.includes}"`;if(T.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${T.pattern}`;return`Virheellinen ${fN[T.format]??$.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${$.divisor} monikerta`;case"unrecognized_keys":return`${$.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${q($.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}};function L9(){return{localeError:yN}}var hN={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function o3($){return hN[$]??null}var gN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"nombre";case"object":{if(Array.isArray($))return"tableau";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},mN={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},cN=($)=>{switch($.code){case"invalid_type":return`Entr\xE9e invalide : ${$.expected} attendu, ${gN($.input)} re\xE7u`;case"invalid_value":if($.values.length===1)return`Entr\xE9e invalide : ${u($.values[0])} attendu`;return`Option invalide : une valeur parmi ${q($.values,"|")} attendue`;case"too_big":{let T=$.inclusive?"<=":"<",W=o3($.origin);if(W)return`Trop grand : ${$.origin??"valeur"} doit ${W.verb} ${T}${$.maximum.toString()} ${W.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${$.origin??"valeur"} doit \xEAtre ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=o3($.origin);if(W)return`Trop petit : ${$.origin} doit ${W.verb} ${T}${$.minimum.toString()} ${W.unit}`;return`Trop petit : ${$.origin} doit \xEAtre ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${T.prefix}"`;if(T.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${T.suffix}"`;if(T.format==="includes")return`Cha\xEEne invalide : doit inclure "${T.includes}"`;if(T.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${T.pattern}`;return`${mN[T.format]??$.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${$.divisor}`;case"unrecognized_keys":return`Cl\xE9${$.keys.length>1?"s":""} non reconnue${$.keys.length>1?"s":""} : ${q($.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${$.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${$.origin}`;default:return"Entr\xE9e invalide"}};function S9(){return{localeError:cN}}var uN={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function l3($){return uN[$]??null}var pN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},dN={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},oN=($)=>{switch($.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${$.expected}, re\xE7u ${pN($.input)}`;case"invalid_value":if($.values.length===1)return`Entr\xE9e invalide : attendu ${u($.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"\u2264":"<",W=l3($.origin);if(W)return`Trop grand : attendu que ${$.origin??"la valeur"} ait ${T}${$.maximum.toString()} ${W.unit}`;return`Trop grand : attendu que ${$.origin??"la valeur"} soit ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?"\u2265":">",W=l3($.origin);if(W)return`Trop petit : attendu que ${$.origin} ait ${T}${$.minimum.toString()} ${W.unit}`;return`Trop petit : attendu que ${$.origin} soit ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${T.prefix}"`;if(T.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${T.suffix}"`;if(T.format==="includes")return`Cha\xEEne invalide : doit inclure "${T.includes}"`;if(T.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${T.pattern}`;return`${dN[T.format]??$.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${$.divisor}`;case"unrecognized_keys":return`Cl\xE9${$.keys.length>1?"s":""} non reconnue${$.keys.length>1?"s":""} : ${q($.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${$.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${$.origin}`;default:return"Entr\xE9e invalide"}};function B9(){return{localeError:oN}}var lN={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function r3($){return lN[$]??null}var rN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},iN={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"},nN=($)=>{switch($.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${$.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${rN($.input)}`;case"invalid_value":if($.values.length===1)return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${u($.values[0])}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=r3($.origin);if(W)return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${$.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${T}${$.maximum.toString()} ${W.unit??"elements"}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${$.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=r3($.origin);if(W)return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${$.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${T}${$.minimum.toString()} ${W.unit}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${$.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${T.prefix}"`;if(T.format==="ends_with")return`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${T.suffix}"`;if(T.format==="includes")return`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${T.includes}"`;if(T.format==="regex")return`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${T.pattern}`;return`${iN[T.format]??$.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${$.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${$.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${$.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${q($.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${$.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${$.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}};function R9(){return{localeError:nN}}var tN={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function i3($){return tN[$]??null}var aN=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"sz\xE1m";case"object":{if(Array.isArray($))return"t\xF6mb";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},sN={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},eN=($)=>{switch($.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${$.expected}, a kapott \xE9rt\xE9k ${aN($.input)}`;case"invalid_value":if($.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${u($.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=i3($.origin);if(W)return`T\xFAl nagy: ${$.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${T}${$.maximum.toString()} ${W.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${$.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=i3($.origin);if(W)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${$.origin} m\xE9rete t\xFAl kicsi ${T}${$.minimum.toString()} ${W.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${$.origin} t\xFAl kicsi ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\xC9rv\xE9nytelen string: "${T.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(T.format==="ends_with")return`\xC9rv\xE9nytelen string: "${T.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(T.format==="includes")return`\xC9rv\xE9nytelen string: "${T.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(T.format==="regex")return`\xC9rv\xE9nytelen string: ${T.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${sN[T.format]??$.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${$.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${$.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${$.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}};function I9(){return{localeError:eN}}var $L={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function n3($){return $L[$]??null}var TL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},WL={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},XL=($)=>{switch($.code){case"invalid_type":return`Input tidak valid: diharapkan ${$.expected}, diterima ${TL($.input)}`;case"invalid_value":if($.values.length===1)return`Input tidak valid: diharapkan ${u($.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=n3($.origin);if(W)return`Terlalu besar: diharapkan ${$.origin??"value"} memiliki ${T}${$.maximum.toString()} ${W.unit??"elemen"}`;return`Terlalu besar: diharapkan ${$.origin??"value"} menjadi ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=n3($.origin);if(W)return`Terlalu kecil: diharapkan ${$.origin} memiliki ${T}${$.minimum.toString()} ${W.unit}`;return`Terlalu kecil: diharapkan ${$.origin} menjadi ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`String tidak valid: harus dimulai dengan "${T.prefix}"`;if(T.format==="ends_with")return`String tidak valid: harus berakhir dengan "${T.suffix}"`;if(T.format==="includes")return`String tidak valid: harus menyertakan "${T.includes}"`;if(T.format==="regex")return`String tidak valid: harus sesuai pola ${T.pattern}`;return`${WL[T.format]??$.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${$.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${$.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${$.origin}`;default:return"Input tidak valid"}};function k9(){return{localeError:XL}}var YL={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t3($){return YL[$]??null}var UL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"numero";case"object":{if(Array.isArray($))return"vettore";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},GL={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},JL=($)=>{switch($.code){case"invalid_type":return`Input non valido: atteso ${$.expected}, ricevuto ${UL($.input)}`;case"invalid_value":if($.values.length===1)return`Input non valido: atteso ${u($.values[0])}`;return`Opzione non valida: atteso uno tra ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=t3($.origin);if(W)return`Troppo grande: ${$.origin??"valore"} deve avere ${T}${$.maximum.toString()} ${W.unit??"elementi"}`;return`Troppo grande: ${$.origin??"valore"} deve essere ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=t3($.origin);if(W)return`Troppo piccolo: ${$.origin} deve avere ${T}${$.minimum.toString()} ${W.unit}`;return`Troppo piccolo: ${$.origin} deve essere ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Stringa non valida: deve iniziare con "${T.prefix}"`;if(T.format==="ends_with")return`Stringa non valida: deve terminare con "${T.suffix}"`;if(T.format==="includes")return`Stringa non valida: deve includere "${T.includes}"`;if(T.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${T.pattern}`;return`Invalid ${GL[T.format]??$.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${$.divisor}`;case"unrecognized_keys":return`Chiav${$.keys.length>1?"i":"e"} non riconosciut${$.keys.length>1?"e":"a"}: ${q($.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${$.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${$.origin}`;default:return"Input non valido"}};function q9(){return{localeError:JL}}var wL={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function a3($){return wL[$]??null}var zL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray($))return"\u914D\u5217";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},_L={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},HL=($)=>{switch($.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${$.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${zL($.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":if($.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${u($.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${q($.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let T=$.inclusive?"<=":"<",W=a3($.origin);if(W)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${$.origin??"\u5024"}\u306F${$.maximum.toString()}${W.unit??"\u8981\u7D20"}${T}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${$.origin??"\u5024"}\u306F${$.maximum.toString()}${T}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let T=$.inclusive?">=":">",W=a3($.origin);if(W)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${$.origin}\u306F${$.minimum.toString()}${W.unit}${T}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${$.origin}\u306F${$.minimum.toString()}${T}\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${T.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(T.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${T.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(T.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${T.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(T.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${T.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${_L[T.format]??$.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${$.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${$.keys.length>1?"\u7FA4":""}: ${q($.keys,"\u3001")}`;case"invalid_key":return`${$.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${$.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}};function P9(){return{localeError:HL}}var FL={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function s3($){return FL[$]??null}var QL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},ZL={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},DL=($)=>{switch($.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${$.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${QL($.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":if($.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${u($.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${q($.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let T=$.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",W=T==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",X=s3($.origin),Y=X?.unit??"\uC694\uC18C";if(X)return`${$.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${$.maximum.toString()}${Y} ${T}${W}`;return`${$.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${$.maximum.toString()} ${T}${W}`}case"too_small":{let T=$.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",W=T==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",X=s3($.origin),Y=X?.unit??"\uC694\uC18C";if(X)return`${$.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${$.minimum.toString()}${Y} ${T}${W}`;return`${$.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${$.minimum.toString()} ${T}${W}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${T.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(T.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${T.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(T.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${T.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(T.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${T.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${ZL[T.format]??$.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${$.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${q($.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${$.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${$.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}};function C9(){return{localeError:DL}}var OL={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function e3($){return OL[$]??null}var VL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray($))return"\u043D\u0438\u0437\u0430";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},KL={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},EL=($)=>{switch($.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${$.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${VL($.input)}`;case"invalid_value":if($.values.length===1)return`Invalid input: expected ${u($.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=e3($.origin);if(W)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${$.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${T}${$.maximum.toString()} ${W.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${$.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=e3($.origin);if(W)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${$.origin} \u0434\u0430 \u0438\u043C\u0430 ${T}${$.minimum.toString()} ${W.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${$.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${T.prefix}"`;if(T.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${T.suffix}"`;if(T.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${T.includes}"`;if(T.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${T.pattern}`;return`Invalid ${KL[T.format]??$.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${$.divisor}`;case"unrecognized_keys":return`${$.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${q($.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${$.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${$.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}};function v9(){return{localeError:EL}}var ML={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function $H($){return ML[$]??null}var AL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"nombor";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},NL={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},LL=($)=>{switch($.code){case"invalid_type":return`Input tidak sah: dijangka ${$.expected}, diterima ${AL($.input)}`;case"invalid_value":if($.values.length===1)return`Input tidak sah: dijangka ${u($.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=$H($.origin);if(W)return`Terlalu besar: dijangka ${$.origin??"nilai"} ${W.verb} ${T}${$.maximum.toString()} ${W.unit??"elemen"}`;return`Terlalu besar: dijangka ${$.origin??"nilai"} adalah ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=$H($.origin);if(W)return`Terlalu kecil: dijangka ${$.origin} ${W.verb} ${T}${$.minimum.toString()} ${W.unit}`;return`Terlalu kecil: dijangka ${$.origin} adalah ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`String tidak sah: mesti bermula dengan "${T.prefix}"`;if(T.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${T.suffix}"`;if(T.format==="includes")return`String tidak sah: mesti mengandungi "${T.includes}"`;if(T.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${T.pattern}`;return`${NL[T.format]??$.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${$.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${q($.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${$.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${$.origin}`;default:return"Input tidak sah"}};function j9(){return{localeError:LL}}var SL={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function TH($){return SL[$]??null}var BL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"tall";case"object":{if(Array.isArray($))return"liste";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},RL={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},IL=($)=>{switch($.code){case"invalid_type":return`Ugyldig input: forventet ${$.expected}, fikk ${BL($.input)}`;case"invalid_value":if($.values.length===1)return`Ugyldig verdi: forventet ${u($.values[0])}`;return`Ugyldig valg: forventet en av ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=TH($.origin);if(W)return`For stor(t): forventet ${$.origin??"value"} til \xE5 ha ${T}${$.maximum.toString()} ${W.unit??"elementer"}`;return`For stor(t): forventet ${$.origin??"value"} til \xE5 ha ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=TH($.origin);if(W)return`For lite(n): forventet ${$.origin} til \xE5 ha ${T}${$.minimum.toString()} ${W.unit}`;return`For lite(n): forventet ${$.origin} til \xE5 ha ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${T.prefix}"`;if(T.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${T.suffix}"`;if(T.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${T.includes}"`;if(T.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${T.pattern}`;return`Ugyldig ${RL[T.format]??$.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${$.divisor}`;case"unrecognized_keys":return`${$.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${q($.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${$.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${$.origin}`;default:return"Ugyldig input"}};function x9(){return{localeError:IL}}var kL={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function WH($){return kL[$]??null}var qL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"numara";case"object":{if(Array.isArray($))return"saf";if($===null)return"gayb";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},PL={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},CL=($)=>{switch($.code){case"invalid_type":return`F\xE2sit giren: umulan ${$.expected}, al\u0131nan ${qL($.input)}`;case"invalid_value":if($.values.length===1)return`F\xE2sit giren: umulan ${u($.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=WH($.origin);if(W)return`Fazla b\xFCy\xFCk: ${$.origin??"value"}, ${T}${$.maximum.toString()} ${W.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${$.origin??"value"}, ${T}${$.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let T=$.inclusive?">=":">",W=WH($.origin);if(W)return`Fazla k\xFC\xE7\xFCk: ${$.origin}, ${T}${$.minimum.toString()} ${W.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${$.origin}, ${T}${$.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`F\xE2sit metin: "${T.prefix}" ile ba\u015Flamal\u0131.`;if(T.format==="ends_with")return`F\xE2sit metin: "${T.suffix}" ile bitmeli.`;if(T.format==="includes")return`F\xE2sit metin: "${T.includes}" ihtiv\xE2 etmeli.`;if(T.format==="regex")return`F\xE2sit metin: ${T.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${PL[T.format]??$.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${$.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`${$.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${$.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}};function b9(){return{localeError:CL}}var vL={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function XH($){return vL[$]??null}var jL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"liczba";case"object":{if(Array.isArray($))return"tablica";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},xL={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},bL=($)=>{switch($.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${$.expected}, otrzymano ${jL($.input)}`;case"invalid_value":if($.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${u($.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=XH($.origin);if(W)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${$.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${T}${$.maximum.toString()} ${W.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${$.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=XH($.origin);if(W)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${$.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${T}${$.minimum.toString()} ${W.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${$.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${T.prefix}"`;if(T.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${T.suffix}"`;if(T.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${T.includes}"`;if(T.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${T.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${xL[T.format]??$.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${$.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${$.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${$.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}};function f9(){return{localeError:bL}}var fL={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function YH($){return fL[$]??null}var yL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"n\xFAmero";case"object":{if(Array.isArray($))return"array";if($===null)return"nulo";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},hL={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},gL=($)=>{switch($.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${$.expected}, recebido ${yL($.input)}`;case"invalid_value":if($.values.length===1)return`Entrada inv\xE1lida: esperado ${u($.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=YH($.origin);if(W)return`Muito grande: esperado que ${$.origin??"valor"} tivesse ${T}${$.maximum.toString()} ${W.unit??"elementos"}`;return`Muito grande: esperado que ${$.origin??"valor"} fosse ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=YH($.origin);if(W)return`Muito pequeno: esperado que ${$.origin} tivesse ${T}${$.minimum.toString()} ${W.unit}`;return`Muito pequeno: esperado que ${$.origin} fosse ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${T.prefix}"`;if(T.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${T.suffix}"`;if(T.format==="includes")return`Texto inv\xE1lido: deve incluir "${T.includes}"`;if(T.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${T.pattern}`;return`${hL[T.format]??$.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${$.divisor}`;case"unrecognized_keys":return`Chave${$.keys.length>1?"s":""} desconhecida${$.keys.length>1?"s":""}: ${q($.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${$.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${$.origin}`;default:return"Campo inv\xE1lido"}};function y9(){return{localeError:gL}}function UH($,T,W,X){let Y=Math.abs($),U=Y%10,G=Y%100;if(G>=11&&G<=19)return X;if(U===1)return T;if(U>=2&&U<=4)return W;return X}var mL={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function GH($){return mL[$]??null}var cL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray($))return"\u043C\u0430\u0441\u0441\u0438\u0432";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},uL={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},pL=($)=>{switch($.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${$.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${cL($.input)}`;case"invalid_value":if($.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${u($.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=GH($.origin);if(W){let X=Number($.maximum),Y=UH(X,W.unit.one,W.unit.few,W.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${$.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${T}${$.maximum.toString()} ${Y}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${$.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=GH($.origin);if(W){let X=Number($.minimum),Y=UH(X,W.unit.one,W.unit.few,W.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${$.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${T}${$.minimum.toString()} ${Y}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${$.origin} \u0431\u0443\u0434\u0435\u0442 ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${T.prefix}"`;if(T.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${T.suffix}"`;if(T.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${T.includes}"`;if(T.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${T.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${uL[T.format]??$.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${$.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${$.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${$.keys.length>1?"\u0438":""}: ${q($.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${$.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${$.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}};function h9(){return{localeError:pL}}var dL={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function JH($){return dL[$]??null}var oL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray($))return"tabela";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},lL={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},rL=($)=>{switch($.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${$.expected}, prejeto ${oL($.input)}`;case"invalid_value":if($.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${u($.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=JH($.origin);if(W)return`Preveliko: pri\u010Dakovano, da bo ${$.origin??"vrednost"} imelo ${T}${$.maximum.toString()} ${W.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${$.origin??"vrednost"} ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=JH($.origin);if(W)return`Premajhno: pri\u010Dakovano, da bo ${$.origin} imelo ${T}${$.minimum.toString()} ${W.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${$.origin} ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${T.prefix}"`;if(T.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${T.suffix}"`;if(T.format==="includes")return`Neveljaven niz: mora vsebovati "${T.includes}"`;if(T.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${T.pattern}`;return`Neveljaven ${lL[T.format]??$.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${$.divisor}`;case"unrecognized_keys":return`Neprepoznan${$.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${q($.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${$.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${$.origin}`;default:return"Neveljaven vnos"}};function g9(){return{localeError:rL}}var iL={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function wH($){return iL[$]??null}var nL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray($))return"\u0B85\u0BA3\u0BBF";if($===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},tL={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},aL=($)=>{switch($.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${$.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${nL($.input)}`;case"invalid_value":if($.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${u($.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${q($.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let T=$.inclusive?"<=":"<",W=wH($.origin);if(W)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${$.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${T}${$.maximum.toString()} ${W.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${$.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${T}${$.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let T=$.inclusive?">=":">",W=wH($.origin);if(W)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${$.origin} ${T}${$.minimum.toString()} ${W.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${$.origin} ${T}${$.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${T.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(T.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${T.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(T.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${T.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(T.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${T.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${tL[T.format]??$.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${$.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${$.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${q($.keys,", ")}`;case"invalid_key":return`${$.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${$.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}};function m9(){return{localeError:aL}}var sL={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function zH($){return sL[$]??null}var eL=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray($))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if($===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},$S={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},TS=($)=>{switch($.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${$.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${eL($.input)}`;case"invalid_value":if($.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${u($.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",W=zH($.origin);if(W)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${$.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${T} ${$.maximum.toString()} ${W.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${$.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${T} ${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",W=zH($.origin);if(W)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${$.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${T} ${$.minimum.toString()} ${W.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${$.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${T} ${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${T.prefix}"`;if(T.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${T.suffix}"`;if(T.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${T.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(T.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${T.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${$S[T.format]??$.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${$.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${q($.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${$.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${$.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}};function c9(){return{localeError:TS}}var WS={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function _H($){return WS[$]??null}var XS=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},YS={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},US=($)=>{switch($.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${$.expected}, al\u0131nan ${XS($.input)}`;case"invalid_value":if($.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${u($.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=_H($.origin);if(W)return`\xC7ok b\xFCy\xFCk: beklenen ${$.origin??"de\u011Fer"} ${T}${$.maximum.toString()} ${W.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${$.origin??"de\u011Fer"} ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=_H($.origin);if(W)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${$.origin} ${T}${$.minimum.toString()} ${W.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${$.origin} ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Ge\xE7ersiz metin: "${T.prefix}" ile ba\u015Flamal\u0131`;if(T.format==="ends_with")return`Ge\xE7ersiz metin: "${T.suffix}" ile bitmeli`;if(T.format==="includes")return`Ge\xE7ersiz metin: "${T.includes}" i\xE7ermeli`;if(T.format==="regex")return`Ge\xE7ersiz metin: ${T.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${YS[T.format]??$.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${$.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${$.keys.length>1?"lar":""}: ${q($.keys,", ")}`;case"invalid_key":return`${$.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${$.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}};function u9(){return{localeError:US}}var GS={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function HH($){return GS[$]??null}var JS=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray($))return"\u043C\u0430\u0441\u0438\u0432";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},wS={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},zS=($)=>{switch($.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${$.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${JS($.input)}`;case"invalid_value":if($.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${u($.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=HH($.origin);if(W)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${$.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${W.verb} ${T}${$.maximum.toString()} ${W.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${$.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=HH($.origin);if(W)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${$.origin} ${W.verb} ${T}${$.minimum.toString()} ${W.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${$.origin} \u0431\u0443\u0434\u0435 ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${T.prefix}"`;if(T.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${T.suffix}"`;if(T.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${T.includes}"`;if(T.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${T.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${wS[T.format]??$.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${$.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${$.keys.length>1?"\u0456":""}: ${q($.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${$.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${$.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}};function p9(){return{localeError:zS}}var _S={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function FH($){return _S[$]??null}var HS=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray($))return"\u0622\u0631\u06D2";if($===null)return"\u0646\u0644";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},FS={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},QS=($)=>{switch($.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${$.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${HS($.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":if($.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${u($.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${q($.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let T=$.inclusive?"<=":"<",W=FH($.origin);if(W)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${$.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${T}${$.maximum.toString()} ${W.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${$.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${T}${$.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let T=$.inclusive?">=":">",W=FH($.origin);if(W)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${$.origin} \u06A9\u06D2 ${T}${$.minimum.toString()} ${W.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${$.origin} \u06A9\u0627 ${T}${$.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${T.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(T.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${T.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(T.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${T.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(T.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${T.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${FS[T.format]??$.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${$.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${$.keys.length>1?"\u0632":""}: ${q($.keys,"\u060C ")}`;case"invalid_key":return`${$.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${$.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}};function d9(){return{localeError:QS}}var ZS={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function QH($){return ZS[$]??null}var DS=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"s\u1ED1";case"object":{if(Array.isArray($))return"m\u1EA3ng";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},OS={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},VS=($)=>{switch($.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${$.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${DS($.input)}`;case"invalid_value":if($.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${u($.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=QH($.origin);if(W)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${$.origin??"gi\xE1 tr\u1ECB"} ${W.verb} ${T}${$.maximum.toString()} ${W.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${$.origin??"gi\xE1 tr\u1ECB"} ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=QH($.origin);if(W)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${$.origin} ${W.verb} ${T}${$.minimum.toString()} ${W.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${$.origin} ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${T.prefix}"`;if(T.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${T.suffix}"`;if(T.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${T.includes}"`;if(T.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${T.pattern}`;return`${OS[T.format]??$.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${$.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${q($.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${$.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${$.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}};function o9(){return{localeError:VS}}var KS={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function ZH($){return KS[$]??null}var ES=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray($))return"\u6570\u7EC4";if($===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},MS={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},AS=($)=>{switch($.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${$.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${ES($.input)}`;case"invalid_value":if($.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${u($.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=ZH($.origin);if(W)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${$.origin??"\u503C"} ${T}${$.maximum.toString()} ${W.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${$.origin??"\u503C"} ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=ZH($.origin);if(W)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${$.origin} ${T}${$.minimum.toString()} ${W.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${$.origin} ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${T.prefix}" \u5F00\u5934`;if(T.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${T.suffix}" \u7ED3\u5C3E`;if(T.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${T.includes}"`;if(T.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${T.pattern}`;return`\u65E0\u6548${MS[T.format]??$.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${$.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${q($.keys,", ")}`;case"invalid_key":return`${$.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${$.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}};function l9(){return{localeError:AS}}var NS={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function DH($){return NS[$]??null}var LS=($)=>{let T=typeof $;switch(T){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return T},SS={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},BS=($)=>{switch($.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${$.expected}\uFF0C\u4F46\u6536\u5230 ${LS($.input)}`;case"invalid_value":if($.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${u($.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${q($.values,"|")}`;case"too_big":{let T=$.inclusive?"<=":"<",W=DH($.origin);if(W)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${$.origin??"\u503C"} \u61C9\u70BA ${T}${$.maximum.toString()} ${W.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${$.origin??"\u503C"} \u61C9\u70BA ${T}${$.maximum.toString()}`}case"too_small":{let T=$.inclusive?">=":">",W=DH($.origin);if(W)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${$.origin} \u61C9\u70BA ${T}${$.minimum.toString()} ${W.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${$.origin} \u61C9\u70BA ${T}${$.minimum.toString()}`}case"invalid_format":{let T=$;if(T.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${T.prefix}" \u958B\u982D`;if(T.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${T.suffix}" \u7D50\u5C3E`;if(T.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${T.includes}"`;if(T.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${T.pattern}`;return`\u7121\u6548\u7684 ${SS[T.format]??$.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${$.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${$.keys.length>1?"\u5011":""}\uFF1A${q($.keys,"\u3001")}`;case"invalid_key":return`${$.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${$.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}};function r9(){return{localeError:BS}}var i9=Symbol("ZodOutput"),n9=Symbol("ZodInput");class RW{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...T){let W=T[0];if(this._map.set($,W),W&&typeof W==="object"&&"id"in W){if(this._idmap.has(W.id))throw new Error(`ID ${W.id} already exists in the registry`);this._idmap.set(W.id,$)}return this}remove($){return this._map.delete($),this}get($){let T=$._zod.parent;if(T){let W={...this.get(T)??{}};return delete W.id,{...W,...this._map.get($)}}return this._map.get($)}has($){return this._map.has($)}}function GY(){return new RW}var v6=GY();function t9($,T){return new $({type:"string",...j(T)})}function a9($,T){return new $({type:"string",coerce:!0,...j(T)})}function JY($,T){return new $({type:"string",format:"email",check:"string_format",abort:!1,...j(T)})}function IW($,T){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...j(T)})}function wY($,T){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...j(T)})}function zY($,T){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(T)})}function _Y($,T){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(T)})}function HY($,T){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(T)})}function FY($,T){return new $({type:"string",format:"url",check:"string_format",abort:!1,...j(T)})}function QY($,T){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...j(T)})}function ZY($,T){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(T)})}function DY($,T){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...j(T)})}function OY($,T){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(T)})}function VY($,T){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...j(T)})}function KY($,T){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...j(T)})}function EY($,T){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(T)})}function MY($,T){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(T)})}function AY($,T){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(T)})}function NY($,T){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(T)})}function LY($,T){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(T)})}function SY($,T){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...j(T)})}function BY($,T){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...j(T)})}function RY($,T){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...j(T)})}function IY($,T){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...j(T)})}function s9($,T){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(T)})}function e9($,T){return new $({type:"string",format:"date",check:"string_format",...j(T)})}function $w($,T){return new $({type:"string",format:"time",check:"string_format",precision:null,...j(T)})}function Tw($,T){return new $({type:"string",format:"duration",check:"string_format",...j(T)})}function Ww($,T){return new $({type:"number",checks:[],...j(T)})}function Xw($,T){return new $({type:"number",coerce:!0,checks:[],...j(T)})}function Yw($,T){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...j(T)})}function Uw($,T){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...j(T)})}function Gw($,T){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...j(T)})}function Jw($,T){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...j(T)})}function ww($,T){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...j(T)})}function zw($,T){return new $({type:"boolean",...j(T)})}function _w($,T){return new $({type:"boolean",coerce:!0,...j(T)})}function Hw($,T){return new $({type:"bigint",...j(T)})}function Fw($,T){return new $({type:"bigint",coerce:!0,...j(T)})}function Qw($,T){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...j(T)})}function Zw($,T){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...j(T)})}function Dw($,T){return new $({type:"symbol",...j(T)})}function Ow($,T){return new $({type:"undefined",...j(T)})}function Vw($,T){return new $({type:"null",...j(T)})}function Kw($){return new $({type:"any"})}function Ew($){return new $({type:"unknown"})}function Mw($,T){return new $({type:"never",...j(T)})}function Aw($,T){return new $({type:"void",...j(T)})}function Nw($,T){return new $({type:"date",...j(T)})}function Lw($,T){return new $({type:"date",coerce:!0,...j(T)})}function Sw($,T){return new $({type:"nan",...j(T)})}function p6($,T){return new sX({check:"less_than",...j(T),value:$,inclusive:!1})}function U6($,T){return new sX({check:"less_than",...j(T),value:$,inclusive:!0})}function d6($,T){return new eX({check:"greater_than",...j(T),value:$,inclusive:!1})}function b4($,T){return new eX({check:"greater_than",...j(T),value:$,inclusive:!0})}function Bw($){return d6(0,$)}function Rw($){return p6(0,$)}function Iw($){return U6(0,$)}function kw($){return b4(0,$)}function $0($,T){return new lG({check:"multiple_of",...j(T),value:$})}function r0($,T){return new nG({check:"max_size",...j(T),maximum:$})}function T0($,T){return new tG({check:"min_size",...j(T),minimum:$})}function kW($,T){return new aG({check:"size_equals",...j(T),size:$})}function i0($,T){return new sG({check:"max_length",...j(T),maximum:$})}function I1($,T){return new eG({check:"min_length",...j(T),minimum:$})}function n0($,T){return new $J({check:"length_equals",...j(T),length:$})}function qW($,T){return new TJ({check:"string_format",format:"regex",...j(T),pattern:$})}function PW($){return new WJ({check:"string_format",format:"lowercase",...j($)})}function CW($){return new XJ({check:"string_format",format:"uppercase",...j($)})}function vW($,T){return new YJ({check:"string_format",format:"includes",...j(T),includes:$})}function jW($,T){return new UJ({check:"string_format",format:"starts_with",...j(T),prefix:$})}function xW($,T){return new GJ({check:"string_format",format:"ends_with",...j(T),suffix:$})}function qw($,T,W){return new JJ({check:"property",property:$,schema:T,...j(W)})}function bW($,T){return new wJ({check:"mime_type",mime:$,...j(T)})}function o6($){return new zJ({check:"overwrite",tx:$})}function fW($){return o6((T)=>T.normalize($))}function yW(){return o6(($)=>$.trim())}function hW(){return o6(($)=>$.toLowerCase())}function gW(){return o6(($)=>$.toUpperCase())}function Pw($,T,W){return new $({type:"array",element:T,...j(W)})}function RS($,T,W){return new $({type:"union",options:T,...j(W)})}function IS($,T,W,X){return new $({type:"union",options:W,discriminator:T,...j(X)})}function kS($,T,W){return new $({type:"intersection",left:T,right:W})}function Cw($,T,W,X){let Y=W instanceof W$;return new $({type:"tuple",items:T,rest:Y?W:null,...j(Y?X:W)})}function qS($,T,W,X){return new $({type:"record",keyType:T,valueType:W,...j(X)})}function PS($,T,W,X){return new $({type:"map",keyType:T,valueType:W,...j(X)})}function CS($,T,W){return new $({type:"set",valueType:T,...j(W)})}function vS($,T,W){let X=Array.isArray(T)?Object.fromEntries(T.map((Y)=>[Y,Y])):T;return new $({type:"enum",entries:X,...j(W)})}function jS($,T,W){return new $({type:"enum",entries:T,...j(W)})}function xS($,T,W){return new $({type:"literal",values:Array.isArray(T)?T:[T],...j(W)})}function vw($,T){return new $({type:"file",...j(T)})}function bS($,T){return new $({type:"transform",transform:T})}function fS($,T){return new $({type:"optional",innerType:T})}function yS($,T){return new $({type:"nullable",innerType:T})}function hS($,T,W){return new $({type:"default",innerType:T,get defaultValue(){return typeof W==="function"?W():W}})}function gS($,T,W){return new $({type:"nonoptional",innerType:T,...j(W)})}function mS($,T){return new $({type:"success",innerType:T})}function cS($,T,W){return new $({type:"catch",innerType:T,catchValue:typeof W==="function"?W:()=>W})}function uS($,T,W){return new $({type:"pipe",in:T,out:W})}function pS($,T){return new $({type:"readonly",innerType:T})}function dS($,T,W){return new $({type:"template_literal",parts:T,...j(W)})}function oS($,T){return new $({type:"lazy",getter:T})}function lS($,T){return new $({type:"promise",innerType:T})}function mW($,T,W){return new $({type:"custom",check:"custom",fn:T,...j(W)})}function rS($,T,W={}){return mW($,T,W)}function jw($,T){let W=j(T),X=new Set(W?.truthy??["true","1","yes","on","y","enabled"]),Y=new Set(W?.falsy??["false","0","no","off","n","disabled"]),U=$.Pipe??LW,G=$.Boolean??AW,z=new($.Unknown??NW)({type:"unknown",checks:[{_zod:{check:(w)=>{if(typeof w.value==="string"){let H=w.value;if(W?.case!=="sensitive")H=H.toLowerCase();if(X.has(H))w.value=!0;else if(Y.has(H))w.value=!1;else w.issues.push({code:"invalid_value",expected:"stringbool",values:[...X,...Y],input:w.value,inst:z})}else w.issues.push({code:"invalid_type",expected:"string",input:w.value})},def:{check:"custom"},onattach:[]}}]});return new U({type:"pipe",in:z,out:new G({type:"boolean"})})}class t0{constructor($){this._def=$,this.def=$}implement($){if(typeof $!=="function")throw new Error("implement() must be called with a function");let T=(...W)=>{let X=this._def.input?dX(this._def.input,W,void 0,{callee:T}):W;if(!Array.isArray(X))throw new Error("Invalid arguments schema: not an array or tuple schema.");let Y=$(...X);return this._def.output?dX(this._def.output,Y,void 0,{callee:T}):Y};return T}implementAsync($){if(typeof $!=="function")throw new Error("implement() must be called with a function");let T=async(...W)=>{let X=this._def.input?await lX(this._def.input,W,void 0,{callee:T}):W;if(!Array.isArray(X))throw new Error("Invalid arguments schema: not an array or tuple schema.");let Y=await $(...X);return this._def.output?lX(this._def.output,Y,void 0,{callee:T}):Y};return T}input(...$){if(Array.isArray($[0]))return new t0({type:"function",input:new e1({type:"tuple",items:$[0],rest:$[1]}),output:this._def.output});return new t0({type:"function",input:$[0],output:this._def.output})}output($){return new t0({type:"function",input:this._def.input,output:$})}}function xw($){return new t0({type:"function",input:Array.isArray($?.input)?Cw(e1,$?.input):$?.input??null,output:$?.output??null})}var iS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string"};class kY{constructor($){this.counter=0,this.metadataRegistry=$?.metadata??v6,this.target=$?.target??"draft-2020-12",this.unrepresentable=$?.unrepresentable??"throw",this.override=$?.override??(()=>{}),this.io=$?.io??"output",this.seen=new Map}process($,T={path:[],schemaPath:[]}){var W;let X=$._zod.def,Y=this.seen.get($);if(Y){if(Y.count++,T.schemaPath.includes($))Y.cycle=T.path;return Y.count++,Y.schema}let U={schema:{},count:1,cycle:void 0};if(this.seen.set($,U),$._zod.toJSONSchema)U.schema=$._zod.toJSONSchema();let G={...T,schemaPath:[...T.schemaPath,$],path:T.path},J=$._zod.parent;if(J)U.ref=J,this.process(J,G),this.seen.get(J).isParent=!0;else{let H=U.schema;switch(X.type){case"string":{let _=H;_.type="string";let{minimum:F,maximum:D,format:V,pattern:E,contentEncoding:R}=$._zod.bag;if(typeof F==="number")_.minLength=F;if(typeof D==="number")_.maxLength=D;if(V)_.format=iS[V]??V;if(E)_.pattern=E.source;if(R)_.contentEncoding=R;break}case"number":{let _=H,{minimum:F,maximum:D,format:V,multipleOf:E,exclusiveMaximum:R,exclusiveMinimum:P}=$._zod.bag;if(typeof V==="string"&&V.includes("int"))_.type="integer";else _.type="number";if(typeof P==="number")_.exclusiveMinimum=P;if(typeof F==="number"){if(_.minimum=F,typeof P==="number")if(P>=F)delete _.minimum;else delete _.exclusiveMinimum}if(typeof R==="number")_.exclusiveMaximum=R;if(typeof D==="number"){if(_.maximum=D,typeof R==="number")if(R<=D)delete _.maximum;else delete _.exclusiveMaximum}if(typeof E==="number")_.multipleOf=E;break}case"boolean":{let _=H;_.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"undefined":{let _=H;_.type="null";break}case"null":{H.type="null";break}case"any":break;case"unknown":break;case"never":{H.not={};break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let _=H,{minimum:F,maximum:D}=$._zod.bag;if(typeof F==="number")_.minItems=F;if(typeof D==="number")_.maxItems=D;_.type="array",_.items=this.process(X.element,{...G,path:[...G.path,"items"]});break}case"object":{let _=H;_.type="object",_.properties={};let F=X.shape;for(let E in F)_.properties[E]=this.process(F[E],{...G,path:[...G.path,"properties",E]});let D=new Set(Object.keys(F)),V=new Set([...D].filter((E)=>{let R=X.shape[E]._zod;if(this.io==="input")return R.optin===void 0;else return R.optout===void 0}));if(_.required=Array.from(V),X.catchall?._zod.def.type==="never")_.additionalProperties=!1;else if(!X.catchall){if(this.io==="output")_.additionalProperties=!1}else if(X.catchall)_.additionalProperties=this.process(X.catchall,{...G,path:[...G.path,"additionalProperties"]});break}case"union":{let _=H;_.anyOf=X.options.map((F,D)=>this.process(F,{...G,path:[...G.path,"anyOf",D]}));break}case"intersection":{let _=H;_.allOf=[this.process(X.left,{...G,path:[...G.path,"allOf",0]}),this.process(X.right,{...G,path:[...G.path,"allOf",1]})];break}case"tuple":{let _=H;_.type="array";let F=X.items.map((E,R)=>this.process(E,{...G,path:[...G.path,"prefixItems",R]}));if(this.target==="draft-2020-12")_.prefixItems=F;else _.items=F;if(X.rest){let E=this.process(X.rest,{...G,path:[...G.path,"items"]});if(this.target==="draft-2020-12")_.items=E;else _.additionalItems=E}if(X.rest)_.items=this.process(X.rest,{...G,path:[...G.path,"items"]});let{minimum:D,maximum:V}=$._zod.bag;if(typeof D==="number")_.minItems=D;if(typeof V==="number")_.maxItems=V;break}case"record":{let _=H;_.type="object",_.propertyNames=this.process(X.keyType,{...G,path:[...G.path,"propertyNames"]}),_.additionalProperties=this.process(X.valueType,{...G,path:[...G.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let _=H;_.enum=Object.values(X.entries);break}case"literal":{let _=H,F=[];for(let D of X.values)if(D===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof D==="bigint")if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");else F.push(Number(D));else F.push(D);if(F.length===0);else if(F.length===1){let D=F[0];_.const=D}else _.enum=F;break}case"file":{if(this.unrepresentable==="throw")throw new Error("File cannot be represented in JSON Schema");break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let _=this.process(X.innerType,G);H.anyOf=[_,{type:"null"}];break}case"nonoptional":{this.process(X.innerType,G),U.ref=X.innerType;break}case"success":{let _=H;_.type="boolean";break}case"default":{this.process(X.innerType,G),U.ref=X.innerType,H.default=X.defaultValue;break}case"prefault":{if(this.process(X.innerType,G),U.ref=X.innerType,this.io==="input")H._prefault=X.defaultValue;break}case"catch":{this.process(X.innerType,G),U.ref=X.innerType;let _;try{_=X.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}H.default=_;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let _=H,F=$._zod.pattern;if(!F)throw new Error("Pattern not found in template literal");_.type="string",_.pattern=F.source;break}case"pipe":{let _=this.io==="input"?X.in:X.out;this.process(_,G),U.ref=_;break}case"readonly":{this.process(X.innerType,G),U.ref=X.innerType,H.readOnly=!0;break}case"promise":{this.process(X.innerType,G),U.ref=X.innerType;break}case"optional":{this.process(X.innerType,G),U.ref=X.innerType;break}case"lazy":{let _=$._zod.innerType;this.process(_,G),U.ref=_;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}let z=this.metadataRegistry.get($);if(z)Object.assign(U.schema,z);if(this.io==="input"&&X.type==="pipe"){if(delete U.schema.examples,delete U.schema.default,U.schema._prefault)U.schema.default=U.schema._prefault}if(this.io==="input"&&U.schema._prefault)(W=U.schema).default??(W.default=U.schema._prefault);return delete U.schema._prefault,this.seen.get($).schema}emit($,T){let W={cycles:T?.cycles??"ref",reused:T?.reused??"inline",external:T?.external??void 0},X=this.seen.get($);if(!X)throw new Error("Unprocessed schema. This is a bug in Zod.");let Y=(w)=>{let H=this.target==="draft-2020-12"?"$defs":"definitions";if(W.external){let V=W.external.registry.get(w[0])?.id;if(V)return{ref:W.external.uri(V)};let E=w[1].defId??w[1].schema.id??`schema${this.counter++}`;return w[1].defId=E,{defId:E,ref:`${W.external.uri("__shared")}#/${H}/${E}`}}if(w[1]===X)return{ref:"#"};let F=`${"#"}/${H}/`,D=w[1].schema.id??`__schema${this.counter++}`;return{defId:D,ref:F+D}},U=(w)=>{if(w[1].schema.$ref)return;let H=w[1],{ref:_,defId:F}=Y(w);if(H.def={...H.schema},F)H.defId=F;let D=H.schema;for(let V in D)delete D[V],D.$ref=_};for(let w of this.seen.entries()){let H=w[1];if($===w[0]){U(w);continue}if(W.external){let F=W.external.registry.get(w[0])?.id;if($!==w[0]&&F){U(w);continue}}if(this.metadataRegistry.get(w[0])?.id){U(w);continue}if(H.cycle){if(W.cycles==="throw")throw new Error(`Cycle detected: #/${H.cycle?.join("/")}/<root>
|
|
32
|
+
|
|
33
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);else if(W.cycles==="ref")U(w);continue}if(H.count>1){if(W.reused==="ref"){U(w);continue}}}let G=(w,H)=>{let _=this.seen.get(w),F=_.def??_.schema,D={...F};if(_.ref===null)return;let V=_.ref;if(_.ref=null,V){G(V,H);let E=this.seen.get(V).schema;if(E.$ref&&H.target==="draft-7")F.allOf=F.allOf??[],F.allOf.push(E);else Object.assign(F,E),Object.assign(F,D)}if(!_.isParent)this.override({zodSchema:w,jsonSchema:F})};for(let w of[...this.seen.entries()].reverse())G(w[0],{target:this.target});let J={...X.def},z=W.external?.defs??{};for(let w of this.seen.entries()){let H=w[1];if(H.def&&H.defId)z[H.defId]=H.def}if(!W.external&&Object.keys(z).length>0)if(this.target==="draft-2020-12")J.$defs=z;else J.definitions=z;if(this.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")J.$schema="http://json-schema.org/draft-07/schema#";else console.warn(`Invalid target: ${this.target}`);try{return JSON.parse(JSON.stringify(J))}catch(w){throw new Error("Error converting schema to JSON.")}}}function bw($,T){if($ instanceof RW){let X=new kY(T),Y={};for(let J of $._idmap.entries()){let[z,w]=J;X.process(w)}let U={},G={registry:$,uri:T?.uri||((J)=>J),defs:Y};for(let J of $._idmap.entries()){let[z,w]=J;U[z]=X.emit(w,{...T,external:G})}if(Object.keys(Y).length>0){let J=X.target==="draft-2020-12"?"$defs":"definitions";U.__shared={[J]:Y}}return{schemas:U}}let W=new kY(T);return W.process($),W.emit($,T)}var OH={};var qY={};M1(qY,{time:()=>hw,duration:()=>gw,datetime:()=>fw,date:()=>yw,ZodISOTime:()=>EH,ZodISODuration:()=>MH,ZodISODateTime:()=>VH,ZodISODate:()=>KH});var VH=K("ZodISODateTime",($,T)=>{LJ.init($,T),f$.init($,T)});function fw($){return s9(VH,$)}var KH=K("ZodISODate",($,T)=>{SJ.init($,T),f$.init($,T)});function yw($){return e9(KH,$)}var EH=K("ZodISOTime",($,T)=>{BJ.init($,T),f$.init($,T)});function hw($){return $w(EH,$)}var MH=K("ZodISODuration",($,T)=>{RJ.init($,T),f$.init($,T)});function gw($){return Tw(MH,$)}var NH=($,T)=>{VW.init($,T),$.name="ZodError",Object.defineProperties($,{format:{value:(W)=>EW($,W)},flatten:{value:(W)=>KW($,W)},addIssue:{value:(W)=>$.issues.push(W)},addIssues:{value:(W)=>$.issues.push(...W)},isEmpty:{get(){return $.issues.length===0}}})},tS=K("ZodError",NH),a0=K("ZodError",NH,{Parent:Error});var mw=pX(a0),cw=oX(a0),uw=rX(a0),pw=iX(a0);var dw={};M1(dw,{string:()=>sS,number:()=>eS,date:()=>WB,boolean:()=>$B,bigint:()=>TB});function sS($){return a9(PY,$)}function eS($){return Xw(cW,$)}function $B($){return _w(uW,$)}function TB($){return Fw(pW,$)}function WB($){return Lw(CY,$)}var z$=K("ZodType",($,T)=>{return W$.init($,T),$.def=T,Object.defineProperty($,"_def",{value:T}),$.check=(...W)=>{return $.clone({...T,checks:[...T.checks??[],...W.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]})},$.clone=(W,X)=>i4($,W,X),$.brand=()=>$,$.register=(W,X)=>{return W.add($,X),$},$.parse=(W,X)=>mw($,W,X,{callee:$.parse}),$.safeParse=(W,X)=>uw($,W,X),$.parseAsync=async(W,X)=>cw($,W,X,{callee:$.parseAsync}),$.safeParseAsync=async(W,X)=>pw($,W,X),$.spa=$.safeParseAsync,$.refine=(W,X)=>$.check(wF(W,X)),$.superRefine=(W)=>$.check(zF(W)),$.overwrite=(W)=>$.check(o6(W)),$.optional=()=>xY($),$.nullable=()=>bY($),$.nullish=()=>xY(bY($)),$.nonoptional=(W)=>tH($,W),$.array=()=>Qz($),$.or=(W)=>gY([$,W]),$.and=(W)=>bH($,W),$.transform=(W)=>fY($,Oz(W)),$.default=(W)=>rH($,W),$.prefault=(W)=>nH($,W),$.catch=(W)=>eH($,W),$.pipe=(W)=>fY($,W),$.readonly=()=>WF($),$.describe=(W)=>{let X=$.clone();return v6.add(X,{description:W}),X},Object.defineProperty($,"description",{get(){return v6.get($)?.description},configurable:!0}),$.meta=(...W)=>{if(W.length===0)return v6.get($);let X=$.clone();return v6.add(X,W[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),rw=K("_ZodString",($,T)=>{MW.init($,T),z$.init($,T);let W=$._zod.bag;$.format=W.format??null,$.minLength=W.minimum??null,$.maxLength=W.maximum??null,$.regex=(...X)=>$.check(qW(...X)),$.includes=(...X)=>$.check(vW(...X)),$.startsWith=(...X)=>$.check(jW(...X)),$.endsWith=(...X)=>$.check(xW(...X)),$.min=(...X)=>$.check(I1(...X)),$.max=(...X)=>$.check(i0(...X)),$.length=(...X)=>$.check(n0(...X)),$.nonempty=(...X)=>$.check(I1(1,...X)),$.lowercase=(X)=>$.check(PW(X)),$.uppercase=(X)=>$.check(CW(X)),$.trim=()=>$.check(yW()),$.normalize=(...X)=>$.check(fW(...X)),$.toLowerCase=()=>$.check(hW()),$.toUpperCase=()=>$.check(gW())}),PY=K("ZodString",($,T)=>{MW.init($,T),rw.init($,T),$.email=(W)=>$.check(JY(iw,W)),$.url=(W)=>$.check(FY(nw,W)),$.jwt=(W)=>$.check(IY(_z,W)),$.emoji=(W)=>$.check(QY(tw,W)),$.guid=(W)=>$.check(IW(vY,W)),$.uuid=(W)=>$.check(wY(r6,W)),$.uuidv4=(W)=>$.check(zY(r6,W)),$.uuidv6=(W)=>$.check(_Y(r6,W)),$.uuidv7=(W)=>$.check(HY(r6,W)),$.nanoid=(W)=>$.check(ZY(aw,W)),$.guid=(W)=>$.check(IW(vY,W)),$.cuid=(W)=>$.check(DY(sw,W)),$.cuid2=(W)=>$.check(OY(ew,W)),$.ulid=(W)=>$.check(VY($z,W)),$.base64=(W)=>$.check(SY(Jz,W)),$.base64url=(W)=>$.check(BY(wz,W)),$.xid=(W)=>$.check(KY(Tz,W)),$.ksuid=(W)=>$.check(EY(Wz,W)),$.ipv4=(W)=>$.check(MY(Xz,W)),$.ipv6=(W)=>$.check(AY(Yz,W)),$.cidrv4=(W)=>$.check(NY(Uz,W)),$.cidrv6=(W)=>$.check(LY(Gz,W)),$.e164=(W)=>$.check(RY(zz,W)),$.datetime=(W)=>$.check(fw(W)),$.date=(W)=>$.check(yw(W)),$.time=(W)=>$.check(hw(W)),$.duration=(W)=>$.check(gw(W))});function ow($){return t9(PY,$)}var f$=K("ZodStringFormat",($,T)=>{q$.init($,T),rw.init($,T)}),iw=K("ZodEmail",($,T)=>{ZJ.init($,T),f$.init($,T)});function XB($){return JY(iw,$)}var vY=K("ZodGUID",($,T)=>{FJ.init($,T),f$.init($,T)});function YB($){return IW(vY,$)}var r6=K("ZodUUID",($,T)=>{QJ.init($,T),f$.init($,T)});function UB($){return wY(r6,$)}function GB($){return zY(r6,$)}function JB($){return _Y(r6,$)}function wB($){return HY(r6,$)}var nw=K("ZodURL",($,T)=>{DJ.init($,T),f$.init($,T)});function zB($){return FY(nw,$)}var tw=K("ZodEmoji",($,T)=>{OJ.init($,T),f$.init($,T)});function _B($){return QY(tw,$)}var aw=K("ZodNanoID",($,T)=>{VJ.init($,T),f$.init($,T)});function HB($){return ZY(aw,$)}var sw=K("ZodCUID",($,T)=>{KJ.init($,T),f$.init($,T)});function FB($){return DY(sw,$)}var ew=K("ZodCUID2",($,T)=>{EJ.init($,T),f$.init($,T)});function QB($){return OY(ew,$)}var $z=K("ZodULID",($,T)=>{MJ.init($,T),f$.init($,T)});function ZB($){return VY($z,$)}var Tz=K("ZodXID",($,T)=>{AJ.init($,T),f$.init($,T)});function DB($){return KY(Tz,$)}var Wz=K("ZodKSUID",($,T)=>{NJ.init($,T),f$.init($,T)});function OB($){return EY(Wz,$)}var Xz=K("ZodIPv4",($,T)=>{IJ.init($,T),f$.init($,T)});function VB($){return MY(Xz,$)}var Yz=K("ZodIPv6",($,T)=>{kJ.init($,T),f$.init($,T)});function KB($){return AY(Yz,$)}var Uz=K("ZodCIDRv4",($,T)=>{qJ.init($,T),f$.init($,T)});function EB($){return NY(Uz,$)}var Gz=K("ZodCIDRv6",($,T)=>{PJ.init($,T),f$.init($,T)});function MB($){return LY(Gz,$)}var Jz=K("ZodBase64",($,T)=>{vJ.init($,T),f$.init($,T)});function AB($){return SY(Jz,$)}var wz=K("ZodBase64URL",($,T)=>{jJ.init($,T),f$.init($,T)});function NB($){return BY(wz,$)}var zz=K("ZodE164",($,T)=>{xJ.init($,T),f$.init($,T)});function LB($){return RY(zz,$)}var _z=K("ZodJWT",($,T)=>{bJ.init($,T),f$.init($,T)});function SB($){return IY(_z,$)}var cW=K("ZodNumber",($,T)=>{XY.init($,T),z$.init($,T),$.gt=(X,Y)=>$.check(d6(X,Y)),$.gte=(X,Y)=>$.check(b4(X,Y)),$.min=(X,Y)=>$.check(b4(X,Y)),$.lt=(X,Y)=>$.check(p6(X,Y)),$.lte=(X,Y)=>$.check(U6(X,Y)),$.max=(X,Y)=>$.check(U6(X,Y)),$.int=(X)=>$.check(lw(X)),$.safe=(X)=>$.check(lw(X)),$.positive=(X)=>$.check(d6(0,X)),$.nonnegative=(X)=>$.check(b4(0,X)),$.negative=(X)=>$.check(p6(0,X)),$.nonpositive=(X)=>$.check(U6(0,X)),$.multipleOf=(X,Y)=>$.check($0(X,Y)),$.step=(X,Y)=>$.check($0(X,Y)),$.finite=()=>$;let W=$._zod.bag;$.minValue=Math.max(W.minimum??Number.NEGATIVE_INFINITY,W.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(W.maximum??Number.POSITIVE_INFINITY,W.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(W.format??"").includes("int")||Number.isSafeInteger(W.multipleOf??0.5),$.isFinite=!0,$.format=W.format??null});function LH($){return Ww(cW,$)}var s0=K("ZodNumberFormat",($,T)=>{fJ.init($,T),cW.init($,T)});function lw($){return Yw(s0,$)}function BB($){return Uw(s0,$)}function RB($){return Gw(s0,$)}function IB($){return Jw(s0,$)}function kB($){return ww(s0,$)}var uW=K("ZodBoolean",($,T)=>{AW.init($,T),z$.init($,T)});function SH($){return zw(uW,$)}var pW=K("ZodBigInt",($,T)=>{YY.init($,T),z$.init($,T),$.gte=(X,Y)=>$.check(b4(X,Y)),$.min=(X,Y)=>$.check(b4(X,Y)),$.gt=(X,Y)=>$.check(d6(X,Y)),$.gte=(X,Y)=>$.check(b4(X,Y)),$.min=(X,Y)=>$.check(b4(X,Y)),$.lt=(X,Y)=>$.check(p6(X,Y)),$.lte=(X,Y)=>$.check(U6(X,Y)),$.max=(X,Y)=>$.check(U6(X,Y)),$.positive=(X)=>$.check(d6(BigInt(0),X)),$.negative=(X)=>$.check(p6(BigInt(0),X)),$.nonpositive=(X)=>$.check(U6(BigInt(0),X)),$.nonnegative=(X)=>$.check(b4(BigInt(0),X)),$.multipleOf=(X,Y)=>$.check($0(X,Y));let W=$._zod.bag;$.minValue=W.minimum??null,$.maxValue=W.maximum??null,$.format=W.format??null});function qB($){return Hw(pW,$)}var Hz=K("ZodBigIntFormat",($,T)=>{yJ.init($,T),pW.init($,T)});function PB($){return Qw(Hz,$)}function CB($){return Zw(Hz,$)}var BH=K("ZodSymbol",($,T)=>{hJ.init($,T),z$.init($,T)});function vB($){return Dw(BH,$)}var RH=K("ZodUndefined",($,T)=>{gJ.init($,T),z$.init($,T)});function jB($){return Ow(RH,$)}var IH=K("ZodNull",($,T)=>{mJ.init($,T),z$.init($,T)});function kH($){return Vw(IH,$)}var qH=K("ZodAny",($,T)=>{cJ.init($,T),z$.init($,T)});function xB(){return Kw(qH)}var Fz=K("ZodUnknown",($,T)=>{NW.init($,T),z$.init($,T)});function jY(){return Ew(Fz)}var PH=K("ZodNever",($,T)=>{uJ.init($,T),z$.init($,T)});function yY($){return Mw(PH,$)}var CH=K("ZodVoid",($,T)=>{pJ.init($,T),z$.init($,T)});function bB($){return Aw(CH,$)}var CY=K("ZodDate",($,T)=>{dJ.init($,T),z$.init($,T),$.min=(X,Y)=>$.check(b4(X,Y)),$.max=(X,Y)=>$.check(U6(X,Y));let W=$._zod.bag;$.minDate=W.minimum?new Date(W.minimum):null,$.maxDate=W.maximum?new Date(W.maximum):null});function fB($){return Nw(CY,$)}var vH=K("ZodArray",($,T)=>{oJ.init($,T),z$.init($,T),$.element=T.element,$.min=(W,X)=>$.check(I1(W,X)),$.nonempty=(W)=>$.check(I1(1,W)),$.max=(W,X)=>$.check(i0(W,X)),$.length=(W,X)=>$.check(n0(W,X)),$.unwrap=()=>$.element});function Qz($,T){return Pw(vH,$,T)}function yB($){let T=$._zod.def.shape;return uH(Object.keys(T))}var hY=K("ZodObject",($,T)=>{lJ.init($,T),z$.init($,T),g.defineLazy($,"shape",()=>{return Object.fromEntries(Object.entries($._zod.def.shape))}),$.keyof=()=>mH(Object.keys($._zod.def.shape)),$.catchall=(W)=>$.clone({...$._zod.def,catchall:W}),$.passthrough=()=>$.clone({...$._zod.def,catchall:jY()}),$.loose=()=>$.clone({...$._zod.def,catchall:jY()}),$.strict=()=>$.clone({...$._zod.def,catchall:yY()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(W)=>{return g.extend($,W)},$.merge=(W)=>g.merge($,W),$.pick=(W)=>g.pick($,W),$.omit=(W)=>g.omit($,W),$.partial=(...W)=>g.partial(Vz,$,W[0]),$.required=(...W)=>g.required(Kz,$,W[0])});function hB($,T){let W={type:"object",get shape(){return g.assignProp(this,"shape",{...$}),this.shape},...g.normalizeParams(T)};return new hY(W)}function gB($,T){return new hY({type:"object",get shape(){return g.assignProp(this,"shape",{...$}),this.shape},catchall:yY(),...g.normalizeParams(T)})}function mB($,T){return new hY({type:"object",get shape(){return g.assignProp(this,"shape",{...$}),this.shape},catchall:jY(),...g.normalizeParams(T)})}var Zz=K("ZodUnion",($,T)=>{UY.init($,T),z$.init($,T),$.options=T.options});function gY($,T){return new Zz({type:"union",options:$,...g.normalizeParams(T)})}var jH=K("ZodDiscriminatedUnion",($,T)=>{Zz.init($,T),rJ.init($,T)});function cB($,T,W){return new jH({type:"union",options:T,discriminator:$,...g.normalizeParams(W)})}var xH=K("ZodIntersection",($,T)=>{iJ.init($,T),z$.init($,T)});function bH($,T){return new xH({type:"intersection",left:$,right:T})}var fH=K("ZodTuple",($,T)=>{e1.init($,T),z$.init($,T),$.rest=(W)=>$.clone({...$._zod.def,rest:W})});function uB($,T,W){let X=T instanceof W$,Y=X?W:T;return new fH({type:"tuple",items:$,rest:X?T:null,...g.normalizeParams(Y)})}var Dz=K("ZodRecord",($,T)=>{nJ.init($,T),z$.init($,T),$.keyType=T.keyType,$.valueType=T.valueType});function yH($,T,W){return new Dz({type:"record",keyType:$,valueType:T,...g.normalizeParams(W)})}function pB($,T,W){return new Dz({type:"record",keyType:gY([$,yY()]),valueType:T,...g.normalizeParams(W)})}var hH=K("ZodMap",($,T)=>{tJ.init($,T),z$.init($,T),$.keyType=T.keyType,$.valueType=T.valueType});function dB($,T,W){return new hH({type:"map",keyType:$,valueType:T,...g.normalizeParams(W)})}var gH=K("ZodSet",($,T)=>{aJ.init($,T),z$.init($,T),$.min=(...W)=>$.check(T0(...W)),$.nonempty=(W)=>$.check(T0(1,W)),$.max=(...W)=>$.check(r0(...W)),$.size=(...W)=>$.check(kW(...W))});function oB($,T){return new gH({type:"set",valueType:$,...g.normalizeParams(T)})}var dW=K("ZodEnum",($,T)=>{sJ.init($,T),z$.init($,T),$.enum=T.entries,$.options=Object.values(T.entries);let W=new Set(Object.keys(T.entries));$.extract=(X,Y)=>{let U={};for(let G of X)if(W.has(G))U[G]=T.entries[G];else throw new Error(`Key ${G} not found in enum`);return new dW({...T,checks:[],...g.normalizeParams(Y),entries:U})},$.exclude=(X,Y)=>{let U={...T.entries};for(let G of X)if(W.has(G))delete U[G];else throw new Error(`Key ${G} not found in enum`);return new dW({...T,checks:[],...g.normalizeParams(Y),entries:U})}});function mH($,T){let W=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new dW({type:"enum",entries:W,...g.normalizeParams(T)})}function lB($,T){return new dW({type:"enum",entries:$,...g.normalizeParams(T)})}var cH=K("ZodLiteral",($,T)=>{eJ.init($,T),z$.init($,T),$.values=new Set(T.values),Object.defineProperty($,"value",{get(){if(T.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return T.values[0]}})});function uH($,T){return new cH({type:"literal",values:Array.isArray($)?$:[$],...g.normalizeParams(T)})}var pH=K("ZodFile",($,T)=>{$9.init($,T),z$.init($,T),$.min=(W,X)=>$.check(T0(W,X)),$.max=(W,X)=>$.check(r0(W,X)),$.mime=(W,X)=>$.check(bW(W,X))});function rB($){return vw(pH,$)}var dH=K("ZodTransform",($,T)=>{T9.init($,T),z$.init($,T),$._zod.parse=(W,X)=>{W.addIssue=(U)=>{if(typeof U==="string")W.issues.push(g.issue(U,W.value,T));else{let G=U;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=W.value),G.inst??(G.inst=$),G.continue??(G.continue=!0),W.issues.push(g.issue(G))}};let Y=T.transform(W.value,W);if(Y instanceof Promise)return Y.then((U)=>{return W.value=U,W});return W.value=Y,W}});function Oz($){return new dH({type:"transform",transform:$})}var Vz=K("ZodOptional",($,T)=>{W9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType});function xY($){return new Vz({type:"optional",innerType:$})}var oH=K("ZodNullable",($,T)=>{X9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType});function bY($){return new oH({type:"nullable",innerType:$})}function iB($){return xY(bY($))}var lH=K("ZodDefault",($,T)=>{Y9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function rH($,T){return new lH({type:"default",innerType:$,get defaultValue(){return typeof T==="function"?T():T}})}var iH=K("ZodPrefault",($,T)=>{U9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType});function nH($,T){return new iH({type:"prefault",innerType:$,get defaultValue(){return typeof T==="function"?T():T}})}var Kz=K("ZodNonOptional",($,T)=>{G9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType});function tH($,T){return new Kz({type:"nonoptional",innerType:$,...g.normalizeParams(T)})}var aH=K("ZodSuccess",($,T)=>{J9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType});function nB($){return new aH({type:"success",innerType:$})}var sH=K("ZodCatch",($,T)=>{w9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function eH($,T){return new sH({type:"catch",innerType:$,catchValue:typeof T==="function"?T:()=>T})}var $F=K("ZodNaN",($,T)=>{z9.init($,T),z$.init($,T)});function tB($){return Sw($F,$)}var Ez=K("ZodPipe",($,T)=>{LW.init($,T),z$.init($,T),$.in=T.in,$.out=T.out});function fY($,T){return new Ez({type:"pipe",in:$,out:T})}var TF=K("ZodReadonly",($,T)=>{_9.init($,T),z$.init($,T)});function WF($){return new TF({type:"readonly",innerType:$})}var XF=K("ZodTemplateLiteral",($,T)=>{H9.init($,T),z$.init($,T)});function aB($,T){return new XF({type:"template_literal",parts:$,...g.normalizeParams(T)})}var YF=K("ZodLazy",($,T)=>{Q9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.getter()});function UF($){return new YF({type:"lazy",getter:$})}var GF=K("ZodPromise",($,T)=>{F9.init($,T),z$.init($,T),$.unwrap=()=>$._zod.def.innerType});function sB($){return new GF({type:"promise",innerType:$})}var mY=K("ZodCustom",($,T)=>{Z9.init($,T),z$.init($,T)});function JF($,T){let W=new u$({check:"custom",...g.normalizeParams(T)});return W._zod.check=$,W}function eB($,T){return mW(mY,$??(()=>!0),T)}function wF($,T={}){return mW(mY,$,T)}function zF($,T){let W=JF((X)=>{return X.addIssue=(Y)=>{if(typeof Y==="string")X.issues.push(g.issue(Y,X.value,W._zod.def));else{let U=Y;if(U.fatal)U.continue=!1;U.code??(U.code="custom"),U.input??(U.input=X.value),U.inst??(U.inst=W),U.continue??(U.continue=!W._zod.def.abort),X.issues.push(g.issue(U))}},$(X.value,X)},T);return W}function $R($,T={error:`Input not instance of ${$.name}`}){let W=new mY({type:"custom",check:"custom",fn:(X)=>X instanceof $,abort:!0,...g.normalizeParams(T)});return W._zod.bag.Class=$,W}var TR=jw.bind(null,{Pipe:Ez,Boolean:uW,Unknown:Fz});function WR($){let T=UF(()=>{return gY([ow($),LH(),SH(),kH(),Qz(T),yH(ow(),T)])});return T}function XR($,T){return fY(Oz($),T)}var YR={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},UR=Object.freeze({status:"aborted"}),GR=UR;function JR($){n$({customError:$})}function wR(){return n$().customError}n$(SW());function _F($,T){return function W({schema:X,fallback:Y,toJsonSchema:U=cY.toJSONSchema}){let G=U(X);return async function J(z,w=3){let H,_=[];while(_.length<w){H=await $(z,G,Y,_);let F=await X["~standard"].validate(H);if("value"in F)return F.value;T?.warn(`safegen failed to generate well-formed data.
|
|
10
34
|
`,`Here's what was returned last time:
|
|
11
|
-
`,JSON.stringify(
|
|
35
|
+
`,JSON.stringify(H,null,"\t"),`
|
|
12
36
|
`,`Here are the issues returned from our validation:
|
|
13
|
-
`,JSON.stringify(
|
|
14
|
-
`)}var
|
|
15
|
-
- ${
|
|
37
|
+
`,JSON.stringify(F.issues,null,"\t")),_.push({response:H,error:F})}return T?.error(`safegen was unable to generate well-formed data after ${w} failed attempts.`),Y}}}function HF($){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify($,null,2)].join(`
|
|
38
|
+
`)}var MF=DA(ZF(),1);import*as f4 from"fs";import*as e0 from"path";import{resolve as ZR}from"path";import{createHash as DR}from"crypto";import{copyFile as OR}from"fs/promises";import{existsSync as Mz,mkdirSync as DF,readFileSync as FR,readdirSync as OF,rmSync as VF,statSync as KF,writeFileSync as QR}from"fs";import{resolve as Az}from"path";var EF=class{rootDir;get initialized(){return Mz(this.rootDir)}initialize(){if(!this.initialized)DF(this.rootDir,{recursive:!0})}constructor($){if(this.rootDir=$.path,$.eagerInit)this.initialize()}getItem($){let T=Az(this.rootDir,$);if(Mz(T))return FR(T,"utf-8");return null}setItem($,T){this.initialize();let W=Az(this.rootDir,$);QR(W,T)}removeItem($){let T=Az(this.rootDir,$);if(Mz(T))this.initialize(),VF(T)}key($){return OF(this.rootDir).sort((X,Y)=>{let U=KF(X);return KF(Y).ctimeMs-U.ctimeMs})[$]??null}clear(){VF(this.rootDir,{recursive:!0}),DF(this.rootDir,{recursive:!0})}get length(){return OF(this.rootDir).length}};var AF=/[^a-zA-Z0-9\-._]/g;function iW($,T=64){if(T%2===1)T+=1;let W=$.replace(AF,"-");if(W.length<=T)return W;let X=DR("sha256").update($).digest("base64").slice(0,8).replaceAll("/","_"),Y=W;if(Y.length>T){let U=Y.slice(0,T/2),G=Y.slice(-T/2);Y=U+"_"+G}return Y+"+"+X}var VR=MF.default("varmint"),rW=iW(process.cwd(),150),Nz=ZR(VR,rW),W4="_-$-_-$-_",NF=`file${W4}`,LF=`list${W4}`,SF=`root${W4}`,KR=`unmatched${W4}`,P$={storage:new EF({path:Nz,eagerInit:!1}),startGlobalTracking(){if(console.log(`\uD83D\uDC3F\uFE0F Starting global tracking of varmint files using project identifier "${rW}"`),P$.storage.initialized)console.error(`\uD83D\uDCA5 The global cache for the project "${rW}" was found already initialized. Clearing it and starting fresh.`),P$.storage.clear();P$.storage.initialize()},async prepareUploads($){console.log(`\uD83D\uDC3F\uFE0F Moving unmatched inputs to /tmp/varmint-uploads using project identifier "${rW}"`);let T=[];for(let W of f4.readdirSync(P$.storage.rootDir))if(uY(`unmatched${W4}`,W))T.push(W);if(T.length===0){console.log("\uD83D\uDC3F\uFE0F ","No unmatched input files found.");return}if(console.log("\uD83D\uDC3F\uFE0F ","Found the following unmatched files:",`
|
|
39
|
+
- ${T.join(`
|
|
16
40
|
`)}
|
|
17
41
|
`,`in root folder:
|
|
18
|
-
`,
|
|
42
|
+
`,Nz),process.env[$])f4.mkdirSync("/tmp/varmint-uploads",{recursive:!0}),await Promise.all(T.map(async(W)=>{let X=e0.join(Nz,W),Y=e0.join("/tmp/varmint-uploads",W);await OR(X,Y)}));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 "${rW}" and starting cleanup of untouched files.`),!P$.storage.initialized){console.error("\uD83D\uDCA5 called flushGlobal, but the global cache wasn't initialized with startGlobalTracking");return}let $=f4.readdirSync(P$.storage.rootDir),T=new Map,W=[],X=[],Y=[];for(let G of $)if(uY(`root${W4}`,G))W.push(G);else if(uY(`list${W4}`,G))X.push(G);else if(uY(`file${W4}`,G))Y.push(G);if(P$.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 G=new Map;for(let J of W){let z=J.replace(SF,"");G.set(z,new Map);let w=P$.storage.getItem(J);if(w)T.set(z,w);else console.error(`\uD83D\uDCA5 Could not find folder ${w} referenced in the global cache`)}for(let J of X){let z=J.replace(LF,""),[w,H]=z.split(W4),_=G.get(w);if(_)_.set(H,new Set);else console.error(`\uD83D\uDCA5 Could not find root ${w} for list ${H}`)}for(let J of Y){let z=J.replace(NF,""),[w,H,_]=z.split(W4),F=G.get(w);if(F){let D=F.get(H);if(D)D.add(_);else console.error(`\uD83D\uDCA5 Could not find list ${H} for file ${z}`)}else console.error(`\uD83D\uDCA5 Could not find root ${w} for file ${z}`)}console.log("\uD83D\uDC3F\uFE0F ",G);for(let[J,z]of G.entries()){let w=T.get(J);if(!w){console.error(`\uD83D\uDCA5 Could not find root ${J}`);continue}if(!f4.existsSync(w)){console.warn(`\uD83D\uDCA5 Root folder ${w}, identified as being used during tracking, no longer exists during cleanup.`);continue}let _=f4.readdirSync(w);for(let F of _)if(F!==".ferret"&&!z.has(F)){let D=e0.join(w,F);console.log(`\uD83E\uDDF9 globalFlush: removing directory ${D}`),f4.rmSync(D,{recursive:!0})}for(let[F,D]of z.entries()){let V=e0.join(w,F);if(!f4.existsSync(V)){console.warn(`\uD83D\uDCA5 List folder ${V}, identified as being used during tracking, no longer exists.`);continue}let R=f4.readdirSync(V);for(let P of R){let A=P.replace(".input.json","").replace(".output.json","").replace(".stream.txt","");if(!D.has(A)){let N=e0.join(V,P);console.log(`\uD83E\uDDF9 globalFlush: removing file ${N}`),f4.rmSync(N)}}}}}f4.rmSync(P$.storage.rootDir,{recursive:!0})}};function uY($,T){return T.startsWith($)}import*as l$ from"fs";import*as K6 from"path";import{inspect as BF}from"util";var RF=class{filenameCache=new Map;filesTouched=new Map;mode;baseDir;rootName;constructor($="off",T=K6.join(process.cwd(),".varmint")){if(this.mode=$,this.baseDir=T,this.rootName=iW(this.baseDir),P$.storage.initialized&&!P$.storage.getItem(`root${W4}${this.rootName}`))P$.storage.setItem(`root${W4}${this.rootName}`,this.baseDir)}read($,T,W){let X=K6.join(this.baseDir,$),Y=`${T}.input.json`,U=K6.join(X,Y);if(!l$.existsSync(U)){if(!l$.existsSync(X)){if(P$.storage.initialized&&this.mode==="read")P$.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${$}" with "${T}" was not found. Directory "${X}" does not exist.`)}let _=l$.readdirSync(X).map((V)=>[V,l$.readFileSync(K6.join(X,V),"utf-8")]).filter(([V])=>V.endsWith(".input.json")),F=[];for(let[V,E]of _){let R=` ${V}`,P=` ${BF(JSON.parse(E),{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
|
|
19
43
|
`).join(`
|
|
20
|
-
`)}`;
|
|
21
|
-
${
|
|
44
|
+
`)}`;F.push(R,P)}let D=` ${Y}
|
|
45
|
+
${BF(W,{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
|
|
22
46
|
`).join(`
|
|
23
|
-
`)}`;if(
|
|
47
|
+
`)}`;if(P$.storage.initialized&&this.mode==="read")P$.storage.setItem(`unmatched${W4}${Y}`,JSON.stringify(W,null,"\t")),P$.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${$}" with subKey "${T}" (${U}) was not found. Directory "${X}" 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
48
|
|
|
25
49
|
CACHED INPUT FILES:
|
|
26
|
-
${
|
|
50
|
+
${F.join(`
|
|
27
51
|
`)}
|
|
28
52
|
|
|
29
53
|
YOUR INPUT DATA:
|
|
30
|
-
${
|
|
31
|
-
`)}let
|
|
54
|
+
${D}
|
|
55
|
+
`)}let G=l$.readFileSync(U,"utf-8"),J=JSON.stringify(W,null,"\t");if(J!==G){if(P$.storage.initialized&&this.mode==="read")P$.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: the content of the cached input file ${U} does not match the input provided.
|
|
32
56
|
|
|
33
57
|
Provided:
|
|
34
|
-
${
|
|
58
|
+
${J}
|
|
35
59
|
|
|
36
60
|
Cached:
|
|
37
|
-
${H}`)}let Q=LW.join(this.baseDir,`${W}/${$}.output.json`);return JSON.parse(i0.readFileSync(Q,"utf-8"))}async write(W,$,Y,X){let G=LW.join(this.baseDir,W),J=LW.join(G,`${$}.input.json`),H=LW.join(G,`${$}.output.json`),T=JSON.stringify(Y,null,"\t");if(!i0.existsSync(this.baseDir))i0.mkdirSync(this.baseDir,{recursive:!0});if(!i0.existsSync(G))i0.mkdirSync(G);if(i0.writeFileSync(J,T),i0.existsSync(H))i0.unlinkSync(H);let Q=await X(...Y),_=JSON.stringify(Q,null,"\t");return i0.writeFileSync(H,_),Q}add(W,$){let Y=`${this.rootName}${Y1}${L4(W)}`;return{flush:()=>{this.flush(W)},for:(X)=>{if(this.mode!=="off"){if(this.filesTouched.set(W,new Set),P0.storage.initialized&&!P0.storage.getItem(`list${Y1}${Y}`))P0.storage.setItem(`list${Y1}${Y}`,"true")}return{get:async(...G)=>{let J=X;if(this.mode!=="off"){let H=this.filenameCache.get(X);if(!H)H=L4(X),this.filenameCache.set(X,H);J=H,this.filesTouched.get(W)?.add(J);let T=`${Y}${Y1}${J}`,Q=`file${Y1}${T}`;if(P0.storage.initialized&&!P0.storage.getItem(Q))P0.storage.setItem(Q,"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[$,Y]of this.filesTouched.entries())if(W.length===0||W.includes($)){let X=LW.join(this.baseDir,$),G=i0.readdirSync(X);for(let J of G){let H=J.replace(".input.json","").replace(".output.json","");if(!Y.has(H))console.info(`\uD83E\uDDF9 Flushing ${H}`),i0.unlinkSync(LW.join(X,J))}}}};var SY="RFC3986",qY={RFC1738:(W)=>String(W).replace(/%20/g,"+"),RFC3986:(W)=>String(W)},o3="RFC1738";var jM=Array.isArray,vW=(()=>{let W=[];for(let $=0;$<256;++$)W.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return W})();var e9=1024,i3=(W,$,Y,X,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(Y==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});let H="";for(let T=0;T<J.length;T+=e9){let Q=J.length>=e9?J.slice(T,T+e9):J,_=[];for(let z=0;z<Q.length;++z){let F=Q.charCodeAt(z);if(F===45||F===46||F===95||F===126||F>=48&&F<=57||F>=65&&F<=90||F>=97&&F<=122||G===o3&&(F===40||F===41)){_[_.length]=Q.charAt(z);continue}if(F<128){_[_.length]=vW[F];continue}if(F<2048){_[_.length]=vW[192|F>>6]+vW[128|F&63];continue}if(F<55296||F>=57344){_[_.length]=vW[224|F>>12]+vW[128|F>>6&63]+vW[128|F&63];continue}z+=1,F=65536+((F&1023)<<10|Q.charCodeAt(z)&1023),_[_.length]=vW[240|F>>18]+vW[128|F>>12&63]+vW[128|F>>6&63]+vW[128|F&63]}H+=_.join("")}return H};function n3(W){if(!W||typeof W!=="object")return!1;return!!(W.constructor&&W.constructor.isBuffer&&W.constructor.isBuffer(W))}function W5(W,$){if(jM(W)){let Y=[];for(let X=0;X<W.length;X+=1)Y.push($(W[X]));return Y}return $(W)}var IM=Object.prototype.hasOwnProperty,r3={brackets(W){return String(W)+"[]"},comma:"comma",indices(W,$){return String(W)+"["+$+"]"},repeat(W){return String(W)}},yW=Array.isArray,PM=Array.prototype.push,t3=function(W,$){PM.apply(W,yW($)?$:[$])},fM=Date.prototype.toISOString,X1={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:i3,encodeValuesOnly:!1,format:SY,formatter:qY[SY],indices:!1,serializeDate(W){return fM.call(W)},skipNulls:!1,strictNullHandling:!1};function bM(W){return typeof W==="string"||typeof W==="number"||typeof W==="boolean"||typeof W==="symbol"||typeof W==="bigint"}var $5={};function a3(W,$,Y,X,G,J,H,T,Q,_,z,F,w,O,V,E,I,j){let N=W,B=j,P=0,g=!1;while((B=B.get($5))!==void 0&&!g){let Z=B.get(W);if(P+=1,typeof Z!=="undefined")if(Z===P)throw new RangeError("Cyclic object value");else g=!0;if(typeof B.get($5)==="undefined")P=0}if(typeof _==="function")N=_($,N);else if(N instanceof Date)N=w?.(N);else if(Y==="comma"&&yW(N))N=W5(N,function(Z){if(Z instanceof Date)return w?.(Z);return Z});if(N===null){if(J)return Q&&!E?Q($,X1.encoder,I,"key",O):$;N=""}if(bM(N)||n3(N)){if(Q){let Z=E?$:Q($,X1.encoder,I,"key",O);return[V?.(Z)+"="+V?.(Q(N,X1.encoder,I,"value",O))]}return[V?.($)+"="+V?.(String(N))]}let x=[];if(typeof N==="undefined")return x;let p;if(Y==="comma"&&yW(N)){if(E&&Q)N=W5(N,Q);p=[{value:N.length>0?N.join(",")||null:void 0}]}else if(yW(_))p=_;else{let Z=Object.keys(N);p=z?Z.sort(z):Z}let w0=T?String($).replace(/\./g,"%2E"):String($),p0=X&&yW(N)&&N.length===1?w0+"[]":w0;if(G&&yW(N)&&N.length===0)return p0+"[]";for(let Z=0;Z<p.length;++Z){let M0=p[Z],Y0=typeof M0==="object"&&typeof M0.value!=="undefined"?M0.value:N[M0];if(H&&Y0===null)continue;let U0=F&&T?M0.replace(/\./g,"%2E"):M0,e0=yW(N)?typeof Y==="function"?Y(p0,U0):p0:p0+(F?"."+U0:"["+U0+"]");j.set(W,P);let V1=new WeakMap;V1.set($5,j),t3(x,a3(Y0,e0,Y,X,G,J,H,T,Y==="comma"&&E&&yW(N)?null:Q,_,z,F,w,O,V,E,I,V1))}return x}function xM(W=X1){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||X1.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 Y=SY;if(typeof W.format!=="undefined"){if(!IM.call(qY,W.format))throw new TypeError("Unknown format option provided.");Y=W.format}let X=qY[Y],G=X1.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=X1.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:X1.allowDots:!!W.allowDots;return{addQueryPrefix:typeof W.addQueryPrefix==="boolean"?W.addQueryPrefix:X1.addQueryPrefix,allowDots:H,allowEmptyArrays:typeof W.allowEmptyArrays==="boolean"?!!W.allowEmptyArrays:X1.allowEmptyArrays,arrayFormat:J,charset:$,charsetSentinel:typeof W.charsetSentinel==="boolean"?W.charsetSentinel:X1.charsetSentinel,commaRoundTrip:!!W.commaRoundTrip,delimiter:typeof W.delimiter==="undefined"?X1.delimiter:W.delimiter,encode:typeof W.encode==="boolean"?W.encode:X1.encode,encodeDotInKeys:typeof W.encodeDotInKeys==="boolean"?W.encodeDotInKeys:X1.encodeDotInKeys,encoder:typeof W.encoder==="function"?W.encoder:X1.encoder,encodeValuesOnly:typeof W.encodeValuesOnly==="boolean"?W.encodeValuesOnly:X1.encodeValuesOnly,filter:G,format:Y,formatter:X,serializeDate:typeof W.serializeDate==="function"?W.serializeDate:X1.serializeDate,skipNulls:typeof W.skipNulls==="boolean"?W.skipNulls:X1.skipNulls,sort:typeof W.sort==="function"?W.sort:null,strictNullHandling:typeof W.strictNullHandling==="boolean"?W.strictNullHandling:X1.strictNullHandling}}function Y5(W,$={}){let Y=W,X=xM($),G,J;if(typeof X.filter==="function")J=X.filter,Y=J("",Y);else if(yW(X.filter))J=X.filter,G=J;let H=[];if(typeof Y!=="object"||Y===null)return"";let T=r3[X.arrayFormat],Q=T==="comma"&&X.commaRoundTrip;if(!G)G=Object.keys(Y);if(X.sort)G.sort(X.sort);let _=new WeakMap;for(let w=0;w<G.length;++w){let O=G[w];if(X.skipNulls&&Y[O]===null)continue;t3(H,a3(Y[O],O,T,Q,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,_))}let z=H.join(X.delimiter),F=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")F+="utf8=%26%2310003%3B&";else F+="utf8=%E2%9C%93&";return z.length>0?F+z:""}var s$="4.100.0";var s3=!1,e$=void 0,X5=void 0,yM=void 0,hM=void 0,gM=void 0,G5=void 0,mM=void 0,CY=void 0,J5=void 0,H5=void 0,T5=void 0,kY=void 0,Q5=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(e$)throw new Error(`can't \`import 'openai/shims/${W.kind}'\` after \`import 'openai/shims/${e$}'\``);s3=$.auto,e$=W.kind,X5=W.fetch,yM=W.Request,hM=W.Response,gM=W.Headers,G5=W.FormData,mM=W.Blob,CY=W.File,J5=W.ReadableStream,H5=W.getMultipartRequestOptions,T5=W.getDefaultAgent,kY=W.fileFromPath,Q5=W.isFsReadStream}class _5{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",Y,X,G,J;try{Y=fetch,X=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:Y,Request:X,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,T)=>({...T,body:new _5(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 uM}from"fs";function $H(){let W=WH();function $(Y){return Y instanceof uM}return{...W,isFsReadStream:$}}var z5=()=>{if(!e$)e3($H(),{auto:!0})};z5();class o extends Error{}class t0 extends o{constructor(W,$,Y,X){super(`${t0.makeMessage(W,$,Y)}`);this.status=W,this.headers=X,this.request_id=X?.["x-request-id"],this.error=$;let G=$;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage(W,$,Y){let X=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):Y;if(W&&X)return`${W} ${X}`;if(W)return`${W} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate(W,$,Y,X){if(!W||!X)return new W2({message:Y,cause:hY($)});let G=$?.error;if(W===400)return new jY(W,G,Y,X);if(W===401)return new IY(W,G,Y,X);if(W===403)return new PY(W,G,Y,X);if(W===404)return new fY(W,G,Y,X);if(W===409)return new bY(W,G,Y,X);if(W===422)return new xY(W,G,Y,X);if(W===429)return new vY(W,G,Y,X);if(W>=500)return new yY(W,G,Y,X);return new t0(W,G,Y,X)}}class G1 extends t0{constructor({message:W}={}){super(void 0,void 0,W||"Request was aborted.",void 0)}}class W2 extends t0{constructor({message:W,cause:$}){super(void 0,void 0,W||"Connection error.",void 0);if($)this.cause=$}}class $2 extends W2{constructor({message:W}={}){super({message:W??"Request timed out."})}}class jY extends t0{}class IY extends t0{}class PY extends t0{}class fY extends t0{}class bY extends t0{}class xY extends t0{}class vY extends t0{}class yY extends t0{}class Z4 extends o{constructor(){super("Could not parse response content as the length limit was reached")}}class N4 extends o{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var gY=function(W,$,Y,X,G){if(X==="m")throw new TypeError("Private method is not writable");if(X==="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 X==="a"?G.call(W,Y):G?G.value=Y:$.set(W,Y),Y},Y2=function(W,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},r1;class i2{constructor(){r1.set(this,void 0),this.buffer=new Uint8Array,gY(this,r1,null,"f")}decode(W){if(W==null)return[];let $=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?new TextEncoder().encode(W):W,Y=new Uint8Array(this.buffer.length+$.length);Y.set(this.buffer),Y.set($,this.buffer.length),this.buffer=Y;let X=[],G;while((G=dM(this.buffer,Y2(this,r1,"f")))!=null){if(G.carriage&&Y2(this,r1,"f")==null){gY(this,r1,G.index,"f");continue}if(Y2(this,r1,"f")!=null&&(G.index!==Y2(this,r1,"f")+1||G.carriage)){X.push(this.decodeText(this.buffer.slice(0,Y2(this,r1,"f")-1))),this.buffer=this.buffer.slice(Y2(this,r1,"f")),gY(this,r1,null,"f");continue}let J=Y2(this,r1,"f")!==null?G.preceding-1:G.preceding,H=this.decodeText(this.buffer.slice(0,J));X.push(H),this.buffer=this.buffer.slice(G.index),gY(this,r1,null,"f")}return X}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
|
-
`)}}
|
|
39
|
-
`,"\r"])
|
|
40
|
-
`);X.enqueue(
|
|
41
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push(W),W.startsWith(":"))return null;let[$,Y,X]=iM(W,":");if(X.startsWith(" "))X=X.substring(1);if($==="event")this.event=X;else if($==="data")this.data.push(X);return null}}function iM(W,$){let Y=W.indexOf($);if(Y!==-1)return[W.substring(0,Y),$,W.substring(Y+$.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"&&R4(W),R4=(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",nM=(W)=>{return JH(W)||GH(W)||Q5(W)};async function M5(W,$,Y){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=R4(G)?[await G.arrayBuffer()]:[G];return new CY(J,$,Y)}let X=await rM(W);if($||($=aM(W)??"unknown_file"),!Y?.type){let G=X[0]?.type;if(typeof G==="string")Y={...Y,type:G}}return new CY(X,$,Y)}async function rM(W){let $=[];if(typeof W==="string"||ArrayBuffer.isView(W)||W instanceof ArrayBuffer)$.push(W);else if(R4(W))$.push(await W.arrayBuffer());else if(sM(W))for await(let Y of W)$.push(Y);else throw new Error(`Unexpected data type: ${typeof W}; constructor: ${W?.constructor?.name}; props: ${tM(W)}`);return $}function tM(W){return`[${Object.getOwnPropertyNames(W).map((Y)=>`"${Y}"`).join(", ")}]`}function aM(W){return U5(W.name)||U5(W.filename)||U5(W.path)?.split(/[\\/]/).pop()}var U5=(W)=>{if(typeof W==="string")return W;if(typeof Buffer!=="undefined"&&W instanceof Buffer)return String(W);return},sM=(W)=>W!=null&&typeof W==="object"&&typeof W[Symbol.asyncIterator]==="function",V5=(W)=>W&&typeof W==="object"&&W.body&&W[Symbol.toStringTag]==="MultipartBody";var JW=async(W)=>{let $=await HH(W.body);return H5($,W)},HH=async(W)=>{let $=new G5;return await Promise.all(Object.entries(W||{}).map(([Y,X])=>D5($,Y,X))),$};var D5=async(W,$,Y)=>{if(Y===void 0)return;if(Y==null)throw new TypeError(`Received null for "${$}"; to pass null in FormData, you must use the string 'null'`);if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")W.append($,String(Y));else if(nM(Y)){let X=await M5(Y);W.append($,X)}else if(Array.isArray(Y))await Promise.all(Y.map((X)=>D5(W,$+"[]",X)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([X,G])=>D5(W,`${$}[${X}]`,G)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var WV=function(W,$,Y,X,G){if(X==="m")throw new TypeError("Private method is not writable");if(X==="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 X==="a"?G.call(W,Y):G?G.value=Y:$.set(W,Y),Y},$V=function(W,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},mY;z5();async function wH(W){let{response:$}=W;if(W.options.stream){if(tW("response",$.status,$.url,$.headers,$.body),W.options.__streamClass)return W.options.__streamClass.fromSSEResponse($,W.controller);return t1.fromSSEResponse($,W.controller)}if($.status===204)return null;if(W.options.__binaryResponse)return $;let X=$.headers.get("content-type")?.split(";")[0]?.trim();if(X?.includes("application/json")||X?.endsWith("+json")){let H=await $.json();return tW("response",$.status,$.url,$.headers,H),UH(H,$)}let J=await $.text();return tW("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 uY extends Promise{constructor(W,$=wH){super((Y)=>{Y(null)});this.responsePromise=W,this.parseResponse=$}_thenUnwrap(W){return new uY(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 K5{constructor({baseURL:W,maxRetries:$=2,timeout:Y=600000,httpAgent:X,fetch:G}){this.baseURL=W,this.maxRetries=O5("maxRetries",$),this.timeout=O5("timeout",Y),this.httpAgent=X,this.fetch=G??X5}authHeaders(W){return{}}defaultHeaders(W){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...JV(),...this.authHeaders(W)}}validateHeaders(W,$){}defaultIdempotencyKey(){return`stainless-node-retry-${_V()}`}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,$,Y){return this.request(Promise.resolve(Y).then(async(X)=>{let G=X&&R4(X?.body)?new DataView(await X.body.arrayBuffer()):X?.body instanceof DataView?X.body:X?.body instanceof ArrayBuffer?new DataView(X.body):X&&ArrayBuffer.isView(X?.body)?new DataView(X.body.buffer):X?.body;return{method:W,path:$,...X,body:G}}))}getAPIList(W,$,Y){return this.requestAPIList($,{method:"get",path:W,...Y})}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 Y={...W},{method:X,path:G,query:J,headers:H={}}=Y,T=ArrayBuffer.isView(Y.body)||Y.__binaryRequest&&typeof Y.body==="string"?Y.body:V5(Y.body)?Y.body.body:Y.body?JSON.stringify(Y.body,null,2):null,Q=this.calculateContentLength(T),_=this.buildURL(G,J);if("timeout"in Y)O5("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let z=Y.httpAgent??this.httpAgent??T5(_),F=Y.timeout+1000;if(typeof z?.options?.timeout==="number"&&F>(z.options.timeout??0))z.options.timeout=F;if(this.idempotencyHeader&&X!=="get"){if(!W.idempotencyKey)W.idempotencyKey=this.defaultIdempotencyKey();H[this.idempotencyHeader]=W.idempotencyKey}let w=this.buildHeaders({options:Y,headers:H,contentLength:Q,retryCount:$});return{req:{method:X,...T&&{body:T},headers:w,...z&&{agent:z},signal:Y.signal??null},url:_,timeout:Y.timeout}}buildHeaders({options:W,headers:$,contentLength:Y,retryCount:X}){let G={};if(Y)G["content-length"]=Y;let J=this.defaultHeaders(W);if(zH(G,J),zH(G,$),V5(W.body)&&e$!=="node")delete G["content-type"];if(pY(J,"x-stainless-retry-count")===void 0&&pY($,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(X);if(pY(J,"x-stainless-timeout")===void 0&&pY($,"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:Y}){}parseHeaders(W){return!W?{}:(Symbol.iterator in W)?Object.fromEntries(Array.from(W).map(($)=>[...$])):{...W}}makeStatusError(W,$,Y,X){return t0.generate(W,$,Y,X)}request(W,$=null){return new uY(this.makeRequest(W,$))}async makeRequest(W,$){let Y=await W,X=Y.maxRetries??this.maxRetries;if($==null)$=X;await this.prepareOptions(Y);let{req:G,url:J,timeout:H}=this.buildRequest(Y,{retryCount:X-$});if(await this.prepareRequest(G,{url:J,options:Y}),tW("request",J,Y,G.headers),Y.signal?.aborted)throw new G1;let T=new AbortController,Q=await this.fetchWithTimeout(J,G,H,T).catch(hY);if(Q instanceof Error){if(Y.signal?.aborted)throw new G1;if($)return this.retryRequest(Y,$);if(Q.name==="AbortError")throw new $2;throw new W2({cause:Q})}let _=w5(Q.headers);if(!Q.ok){if($&&this.shouldRetry(Q)){let E=`retrying, ${$} attempts remaining`;return tW(`response (error; ${E})`,Q.status,J,_),this.retryRequest(Y,$,_)}let z=await Q.text().catch((E)=>hY(E).message),F=HV(z),w=F?void 0:z;throw tW(`response (error; ${$?"(error; no more retries left)":"(error; not retryable)"})`,Q.status,J,_,w),this.makeStatusError(Q.status,F,w,_)}return{response:Q,options:Y,controller:T}}requestAPIList(W,$){let Y=this.makeRequest($,null);return new DH(this,Y,W)}buildURL(W,$){let Y=QV(W)?new URL(W):new URL(this.baseURL+(this.baseURL.endsWith("/")&&W.startsWith("/")?W.slice(1):W)),X=this.defaultQuery();if(!MH(X))$={...X,...$};if(typeof $==="object"&&$&&!Array.isArray($))Y.search=this.stringifyQuery($);return Y.toString()}stringifyQuery(W){return Object.entries(W).filter(([$,Y])=>typeof Y!=="undefined").map(([$,Y])=>{if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")return`${encodeURIComponent($)}=${encodeURIComponent(Y)}`;if(Y===null)return`${encodeURIComponent($)}=`;throw new o(`Cannot stringify type ${typeof Y}; 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,$,Y,X){let{signal:G,...J}=$||{};if(G)G.addEventListener("abort",()=>X.abort());let H=setTimeout(()=>X.abort(),Y),T={signal:X.signal,...J};if(T.method)T.method=T.method.toUpperCase();return this.fetch.call(void 0,W,T).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,$,Y){let X,G=Y?.["retry-after-ms"];if(G){let H=parseFloat(G);if(!Number.isNaN(H))X=H}let J=Y?.["retry-after"];if(J&&!X){let H=parseFloat(J);if(!Number.isNaN(H))X=H*1000;else X=Date.parse(J)-Date.now()}if(!(X&&0<=X&&X<60000)){let H=W.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis($,H)}return await aW(X),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 ${s$}`}}class cY{constructor(W,$,Y,X){mY.set(this,void 0),WV(this,mY,W,"f"),this.options=X,this.response=$,this.body=Y}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 Y=[...Object.entries($.query||{}),...W.url.searchParams.entries()];for(let[X,G]of Y)W.url.searchParams.set(X,G);$.query=void 0,$.path=W.url.toString()}return await $V(this,mY,"f").requestAPIList(this.constructor,$)}async*iterPages(){let W=this;yield W;while(W.hasNextPage())W=await W.getNextPage(),yield W}async*[(mY=new WeakMap,Symbol.asyncIterator)](){for await(let W of this.iterPages())for(let $ of W.getPaginatedItems())yield $}}class DH extends uY{constructor(W,$,Y){super($,async(X)=>new Y(W,X.response,await wH(X),X.options))}async*[Symbol.asyncIterator](){let W=await this;for await(let $ of W)yield $}}var w5=(W)=>{return new Proxy(Object.fromEntries(W.entries()),{get($,Y){let X=Y.toString();return $[X.toLowerCase()]||$[X]}})},YV={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},Q0=(W)=>{return typeof W==="object"&&W!==null&&!MH(W)&&Object.keys(W).every(($)=>VH(YV,$))},XV=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s$,"X-Stainless-OS":QH(Deno.build.os),"X-Stainless-Arch":TH(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":s$,"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":s$,"X-Stainless-OS":QH(process.platform),"X-Stainless-Arch":TH(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let W=GV();if(W)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":s$,"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":s$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function GV(){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:Y}of W){let X=Y.exec(navigator.userAgent);if(X){let G=X[1]||0,J=X[2]||0,H=X[3]||0;return{browser:$,version:`${G}.${J}.${H}`}}}return null}var TH=(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"},QH=(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"},_H,JV=()=>{return _H??(_H=XV())},HV=(W)=>{try{return JSON.parse(W)}catch($){return}},TV=/^[a-z][a-z0-9+.-]*:/i,QV=(W)=>{return TV.test(W)},aW=(W)=>new Promise(($)=>setTimeout($,W)),O5=(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 $},hY=(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 B4=(W)=>{if(typeof process!=="undefined")return process.env?.[W]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(W)?.trim();return};function MH(W){if(!W)return!0;for(let $ in W)return!1;return!0}function VH(W,$){return Object.prototype.hasOwnProperty.call(W,$)}function zH(W,$){for(let Y in $){if(!VH($,Y))continue;let X=Y.toLowerCase();if(!X)continue;let G=$[Y];if(G===null)delete W[X];else if(G!==void 0)W[X]=G}}var FH=new Set(["authorization","api-key"]);function tW(W,...$){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true"){let Y=$.map((X)=>{if(!X)return X;if(X.headers){let J={...X,headers:{...X.headers}};for(let H in X.headers)if(FH.has(H.toLowerCase()))J.headers[H]="REDACTED";return J}let G=null;for(let J in X)if(FH.has(J.toLowerCase()))G??(G={...X}),G[J]="REDACTED";return G??X});console.log(`OpenAI:DEBUG:${W}`,...Y)}}var _V=()=>{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"},zV=(W)=>{return typeof W?.get==="function"};var pY=(W,$)=>{let Y=$.toLowerCase();if(zV(W)){let X=$[0]?.toUpperCase()+$.substring(1).replace(/([^\w])(\w)/g,(G,J,H)=>J+H.toUpperCase());for(let G of[$,Y,$.toUpperCase(),X]){let J=W.get(G);if(J)return J}}for(let[X,G]of Object.entries(W))if(X.toLowerCase()===Y){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),Y=$.length,X=new Uint8Array(Y);for(let G=0;G<Y;G++)X[G]=$.charCodeAt(G);return Array.from(new Float32Array(X.buffer))}};function S4(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}class sW extends cY{constructor(W,$,Y,X){super(W,$,Y,X);this.data=Y.data||[],this.object=Y.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class A0 extends cY{constructor(W,$,Y,X){super(W,$,Y,X);this.data=Y.data||[],this.has_more=Y.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 q4 extends C{list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/chat/completions/${W}/messages`,E5,{query:$,...Y})}}class X2 extends C{constructor(){super(...arguments);this.messages=new q4(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,$,Y){return this._client.post(`/chat/completions/${W}`,{body:$,...Y})}list(W={},$){if(Q0(W))return this.list({},W);return this._client.getAPIList("/chat/completions",G2,{query:W,...$})}del(W,$){return this._client.delete(`/chat/completions/${W}`,$)}}class G2 extends A0{}class E5 extends A0{}X2.ChatCompletionsPage=G2;X2.Messages=q4;class C$ extends C{constructor(){super(...arguments);this.completions=new X2(this._client)}}C$.Completions=X2;C$.ChatCompletionsPage=G2;class C4 extends C{create(W,$){return this._client.post("/audio/speech",{body:W,...$,headers:{Accept:"application/octet-stream",...$?.headers},__binaryResponse:!0})}}class k4 extends C{create(W,$){return this._client.post("/audio/transcriptions",JW({body:W,...$,stream:W.stream??!1,__metadata:{model:W.model}}))}}class j4 extends C{create(W,$){return this._client.post("/audio/translations",JW({body:W,...$,__metadata:{model:W.model}}))}}class eW extends C{constructor(){super(...arguments);this.transcriptions=new k4(this._client),this.translations=new j4(this._client),this.speech=new C4(this._client)}}eW.Transcriptions=k4;eW.Translations=j4;eW.Speech=C4;class J2 extends C{create(W,$){return this._client.post("/batches",{body:W,...$})}retrieve(W,$){return this._client.get(`/batches/${W}`,$)}list(W={},$){if(Q0(W))return this.list({},W);return this._client.getAPIList("/batches",n2,{query:W,...$})}cancel(W,$){return this._client.post(`/batches/${W}/cancel`,$)}}class n2 extends A0{}J2.BatchesPage=n2;var ZW=function(W,$,Y,X,G){if(X==="m")throw new TypeError("Private method is not writable");if(X==="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 X==="a"?G.call(W,Y):G?G.value=Y:$.set(W,Y),Y},c0=function(W,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},A5,dY,lY,I4,P4,oY,f4,W$,b4,iY,nY,r2,EH;class H2{constructor(){A5.add(this),this.controller=new AbortController,dY.set(this,void 0),lY.set(this,()=>{}),I4.set(this,()=>{}),P4.set(this,void 0),oY.set(this,()=>{}),f4.set(this,()=>{}),W$.set(this,{}),b4.set(this,!1),iY.set(this,!1),nY.set(this,!1),r2.set(this,!1),ZW(this,dY,new Promise((W,$)=>{ZW(this,lY,W,"f"),ZW(this,I4,$,"f")}),"f"),ZW(this,P4,new Promise((W,$)=>{ZW(this,oY,W,"f"),ZW(this,f4,$,"f")}),"f"),c0(this,dY,"f").catch(()=>{}),c0(this,P4,"f").catch(()=>{})}_run(W){setTimeout(()=>{W().then(()=>{this._emitFinal(),this._emit("end")},c0(this,A5,"m",EH).bind(this))},0)}_connected(){if(this.ended)return;c0(this,lY,"f").call(this),this._emit("connect")}get ended(){return c0(this,b4,"f")}get errored(){return c0(this,iY,"f")}get aborted(){return c0(this,nY,"f")}abort(){this.controller.abort()}on(W,$){return(c0(this,W$,"f")[W]||(c0(this,W$,"f")[W]=[])).push({listener:$}),this}off(W,$){let Y=c0(this,W$,"f")[W];if(!Y)return this;let X=Y.findIndex((G)=>G.listener===$);if(X>=0)Y.splice(X,1);return this}once(W,$){return(c0(this,W$,"f")[W]||(c0(this,W$,"f")[W]=[])).push({listener:$,once:!0}),this}emitted(W){return new Promise(($,Y)=>{if(ZW(this,r2,!0,"f"),W!=="error")this.once("error",Y);this.once(W,$)})}async done(){ZW(this,r2,!0,"f"),await c0(this,P4,"f")}_emit(W,...$){if(c0(this,b4,"f"))return;if(W==="end")ZW(this,b4,!0,"f"),c0(this,oY,"f").call(this);let Y=c0(this,W$,"f")[W];if(Y)c0(this,W$,"f")[W]=Y.filter((X)=>!X.once),Y.forEach(({listener:X})=>X(...$));if(W==="abort"){let X=$[0];if(!c0(this,r2,"f")&&!Y?.length)Promise.reject(X);c0(this,I4,"f").call(this,X),c0(this,f4,"f").call(this,X),this._emit("end");return}if(W==="error"){let X=$[0];if(!c0(this,r2,"f")&&!Y?.length)Promise.reject(X);c0(this,I4,"f").call(this,X),c0(this,f4,"f").call(this,X),this._emit("end")}}_emitFinal(){}}dY=new WeakMap,lY=new WeakMap,I4=new WeakMap,P4=new WeakMap,oY=new WeakMap,f4=new WeakMap,W$=new WeakMap,b4=new WeakMap,iY=new WeakMap,nY=new WeakMap,r2=new WeakMap,A5=new WeakSet,EH=function W($){if(ZW(this,iY,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new G1;if($ instanceof G1)return ZW(this,nY,!0,"f"),this._emit("abort",$);if($ instanceof o)return this._emit("error",$);if($ instanceof Error){let Y=new o($.message);return Y.cause=$,this._emit("error",Y)}return this._emit("error",new o(String($)))};var i=function(W,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},a1=function(W,$,Y,X,G){if(X==="m")throw new TypeError("Private method is not writable");if(X==="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 X==="a"?G.call(W,Y):G?G.value=Y:$.set(W,Y),Y},D1,L5,hW,rY,NW,Q2,t2,T2,sY,s1,tY,aY,y4,x4,v4,AH,LH,ZH,NH,RH,BH,SH;class e1 extends H2{constructor(){super(...arguments);D1.add(this),L5.set(this,[]),hW.set(this,{}),rY.set(this,{}),NW.set(this,void 0),Q2.set(this,void 0),t2.set(this,void 0),T2.set(this,void 0),sY.set(this,void 0),s1.set(this,void 0),tY.set(this,void 0),aY.set(this,void 0),y4.set(this,void 0)}[(L5=new WeakMap,hW=new WeakMap,rY=new WeakMap,NW=new WeakMap,Q2=new WeakMap,t2=new WeakMap,T2=new WeakMap,sY=new WeakMap,s1=new WeakMap,tY=new WeakMap,aY=new WeakMap,y4=new WeakMap,D1=new WeakSet,Symbol.asyncIterator)](){let W=[],$=[],Y=!1;return this.on("event",(X)=>{let G=$.shift();if(G)G.resolve(X);else W.push(X)}),this.on("end",()=>{Y=!0;for(let X of $)X.resolve(void 0);$.length=0}),this.on("abort",(X)=>{Y=!0;for(let G of $)G.reject(X);$.length=0}),this.on("error",(X)=>{Y=!0;for(let G of $)G.reject(X);$.length=0}),{next:async()=>{if(!W.length){if(Y)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 e1;return $._run(()=>$._fromReadableStream(W)),$}async _fromReadableStream(W,$){let Y=$?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}this._connected();let X=t1.fromReadableStream(W,this.controller);for await(let G of X)i(this,D1,"m",x4).call(this,G);if(X.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",v4).call(this))}toReadableStream(){return new t1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(W,$,Y,X,G){let J=new e1;return J._run(()=>J._runToolAssistantStream(W,$,Y,X,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(W,$,Y,X,G){let J=G?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let H={...X,stream:!0},T=await W.submitToolOutputs($,Y,H,{...G,signal:this.controller.signal});this._connected();for await(let Q of T)i(this,D1,"m",x4).call(this,Q);if(T.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",v4).call(this))}static createThreadAssistantStream(W,$,Y){let X=new e1;return X._run(()=>X._threadAssistantStream(W,$,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),X}static createAssistantStream(W,$,Y,X){let G=new e1;return G._run(()=>G._runAssistantStream(W,$,Y,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),G}currentEvent(){return i(this,tY,"f")}currentRun(){return i(this,aY,"f")}currentMessageSnapshot(){return i(this,NW,"f")}currentRunStepSnapshot(){return i(this,y4,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,hW,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,rY,"f"))}async finalRun(){if(await this.done(),!i(this,Q2,"f"))throw Error("Final run was not received.");return i(this,Q2,"f")}async _createThreadAssistantStream(W,$,Y){let X=Y?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let G={...$,stream:!0},J=await W.createAndRun(G,{...Y,signal:this.controller.signal});this._connected();for await(let H of J)i(this,D1,"m",x4).call(this,H);if(J.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",v4).call(this))}async _createAssistantStream(W,$,Y,X){let G=X?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let J={...Y,stream:!0},H=await W.create($,J,{...X,signal:this.controller.signal});this._connected();for await(let T of H)i(this,D1,"m",x4).call(this,T);if(H.controller.signal?.aborted)throw new G1;return this._addRun(i(this,D1,"m",v4).call(this))}static accumulateDelta(W,$){for(let[Y,X]of Object.entries($)){if(!W.hasOwnProperty(Y)){W[Y]=X;continue}let G=W[Y];if(G===null||G===void 0){W[Y]=X;continue}if(Y==="index"||Y==="type"){W[Y]=X;continue}if(typeof G==="string"&&typeof X==="string")G+=X;else if(typeof G==="number"&&typeof X==="number")G+=X;else if(S4(G)&&S4(X))G=this.accumulateDelta(G,X);else if(Array.isArray(G)&&Array.isArray(X)){if(G.every((J)=>typeof J==="string"||typeof J==="number")){G.push(...X);continue}for(let J of X){if(!S4(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 T=G[H];if(T==null)G.push(J);else G[H]=this.accumulateDelta(T,J)}continue}else throw Error(`Unhandled record type: ${Y}, deltaValue: ${X}, accValue: ${G}`);W[Y]=G}return W}_addRun(W){return W}async _threadAssistantStream(W,$,Y){return await this._createThreadAssistantStream($,W,Y)}async _runAssistantStream(W,$,Y,X){return await this._createAssistantStream($,W,Y,X)}async _runToolAssistantStream(W,$,Y,X,G){return await this._createToolAssistantStream(Y,W,$,X,G)}}x4=function W($){if(this.ended)return;switch(a1(this,tY,$,"f"),i(this,D1,"m",ZH).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",AH).call(this,$);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:VV($)}},v4=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");if(!i(this,Q2,"f"))throw Error("Final run has not been received");return i(this,Q2,"f")},AH=function W($){let[Y,X]=i(this,D1,"m",RH).call(this,$,i(this,NW,"f"));a1(this,NW,Y,"f"),i(this,rY,"f")[Y.id]=Y;for(let G of X){let J=Y.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,Y),$.data.delta.content)for(let G of $.data.delta.content){if(G.type=="text"&&G.text){let J=G.text,H=Y.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,t2,"f")){if(i(this,T2,"f"))switch(i(this,T2,"f").type){case"text":this._emit("textDone",i(this,T2,"f").text,i(this,NW,"f"));break;case"image_file":this._emit("imageFileDone",i(this,T2,"f").image_file,i(this,NW,"f"));break}a1(this,t2,G.index,"f")}a1(this,T2,Y.content[G.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,t2,"f")!==void 0){let G=$.data.content[i(this,t2,"f")];if(G)switch(G.type){case"image_file":this._emit("imageFileDone",G.image_file,i(this,NW,"f"));break;case"text":this._emit("textDone",G.text,i(this,NW,"f"));break}}if(i(this,NW,"f"))this._emit("messageDone",$.data);a1(this,NW,void 0,"f")}},LH=function W($){let Y=i(this,D1,"m",NH).call(this,$);switch(a1(this,y4,Y,"f"),$.event){case"thread.run.step.created":this._emit("runStepCreated",$.data);break;case"thread.run.step.delta":let X=$.data.delta;if(X.step_details&&X.step_details.type=="tool_calls"&&X.step_details.tool_calls&&Y.step_details.type=="tool_calls")for(let J of X.step_details.tool_calls)if(J.index==i(this,sY,"f"))this._emit("toolCallDelta",J,Y.step_details.tool_calls[J.index]);else{if(i(this,s1,"f"))this._emit("toolCallDone",i(this,s1,"f"));if(a1(this,sY,J.index,"f"),a1(this,s1,Y.step_details.tool_calls[J.index],"f"),i(this,s1,"f"))this._emit("toolCallCreated",i(this,s1,"f"))}this._emit("runStepDelta",$.data.delta,Y);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(a1(this,y4,void 0,"f"),$.data.step_details.type=="tool_calls"){if(i(this,s1,"f"))this._emit("toolCallDone",i(this,s1,"f")),a1(this,s1,void 0,"f")}this._emit("runStepDone",$.data,Y);break;case"thread.run.step.in_progress":break}},ZH=function W($){i(this,L5,"f").push($),this._emit("event",$)},NH=function W($){switch($.event){case"thread.run.step.created":return i(this,hW,"f")[$.data.id]=$.data,$.data;case"thread.run.step.delta":let Y=i(this,hW,"f")[$.data.id];if(!Y)throw Error("Received a RunStepDelta before creation of a snapshot");let X=$.data;if(X.delta){let G=e1.accumulateDelta(Y,X.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")},RH=function W($,Y){let X=[];switch($.event){case"thread.message.created":return[$.data,X];case"thread.message.delta":if(!Y)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 Y.content){let H=Y.content[J.index];Y.content[J.index]=i(this,D1,"m",BH).call(this,J,H)}else Y.content[J.index]=J,X.push(J);return[Y,X];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Y)return[Y,X];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},BH=function W($,Y){return e1.accumulateDelta(Y,$)},SH=function W($){switch(a1(this,aY,$.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(a1(this,Q2,$.data,"f"),i(this,s1,"f"))this._emit("toolCallDone",i(this,s1,"f")),a1(this,s1,void 0,"f");break;case"thread.run.cancelling":break}};function VV(W){}class a2 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,$,Y){return this._client.post(`/assistants/${W}`,{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W={},$){if(Q0(W))return this.list({},W);return this._client.getAPIList("/assistants",h4,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class h4 extends A0{}a2.AssistantsPage=h4;function Z5(W){return typeof W.parse==="function"}var k$=(W)=>{return W?.role==="assistant"},N5=(W)=>{return W?.role==="function"},R5=(W)=>{return W?.role==="tool"};function g4(W){return W?.$brand==="auto-parseable-response-format"}function _2(W){return W?.$brand==="auto-parseable-tool"}function qH(W,$){if(!$||!B5($))return{...W,choices:W.choices.map((Y)=>({...Y,message:{...Y.message,parsed:null,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls}:void 0}}))};return m4(W,$)}function m4(W,$){let Y=W.choices.map((X)=>{if(X.finish_reason==="length")throw new Z4;if(X.finish_reason==="content_filter")throw new N4;return{...X,message:{...X.message,...X.message.tool_calls?{tool_calls:X.message.tool_calls?.map((G)=>EV($,G))??void 0}:void 0,parsed:X.message.content&&!X.message.refusal?KV($,X.message.content):null}}});return{...W,choices:Y}}function KV(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 EV(W,$){let Y=W.tools?.find((X)=>X.function?.name===$.function.name);return{...$,function:{...$.function,parsed_arguments:_2(Y)?Y.$parseRaw($.function.arguments):Y?.function.strict?JSON.parse($.function.arguments):null}}}function CH(W,$){if(!W)return!1;let Y=W.tools?.find((X)=>X.function?.name===$.function.name);return _2(Y)||Y?.function.strict||!1}function B5(W){if(g4(W.response_format))return!0;return W.tools?.some(($)=>_2($)||$.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,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},Z1,S5,eY,q5,C5,k5,IH,j5,jH=10;class p4 extends H2{constructor(){super(...arguments);Z1.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),(N5(W)||R5(W))&&W.content)this._emit("functionCallResult",W.content);else if(k$(W)&&W.function_call)this._emit("functionCall",W.function_call);else if(k$(W)&&W.tool_calls){for(let Y of W.tool_calls)if(Y.type==="function")this._emit("functionCall",Y.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,Z1,"m",S5).call(this)}async finalMessage(){return await this.done(),h1(this,Z1,"m",eY).call(this)}async finalFunctionCall(){return await this.done(),h1(this,Z1,"m",q5).call(this)}async finalFunctionCallResult(){return await this.done(),h1(this,Z1,"m",C5).call(this)}async totalUsage(){return await this.done(),h1(this,Z1,"m",k5).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let W=this._chatCompletions[this._chatCompletions.length-1];if(W)this._emit("finalChatCompletion",W);let $=h1(this,Z1,"m",eY).call(this);if($)this._emit("finalMessage",$);let Y=h1(this,Z1,"m",S5).call(this);if(Y)this._emit("finalContent",Y);let X=h1(this,Z1,"m",q5).call(this);if(X)this._emit("finalFunctionCall",X);let G=h1(this,Z1,"m",C5).call(this);if(G!=null)this._emit("finalFunctionCallResult",G);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",h1(this,Z1,"m",k5).call(this))}async _createChatCompletion(W,$,Y){let X=Y?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}h1(this,Z1,"m",IH).call(this,$);let G=await W.chat.completions.create({...$,stream:!1},{...Y,signal:this.controller.signal});return this._connected(),this._addChatCompletion(m4(G,$))}async _runChatCompletion(W,$,Y){for(let X of $.messages)this._addMessage(X,!1);return await this._createChatCompletion(W,$,Y)}async _runFunctions(W,$,Y){let{function_call:G="auto",stream:J,...H}=$,T=typeof G!=="string"&&G?.name,{maxChatCompletions:Q=jH}=Y||{},_={};for(let F of $.functions)_[F.name||F.function.name]=F;let z=$.functions.map((F)=>({name:F.name||F.function.name,parameters:F.parameters,description:F.description}));for(let F of $.messages)this._addMessage(F,!1);for(let F=0;F<Q;++F){let O=(await this._createChatCompletion(W,{...H,function_call:G,functions:z,messages:[...this.messages]},Y)).choices[0]?.message;if(!O)throw new o("missing message in ChatCompletion response");if(!O.function_call)return;let{name:V,arguments:E}=O.function_call,I=_[V];if(!I){let P=`Invalid function_call: ${JSON.stringify(V)}. Available options are: ${z.map((g)=>JSON.stringify(g.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:V,content:P});continue}else if(T&&T!==V){let P=`Invalid function_call: ${JSON.stringify(V)}. ${JSON.stringify(T)} requested. Please try again`;this._addMessage({role:"function",name:V,content:P});continue}let j;try{j=Z5(I)?await I.parse(E):E}catch(P){this._addMessage({role:"function",name:V,content:P instanceof Error?P.message:String(P)});continue}let N=await I.function(j,this),B=h1(this,Z1,"m",j5).call(this,N);if(this._addMessage({role:"function",name:V,content:B}),T)return}}async _runTools(W,$,Y){let{tool_choice:G="auto",stream:J,...H}=$,T=typeof G!=="string"&&G?.function?.name,{maxChatCompletions:Q=jH}=Y||{},_=$.tools.map((w)=>{if(_2(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}),z={};for(let w of _)if(w.type==="function")z[w.function.name||w.function.function.name]=w.function;let F="tools"in $?_.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<Q;++w){let V=(await this._createChatCompletion(W,{...H,tool_choice:G,tools:F,messages:[...this.messages]},Y)).choices[0]?.message;if(!V)throw new o("missing message in ChatCompletion response");if(!V.tool_calls?.length)return;for(let E of V.tool_calls){if(E.type!=="function")continue;let I=E.id,{name:j,arguments:N}=E.function,B=z[j];if(!B){let p=`Invalid tool_call: ${JSON.stringify(j)}. Available options are: ${Object.keys(z).map((w0)=>JSON.stringify(w0)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:p});continue}else if(T&&T!==j){let p=`Invalid tool_call: ${JSON.stringify(j)}. ${JSON.stringify(T)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:p});continue}let P;try{P=Z5(B)?await B.parse(N):N}catch(p){let w0=p instanceof Error?p.message:String(p);this._addMessage({role:"tool",tool_call_id:I,content:w0});continue}let g=await B.function(P,this),x=h1(this,Z1,"m",j5).call(this,g);if(this._addMessage({role:"tool",tool_call_id:I,content:x}),T)return}}return}}Z1=new WeakSet,S5=function W(){return h1(this,Z1,"m",eY).call(this).content??null},eY=function W(){let $=this.messages.length;while($-- >0){let Y=this.messages[$];if(k$(Y)){let{function_call:X,...G}=Y,J={...G,content:Y.content??null,refusal:Y.refusal??null};if(X)J.function_call=X;return J}}throw new o("stream ended without producing a ChatCompletionMessage with role=assistant")},q5=function W(){for(let $=this.messages.length-1;$>=0;$--){let Y=this.messages[$];if(k$(Y)&&Y?.function_call)return Y.function_call;if(k$(Y)&&Y?.tool_calls?.length)return Y.tool_calls.at(-1)?.function}return},C5=function W(){for(let $=this.messages.length-1;$>=0;$--){let Y=this.messages[$];if(N5(Y)&&Y.content!=null)return Y.content;if(R5(Y)&&Y.content!=null&&typeof Y.content==="string"&&this.messages.some((X)=>X.role==="assistant"&&X.tool_calls?.some((G)=>G.type==="function"&&G.id===Y.tool_call_id)))return Y.content}return},k5=function W(){let $={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Y}of this._chatCompletions)if(Y)$.completion_tokens+=Y.completion_tokens,$.prompt_tokens+=Y.prompt_tokens,$.total_tokens+=Y.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.")},j5=function W($){return typeof $==="string"?$:$===void 0?"undefined":JSON.stringify($)};class s2 extends p4{static runFunctions(W,$,Y){let X=new s2,G={...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return X._run(()=>X._runFunctions(W,$,G)),X}static runTools(W,$,Y){let X=new s2,G={...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"runTools"}};return X._run(()=>X._runTools(W,$,G)),X}_addMessage(W,$=!0){if(super._addMessage(W,$),k$(W)&&W.content)this._emit("content",W.content)}}var F1={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 AV(W,$=F1.ALL){if(typeof W!=="string")throw new TypeError(`expecting str, got ${typeof W}`);if(!W.trim())throw new Error(`${W} is empty`);return LV(W.trim(),$)}var LV=(W,$)=>{let Y=W.length,X=0,G=(w)=>{throw new PH(`${w} at position ${X}`)},J=(w)=>{throw new fH(`${w} at position ${X}`)},H=()=>{if(F(),X>=Y)G("Unexpected end of input");if(W[X]==='"')return T();if(W[X]==="{")return Q();if(W[X]==="[")return _();if(W.substring(X,X+4)==="null"||F1.NULL&$&&Y-X<4&&"null".startsWith(W.substring(X)))return X+=4,null;if(W.substring(X,X+4)==="true"||F1.BOOL&$&&Y-X<4&&"true".startsWith(W.substring(X)))return X+=4,!0;if(W.substring(X,X+5)==="false"||F1.BOOL&$&&Y-X<5&&"false".startsWith(W.substring(X)))return X+=5,!1;if(W.substring(X,X+8)==="Infinity"||F1.INFINITY&$&&Y-X<8&&"Infinity".startsWith(W.substring(X)))return X+=8,1/0;if(W.substring(X,X+9)==="-Infinity"||F1.MINUS_INFINITY&$&&1<Y-X&&Y-X<9&&"-Infinity".startsWith(W.substring(X)))return X+=9,-1/0;if(W.substring(X,X+3)==="NaN"||F1.NAN&$&&Y-X<3&&"NaN".startsWith(W.substring(X)))return X+=3,NaN;return z()},T=()=>{let w=X,O=!1;X++;while(X<Y&&(W[X]!=='"'||O&&W[X-1]==="\\"))O=W[X]==="\\"?!O:!1,X++;if(W.charAt(X)=='"')try{return JSON.parse(W.substring(w,++X-Number(O)))}catch(V){J(String(V))}else if(F1.STR&$)try{return JSON.parse(W.substring(w,X-Number(O))+'"')}catch(V){return JSON.parse(W.substring(w,W.lastIndexOf("\\"))+'"')}G("Unterminated string literal")},Q=()=>{X++,F();let w={};try{while(W[X]!=="}"){if(F(),X>=Y&&F1.OBJ&$)return w;let O=T();F(),X++;try{let V=H();Object.defineProperty(w,O,{value:V,writable:!0,enumerable:!0,configurable:!0})}catch(V){if(F1.OBJ&$)return w;else throw V}if(F(),W[X]===",")X++}}catch(O){if(F1.OBJ&$)return w;else G("Expected '}' at end of object")}return X++,w},_=()=>{X++;let w=[];try{while(W[X]!=="]")if(w.push(H()),F(),W[X]===",")X++}catch(O){if(F1.ARR&$)return w;G("Expected ']' at end of array")}return X++,w},z=()=>{if(X===0){if(W==="-"&&F1.NUM&$)G("Not sure what '-' is");try{return JSON.parse(W)}catch(O){if(F1.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(V){}J(String(O))}}let w=X;if(W[X]==="-")X++;while(W[X]&&!",]}".includes(W[X]))X++;if(X==Y&&!(F1.NUM&$))G("Unterminated number literal");try{return JSON.parse(W.substring(w,X))}catch(O){if(W.substring(w,X)==="-"&&F1.NUM&$)G("Not sure what '-' is");try{return JSON.parse(W.substring(w,W.lastIndexOf("e")))}catch(V){J(String(V))}}},F=()=>{while(X<Y&&`
|
|
42
|
-
\r `.includes(
|
|
43
|
-
${
|
|
44
|
-
${
|
|
45
|
-
${
|
|
46
|
-
${YX(W)}`);return{...w0,id:p,type:x,function:{...M0,name:Z,arguments:p0}}})}};return{...O,message:{...j,content:V,role:N,refusal:_.refusal??null},finish_reason:z,index:F,logprobs:w}}),created:G,model:J,object:"chat.completion",...H?{system_fingerprint:H}:{}};return qH(Q,$)}function YX(W){return JSON.stringify(W)}function xH(W){return}function vH(W){}class F2 extends z2{static fromReadableStream(W){let $=new F2(null);return $._run(()=>$._fromReadableStream(W)),$}static runFunctions(W,$,Y){let X=new F2(null),G={...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return X._run(()=>X._runFunctions(W,$,G)),X}static runTools(W,$,Y){let X=new F2($),G={...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"runTools"}};return X._run(()=>X._runTools(W,$,G)),X}}class XX 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((Y)=>m4(Y,W))}runFunctions(W,$){if(W.stream)return F2.runFunctions(this._client,W,$);return s2.runFunctions(this._client,W,$)}runTools(W,$){if(W.stream)return F2.runTools(this._client,W,$);return s2.runTools(this._client,W,$)}stream(W,$){return z2.createChatCompletion(this._client,W,$)}}class u4 extends C{constructor(){super(...arguments);this.completions=new XX(this._client)}}(function(W){W.Completions=XX})(u4||(u4={}));class c4 extends C{create(W,$){return this._client.post("/realtime/sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class d4 extends C{create(W,$){return this._client.post("/realtime/transcription_sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class w2 extends C{constructor(){super(...arguments);this.sessions=new c4(this._client),this.transcriptionSessions=new d4(this._client)}}w2.Sessions=c4;w2.TranscriptionSessions=d4;class $8 extends C{create(W,$,Y){return this._client.post(`/threads/${W}/messages`,{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}retrieve(W,$,Y){return this._client.get(`/threads/${W}/messages/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}update(W,$,Y,X){return this._client.post(`/threads/${W}/messages/${$}`,{body:Y,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/messages`,l4,{query:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}del(W,$,Y){return this._client.delete(`/threads/${W}/messages/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}class l4 extends A0{}$8.MessagesPage=l4;class Y8 extends C{retrieve(W,$,Y,X={},G){if(Q0(X))return this.retrieve(W,$,Y,{},X);return this._client.get(`/threads/${W}/runs/${$}/steps/${Y}`,{query:X,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}list(W,$,Y={},X){if(Q0(Y))return this.list(W,$,{},Y);return this._client.getAPIList(`/threads/${W}/runs/${$}/steps`,o4,{query:Y,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class o4 extends A0{}Y8.RunStepsPage=o4;class I$ extends C{constructor(){super(...arguments);this.steps=new Y8(this._client)}create(W,$,Y){let{include:X,...G}=$;return this._client.post(`/threads/${W}/runs`,{query:{include:X},body:G,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers},stream:$.stream??!1})}retrieve(W,$,Y){return this._client.get(`/threads/${W}/runs/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}update(W,$,Y,X){return this._client.post(`/threads/${W}/runs/${$}`,{body:Y,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/runs`,i4,{query:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}cancel(W,$,Y){return this._client.post(`/threads/${W}/runs/${$}/cancel`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}async createAndPoll(W,$,Y){let X=await this.create(W,$,Y);return await this.poll(W,X.id,Y)}createAndStream(W,$,Y){return e1.createAssistantStream(W,this._client.beta.threads.runs,$,Y)}async poll(W,$,Y){let X={...Y?.headers,"X-Stainless-Poll-Helper":"true"};if(Y?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=Y.pollIntervalMs.toString();while(!0){let{data:G,response:J}=await this.retrieve(W,$,{...Y,headers:{...Y?.headers,...X}}).withResponse();switch(G.status){case"queued":case"in_progress":case"cancelling":let H=5000;if(Y?.pollIntervalMs)H=Y.pollIntervalMs;else{let T=J.headers.get("openai-poll-after-ms");if(T){let Q=parseInt(T);if(!isNaN(Q))H=Q}}await aW(H);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return G}}}stream(W,$,Y){return e1.createAssistantStream(W,this._client.beta.threads.runs,$,Y)}submitToolOutputs(W,$,Y,X){return this._client.post(`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:Y,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers},stream:Y.stream??!1})}async submitToolOutputsAndPoll(W,$,Y,X){let G=await this.submitToolOutputs(W,$,Y,X);return await this.poll(W,G.id,X)}submitToolOutputsStream(W,$,Y,X){return e1.createToolAssistantStream(W,$,this._client.beta.threads.runs,Y,X)}}class i4 extends A0{}I$.RunsPage=i4;I$.Steps=Y8;I$.RunStepsPage=o4;class Y$ extends C{constructor(){super(...arguments);this.runs=new I$(this._client),this.messages=new $8(this._client)}create(W={},$){if(Q0(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,$,Y){return this._client.post(`/threads/${W}`,{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.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 Y=await this.createAndRun(W,$);return await this.runs.poll(Y.thread_id,Y.id,$)}createAndRunStream(W,$){return e1.createThreadAssistantStream(W,this._client.beta.threads,$)}}Y$.Runs=I$;Y$.RunsPage=i4;Y$.Messages=$8;Y$.MessagesPage=l4;class gW extends C{constructor(){super(...arguments);this.realtime=new w2(this._client),this.chat=new u4(this._client),this.assistants=new a2(this._client),this.threads=new Y$(this._client)}}gW.Realtime=w2;gW.Assistants=a2;gW.AssistantsPage=h4;gW.Threads=Y$;class X8 extends C{create(W,$){return this._client.post("/completions",{body:W,...$,stream:W.stream??!1})}}class G8 extends C{create(W,$){let Y=!!W.encoding_format,X=Y?W.encoding_format:"base64";if(Y)tW("Request","User defined encoding_format:",W.encoding_format);let G=this._client.post("/embeddings",{body:{...W,encoding_format:X},...$});if(Y)return G;return tW("response","Decoding base64 embeddings to float32 array"),G._thenUnwrap((J)=>{if(J&&J.data)J.data.forEach((H)=>{let T=H.embedding;H.embedding=KH(T)});return J})}}class J8 extends C{retrieve(W,$,Y,X){return this._client.get(`/evals/${W}/runs/${$}/output_items/${Y}`,X)}list(W,$,Y={},X){if(Q0(Y))return this.list(W,$,{},Y);return this._client.getAPIList(`/evals/${W}/runs/${$}/output_items`,n4,{query:Y,...X})}}class n4 extends A0{}J8.OutputItemListResponsesPage=n4;class P$ extends C{constructor(){super(...arguments);this.outputItems=new J8(this._client)}create(W,$,Y){return this._client.post(`/evals/${W}/runs`,{body:$,...Y})}retrieve(W,$,Y){return this._client.get(`/evals/${W}/runs/${$}`,Y)}list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/evals/${W}/runs`,r4,{query:$,...Y})}del(W,$,Y){return this._client.delete(`/evals/${W}/runs/${$}`,Y)}cancel(W,$,Y){return this._client.post(`/evals/${W}/runs/${$}`,Y)}}class r4 extends A0{}P$.RunListResponsesPage=r4;P$.OutputItems=J8;P$.OutputItemListResponsesPage=n4;class X$ extends C{constructor(){super(...arguments);this.runs=new P$(this._client)}create(W,$){return this._client.post("/evals",{body:W,...$})}retrieve(W,$){return this._client.get(`/evals/${W}`,$)}update(W,$,Y){return this._client.post(`/evals/${W}`,{body:$,...Y})}list(W={},$){if(Q0(W))return this.list({},W);return this._client.getAPIList("/evals",H8,{query:W,...$})}del(W,$){return this._client.delete(`/evals/${W}`,$)}}class H8 extends A0{}X$.EvalListResponsesPage=H8;X$.Runs=P$;X$.RunListResponsesPage=r4;class U2 extends C{create(W,$){return this._client.post("/files",JW({body:W,...$}))}retrieve(W,$){return this._client.get(`/files/${W}`,$)}list(W={},$){if(Q0(W))return this.list({},W);return this._client.getAPIList("/files",T8,{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:Y=1800000}={}){let X=new Set(["processed","error","deleted"]),G=Date.now(),J=await this.retrieve(W);while(!J.status||!X.has(J.status))if(await aW($),J=await this.retrieve(W),Date.now()-G>Y)throw new $2({message:`Giving up on waiting for file ${W} to finish processing after ${Y} milliseconds.`});return J}}class T8 extends A0{}U2.FileObjectsPage=T8;class t4 extends C{}class a4 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 Q8 extends C{constructor(){super(...arguments);this.graders=new a4(this._client)}}Q8.Graders=a4;class _8 extends C{create(W,$,Y){return this._client.getAPIList(`/fine_tuning/checkpoints/${W}/permissions`,s4,{body:$,method:"post",...Y})}retrieve(W,$={},Y){if(Q0($))return this.retrieve(W,{},$);return this._client.get(`/fine_tuning/checkpoints/${W}/permissions`,{query:$,...Y})}del(W,$,Y){return this._client.delete(`/fine_tuning/checkpoints/${W}/permissions/${$}`,Y)}}class s4 extends sW{}_8.PermissionCreateResponsesPage=s4;class D2 extends C{constructor(){super(...arguments);this.permissions=new _8(this._client)}}D2.Permissions=_8;D2.PermissionCreateResponsesPage=s4;class z8 extends C{list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/checkpoints`,e4,{query:$,...Y})}}class e4 extends A0{}z8.FineTuningJobCheckpointsPage=e4;class G$ extends C{constructor(){super(...arguments);this.checkpoints=new z8(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(Q0(W))return this.list({},W);return this._client.getAPIList("/fine_tuning/jobs",W6,{query:W,...$})}cancel(W,$){return this._client.post(`/fine_tuning/jobs/${W}/cancel`,$)}listEvents(W,$={},Y){if(Q0($))return this.listEvents(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/events`,$6,{query:$,...Y})}pause(W,$){return this._client.post(`/fine_tuning/jobs/${W}/pause`,$)}resume(W,$){return this._client.post(`/fine_tuning/jobs/${W}/resume`,$)}}class W6 extends A0{}class $6 extends A0{}G$.FineTuningJobsPage=W6;G$.FineTuningJobEventsPage=$6;G$.Checkpoints=z8;G$.FineTuningJobCheckpointsPage=e4;class HW extends C{constructor(){super(...arguments);this.methods=new t4(this._client),this.jobs=new G$(this._client),this.checkpoints=new D2(this._client),this.alpha=new Q8(this._client)}}HW.Methods=t4;HW.Jobs=G$;HW.FineTuningJobsPage=W6;HW.FineTuningJobEventsPage=$6;HW.Checkpoints=D2;HW.Alpha=Q8;class Y6 extends C{}class M2 extends C{constructor(){super(...arguments);this.graderModels=new Y6(this._client)}}M2.GraderModels=Y6;class F8 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 V2 extends C{retrieve(W,$){return this._client.get(`/models/${W}`,$)}list(W){return this._client.getAPIList("/models",w8,W)}del(W,$){return this._client.delete(`/models/${W}`,$)}}class w8 extends sW{}V2.ModelsPage=w8;class U8 extends C{create(W,$){return this._client.post("/moderations",{body:W,...$})}}function yH(W,$){if(!$||!cV($))return{...W,output_parsed:null,output:W.output.map((Y)=>{if(Y.type==="function_call")return{...Y,parsed_arguments:null};if(Y.type==="message")return{...Y,content:Y.content.map((X)=>({...X,parsed:null}))};else return Y})};return y5(W,$)}function y5(W,$){let Y=W.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:oV($,G)};if(G.type==="message"){let J=G.content.map((H)=>{if(H.type==="output_text")return{...H,parsed:uV($,H.text)};return H});return{...G,content:J}}return G}),X=Object.assign({},W,{output:Y});if(!Object.getOwnPropertyDescriptor(W,"output_text"))h5(X);return Object.defineProperty(X,"output_parsed",{enumerable:!0,get(){for(let G of X.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}}),X}function uV(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 cV(W){if(g4(W.text?.format))return!0;return!1}function dV(W){return W?.$brand==="auto-parseable-tool"}function lV(W,$){return W.find((Y)=>Y.type==="function"&&Y.name===$)}function oV(W,$){let Y=lV(W.tools??[],$.name);return{...$,...$,parsed_arguments:dV(Y)?Y.$parseRaw($.arguments):Y?.strict?JSON.parse($.arguments):null}}function h5(W){let $=[];for(let Y of W.output){if(Y.type!=="message")continue;for(let X of Y.content)if(X.type==="output_text")$.push(X.text)}W.output_text=$.join("")}class X6 extends C{list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/responses/${W}/input_items`,g5,{query:$,...Y})}}var D8=function(W,$,Y,X,G){if(X==="m")throw new TypeError("Private method is not writable");if(X==="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 X==="a"?G.call(W,Y):G?G.value=Y:$.set(W,Y),Y},f$=function(W,$,Y,X){if(Y==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!X:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(W):X?X.value:$.get(W)},M8,GX,b$,JX,hH,gH,mH,pH;class HX extends H2{constructor(W){super();M8.add(this),GX.set(this,void 0),b$.set(this,void 0),JX.set(this,void 0),D8(this,GX,W,"f")}static createResponse(W,$,Y){let X=new HX($);return X._run(()=>X._createResponse(W,$,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createResponse(W,$,Y){let X=Y?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}f$(this,M8,"m",hH).call(this);let G=await W.responses.create({...$,stream:!0},{...Y,signal:this.controller.signal});this._connected();for await(let J of G)f$(this,M8,"m",gH).call(this,J);if(G.controller.signal?.aborted)throw new G1;return f$(this,M8,"m",mH).call(this)}[(GX=new WeakMap,b$=new WeakMap,JX=new WeakMap,M8=new WeakSet,hH=function W(){if(this.ended)return;D8(this,b$,void 0,"f")},gH=function W($){if(this.ended)return;let Y=f$(this,M8,"m",pH).call(this,$);switch(this._emit("event",$),$.type){case"response.output_text.delta":{let X=Y.output[$.output_index];if(!X)throw new o(`missing output at index ${$.output_index}`);if(X.type==="message"){let G=X.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 X=Y.output[$.output_index];if(!X)throw new o(`missing output at index ${$.output_index}`);if(X.type==="function_call")this._emit("response.function_call_arguments.delta",{...$,snapshot:X.arguments});break}default:this._emit($.type,$);break}},mH=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=f$(this,b$,"f");if(!$)throw new o("request ended without sending any events");D8(this,b$,void 0,"f");let Y=nV($,f$(this,GX,"f"));return D8(this,JX,Y,"f"),Y},pH=function W($){let Y=f$(this,b$,"f");if(!Y){if($.type!=="response.created")throw new o(`When snapshot hasn't been set yet, expected 'response.created' event, got ${$.type}`);return Y=D8(this,b$,$.response,"f"),Y}switch($.type){case"response.output_item.added":{Y.output.push($.item);break}case"response.content_part.added":{let X=Y.output[$.output_index];if(!X)throw new o(`missing output at index ${$.output_index}`);if(X.type==="message")X.content.push($.part);break}case"response.output_text.delta":{let X=Y.output[$.output_index];if(!X)throw new o(`missing output at index ${$.output_index}`);if(X.type==="message"){let G=X.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 X=Y.output[$.output_index];if(!X)throw new o(`missing output at index ${$.output_index}`);if(X.type==="function_call")X.arguments+=$.delta;break}case"response.completed":{D8(this,b$,$.response,"f");break}}return Y},Symbol.asyncIterator)](){let W=[],$=[],Y=!1;return this.on("event",(X)=>{let G=$.shift();if(G)G.resolve(X);else W.push(X)}),this.on("end",()=>{Y=!0;for(let X of $)X.resolve(void 0);$.length=0}),this.on("abort",(X)=>{Y=!0;for(let G of $)G.reject(X);$.length=0}),this.on("error",(X)=>{Y=!0;for(let G of $)G.reject(X);$.length=0}),{next:async()=>{if(!W.length){if(Y)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=f$(this,JX,"f");if(!W)throw new o("stream ended without producing a ChatCompletion");return W}}function nV(W,$){return yH(W,$)}class O2 extends C{constructor(){super(...arguments);this.inputItems=new X6(this._client)}create(W,$){return this._client.post("/responses",{body:W,...$,stream:W.stream??!1})._thenUnwrap((Y)=>{if("object"in Y&&Y.object==="response")h5(Y);return Y})}retrieve(W,$={},Y){if(Q0($))return this.retrieve(W,{},$);return this._client.get(`/responses/${W}`,{query:$,...Y})}del(W,$){return this._client.delete(`/responses/${W}`,{...$,headers:{Accept:"*/*",...$?.headers}})}parse(W,$){return this._client.responses.create(W,$)._thenUnwrap((Y)=>y5(Y,W))}stream(W,$){return HX.createResponse(this._client,W,$)}}class g5 extends A0{}O2.InputItems=X6;class G6 extends C{create(W,$,Y){return this._client.post(`/uploads/${W}/parts`,JW({body:$,...Y}))}}class K2 extends C{constructor(){super(...arguments);this.parts=new G6(this._client)}create(W,$){return this._client.post("/uploads",{body:W,...$})}cancel(W,$){return this._client.post(`/uploads/${W}/cancel`,$)}complete(W,$,Y){return this._client.post(`/uploads/${W}/complete`,{body:$,...Y})}}K2.Parts=G6;var uH=async(W)=>{let $=await Promise.allSettled(W),Y=$.filter((G)=>G.status==="rejected");if(Y.length){for(let G of Y)console.error(G.reason);throw new Error(`${Y.length} promise(s) failed - see the above errors`)}let X=[];for(let G of $)if(G.status==="fulfilled")X.push(G.value);return X};class E2 extends C{create(W,$,Y){return this._client.post(`/vector_stores/${W}/files`,{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}retrieve(W,$,Y){return this._client.get(`/vector_stores/${W}/files/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}update(W,$,Y,X){return this._client.post(`/vector_stores/${W}/files/${$}`,{body:Y,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W,$={},Y){if(Q0($))return this.list(W,{},$);return this._client.getAPIList(`/vector_stores/${W}/files`,A2,{query:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}del(W,$,Y){return this._client.delete(`/vector_stores/${W}/files/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}async createAndPoll(W,$,Y){let X=await this.create(W,$,Y);return await this.poll(W,X.id,Y)}async poll(W,$,Y){let X={...Y?.headers,"X-Stainless-Poll-Helper":"true"};if(Y?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=Y.pollIntervalMs.toString();while(!0){let G=await this.retrieve(W,$,{...Y,headers:X}).withResponse(),J=G.data;switch(J.status){case"in_progress":let H=5000;if(Y?.pollIntervalMs)H=Y.pollIntervalMs;else{let T=G.response.headers.get("openai-poll-after-ms");if(T){let Q=parseInt(T);if(!isNaN(Q))H=Q}}await aW(H);break;case"failed":case"completed":return J}}}async upload(W,$,Y){let X=await this._client.files.create({file:$,purpose:"assistants"},Y);return this.create(W,{file_id:X.id},Y)}async uploadAndPoll(W,$,Y){let X=await this.upload(W,$,Y);return await this.poll(W,X.id,Y)}content(W,$,Y){return this._client.getAPIList(`/vector_stores/${W}/files/${$}/content`,J6,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}class A2 extends A0{}class J6 extends sW{}E2.VectorStoreFilesPage=A2;E2.FileContentResponsesPage=J6;class H6 extends C{create(W,$,Y){return this._client.post(`/vector_stores/${W}/file_batches`,{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}retrieve(W,$,Y){return this._client.get(`/vector_stores/${W}/file_batches/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}cancel(W,$,Y){return this._client.post(`/vector_stores/${W}/file_batches/${$}/cancel`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}async createAndPoll(W,$,Y){let X=await this.create(W,$);return await this.poll(W,X.id,Y)}listFiles(W,$,Y={},X){if(Q0(Y))return this.listFiles(W,$,{},Y);return this._client.getAPIList(`/vector_stores/${W}/file_batches/${$}/files`,A2,{query:Y,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async poll(W,$,Y){let X={...Y?.headers,"X-Stainless-Poll-Helper":"true"};if(Y?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=Y.pollIntervalMs.toString();while(!0){let{data:G,response:J}=await this.retrieve(W,$,{...Y,headers:X}).withResponse();switch(G.status){case"in_progress":let H=5000;if(Y?.pollIntervalMs)H=Y.pollIntervalMs;else{let T=J.headers.get("openai-poll-after-ms");if(T){let Q=parseInt(T);if(!isNaN(Q))H=Q}}await aW(H);break;case"failed":case"cancelled":case"completed":return G}}}async uploadAndPoll(W,{files:$,fileIds:Y=[]},X){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=X?.maxConcurrency??5,J=Math.min(G,$.length),H=this._client,T=$.values(),Q=[...Y];async function _(F){for(let w of F){let O=await H.files.create({file:w,purpose:"assistants"},X);Q.push(O.id)}}let z=Array(J).fill(T).map(_);return await uH(z),await this.createAndPoll(W,{file_ids:Q})}}class TW extends C{constructor(){super(...arguments);this.files=new E2(this._client),this.fileBatches=new H6(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,$,Y){return this._client.post(`/vector_stores/${W}`,{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W={},$){if(Q0(W))return this.list({},W);return this._client.getAPIList("/vector_stores",V8,{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,$,Y){return this._client.getAPIList(`/vector_stores/${W}/search`,O8,{body:$,method:"post",...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}class V8 extends A0{}class O8 extends sW{}TW.VectorStoresPage=V8;TW.VectorStoreSearchResponsesPage=O8;TW.Files=E2;TW.VectorStoreFilesPage=A2;TW.FileContentResponsesPage=J6;TW.FileBatches=H6;var cH;class H0 extends K5{constructor({baseURL:W=B4("OPENAI_BASE_URL"),apiKey:$=B4("OPENAI_API_KEY"),organization:Y=B4("OPENAI_ORG_ID")??null,project:X=B4("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:Y,project:X,...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.
|
|
61
|
+
${G}`)}let z=K6.join(this.baseDir,`${$}/${T}.output.json`);return JSON.parse(l$.readFileSync(z,"utf-8"))}async write($,T,W,X){let Y=K6.join(this.baseDir,$),U=K6.join(Y,`${T}.input.json`),G=K6.join(Y,`${T}.output.json`),J=JSON.stringify(W,null,"\t");if(!l$.existsSync(this.baseDir))l$.mkdirSync(this.baseDir,{recursive:!0});if(!l$.existsSync(Y))l$.mkdirSync(Y);if(l$.writeFileSync(U,J),l$.existsSync(G))l$.unlinkSync(G);let z=await X(...W),w=JSON.stringify(z,null,"\t");return l$.writeFileSync(G,w),z}add($,T){let W=`${this.rootName}${W4}${iW($)}`;return{flush:()=>{this.flush($)},for:(X)=>{if(this.mode!=="off"){if(this.filesTouched.set($,new Set),P$.storage.initialized&&!P$.storage.getItem(`list${W4}${W}`))P$.storage.setItem(`list${W4}${W}`,"true")}return{get:async(...Y)=>{let U=X;if(this.mode!=="off"){let G=this.filenameCache.get(X);if(!G)G=iW(X),this.filenameCache.set(X,G);U=G,this.filesTouched.get($)?.add(U);let J=`${W}${W4}${U}`,z=`file${W4}${J}`;if(P$.storage.initialized&&!P$.storage.getItem(z))P$.storage.setItem(z,"true")}switch(this.mode){case"off":return T(...Y);case"read":return this.read($,U,Y);case"write":return this.write($,U,Y,T);case"read-write":try{return this.read($,U,Y)}catch(G){if(G instanceof Error)return this.write($,U,Y,T);throw G}}}}}}}flush(...$){console.log(this.filesTouched);for(let[T,W]of this.filesTouched.entries())if($.length===0||$.includes(T)){let X=K6.join(this.baseDir,T),Y=l$.readdirSync(X);for(let U of Y){let G=U.replace(".input.json","").replace(".output.json","");if(!W.has(G))console.info(`\uD83E\uDDF9 Flushing ${G}`),l$.unlinkSync(K6.join(X,U))}}}};var pY="RFC3986",dY={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:($)=>String($)},IF="RFC1738";var ER=Array.isArray,j6=(()=>{let $=[];for(let T=0;T<256;++T)$.push("%"+((T<16?"0":"")+T.toString(16)).toUpperCase());return $})();var Lz=1024,kF=($,T,W,X,Y)=>{if($.length===0)return $;let U=$;if(typeof $==="symbol")U=Symbol.prototype.toString.call($);else if(typeof $!=="string")U=String($);if(W==="iso-8859-1")return escape(U).replace(/%u[0-9a-f]{4}/gi,function(J){return"%26%23"+parseInt(J.slice(2),16)+"%3B"});let G="";for(let J=0;J<U.length;J+=Lz){let z=U.length>=Lz?U.slice(J,J+Lz):U,w=[];for(let H=0;H<z.length;++H){let _=z.charCodeAt(H);if(_===45||_===46||_===95||_===126||_>=48&&_<=57||_>=65&&_<=90||_>=97&&_<=122||Y===IF&&(_===40||_===41)){w[w.length]=z.charAt(H);continue}if(_<128){w[w.length]=j6[_];continue}if(_<2048){w[w.length]=j6[192|_>>6]+j6[128|_&63];continue}if(_<55296||_>=57344){w[w.length]=j6[224|_>>12]+j6[128|_>>6&63]+j6[128|_&63];continue}H+=1,_=65536+((_&1023)<<10|z.charCodeAt(H)&1023),w[w.length]=j6[240|_>>18]+j6[128|_>>12&63]+j6[128|_>>6&63]+j6[128|_&63]}G+=w.join("")}return G};function qF($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function Sz($,T){if(ER($)){let W=[];for(let X=0;X<$.length;X+=1)W.push(T($[X]));return W}return T($)}var MR=Object.prototype.hasOwnProperty,PF={brackets($){return String($)+"[]"},comma:"comma",indices($,T){return String($)+"["+T+"]"},repeat($){return String($)}},x6=Array.isArray,AR=Array.prototype.push,CF=function($,T){AR.apply($,x6(T)?T:[T])},NR=Date.prototype.toISOString,X4={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:kF,encodeValuesOnly:!1,format:pY,formatter:dY[pY],indices:!1,serializeDate($){return NR.call($)},skipNulls:!1,strictNullHandling:!1};function LR($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var Bz={};function vF($,T,W,X,Y,U,G,J,z,w,H,_,F,D,V,E,R,P){let A=$,N=P,k=0,y=!1;while((N=N.get(Bz))!==void 0&&!y){let B=N.get($);if(k+=1,typeof B!=="undefined")if(B===k)throw new RangeError("Cyclic object value");else y=!0;if(typeof N.get(Bz)==="undefined")k=0}if(typeof w==="function")A=w(T,A);else if(A instanceof Date)A=F?.(A);else if(W==="comma"&&x6(A))A=Sz(A,function(B){if(B instanceof Date)return F?.(B);return B});if(A===null){if(U)return z&&!E?z(T,X4.encoder,R,"key",D):T;A=""}if(LR(A)||qF(A)){if(z){let B=E?T:z(T,X4.encoder,R,"key",D);return[V?.(B)+"="+V?.(z(A,X4.encoder,R,"value",D))]}return[V?.(T)+"="+V?.(String(A))]}let x=[];if(typeof A==="undefined")return x;let m;if(W==="comma"&&x6(A)){if(E&&z)A=Sz(A,z);m=[{value:A.length>0?A.join(",")||null:void 0}]}else if(x6(w))m=w;else{let B=Object.keys(A);m=H?B.sort(H):B}let J$=J?String(T).replace(/\./g,"%2E"):String(T),m$=X&&x6(A)&&A.length===1?J$+"[]":J$;if(Y&&x6(A)&&A.length===0)return m$+"[]";for(let B=0;B<m.length;++B){let Z$=m[B],$$=typeof Z$==="object"&&typeof Z$.value!=="undefined"?Z$.value:A[Z$];if(G&&$$===null)continue;let H$=_&&J?Z$.replace(/\./g,"%2E"):Z$,e$=x6(A)?typeof W==="function"?W(m$,H$):m$:m$+(_?"."+H$:"["+H$+"]");P.set($,k);let V4=new WeakMap;V4.set(Bz,P),CF(x,vF($$,e$,W,X,Y,U,G,J,W==="comma"&&E&&x6(A)?null:z,w,H,_,F,D,V,E,R,V4))}return x}function SR($=X4){if(typeof $.allowEmptyArrays!=="undefined"&&typeof $.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys!=="undefined"&&typeof $.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder!=="undefined"&&typeof $.encoder!=="function")throw new TypeError("Encoder has to be a function.");let T=$.charset||X4.charset;if(typeof $.charset!=="undefined"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let W=pY;if(typeof $.format!=="undefined"){if(!MR.call(dY,$.format))throw new TypeError("Unknown format option provided.");W=$.format}let X=dY[W],Y=X4.filter;if(typeof $.filter==="function"||x6($.filter))Y=$.filter;let U;if($.arrayFormat&&$.arrayFormat in PF)U=$.arrayFormat;else if("indices"in $)U=$.indices?"indices":"repeat";else U=X4.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots==="undefined"?!!$.encodeDotInKeys===!0?!0:X4.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:X4.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:X4.allowEmptyArrays,arrayFormat:U,charset:T,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:X4.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter==="undefined"?X4.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:X4.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:X4.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:X4.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:X4.encodeValuesOnly,filter:Y,format:W,formatter:X,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:X4.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:X4.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:X4.strictNullHandling}}function Rz($,T={}){let W=$,X=SR(T),Y,U;if(typeof X.filter==="function")U=X.filter,W=U("",W);else if(x6(X.filter))U=X.filter,Y=U;let G=[];if(typeof W!=="object"||W===null)return"";let J=PF[X.arrayFormat],z=J==="comma"&&X.commaRoundTrip;if(!Y)Y=Object.keys(W);if(X.sort)Y.sort(X.sort);let w=new WeakMap;for(let F=0;F<Y.length;++F){let D=Y[F];if(X.skipNulls&&W[D]===null)continue;CF(G,vF(W[D],D,J,z,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,w))}let H=G.join(X.delimiter),_=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")_+="utf8=%26%2310003%3B&";else _+="utf8=%E2%9C%93&";return H.length>0?_+H:""}var W0="4.103.0";var jF=!1,X0=void 0,Iz=void 0,RR=void 0,IR=void 0,kR=void 0,kz=void 0,qR=void 0,oY=void 0,qz=void 0,Pz=void 0,Cz=void 0,lY=void 0,vz=void 0;function xF($,T={auto:!1}){if(jF)throw new Error(`you must \`import 'openai/shims/${$.kind}'\` before importing anything else from openai`);if(X0)throw new Error(`can't \`import 'openai/shims/${$.kind}'\` after \`import 'openai/shims/${X0}'\``);jF=T.auto,X0=$.kind,Iz=$.fetch,RR=$.Request,IR=$.Response,kR=$.Headers,kz=$.FormData,qR=$.Blob,oY=$.File,qz=$.ReadableStream,Pz=$.getMultipartRequestOptions,Cz=$.getDefaultAgent,lY=$.fileFromPath,vz=$.isFsReadStream}class jz{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}function bF({manuallyImported:$}={}){let T=$?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",W,X,Y,U;try{W=fetch,X=Request,Y=Response,U=Headers}catch(G){throw new Error(`this environment is missing the following Web Fetch API type: ${G.message}. ${T}`)}return{kind:"web",fetch:W,Request:X,Response:Y,Headers:U,FormData:typeof FormData!=="undefined"?FormData:class G{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${T}`)}},Blob:typeof Blob!=="undefined"?Blob:class G{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${T}`)}},File:typeof File!=="undefined"?File:class G{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${T}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class G{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${T}`)}},getMultipartRequestOptions:async(G,J)=>({...J,body:new jz(G)}),getDefaultAgent:(G)=>{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:(G)=>!1}}import{ReadStream as CR}from"fs";function fF(){let $=bF();function T(W){return W instanceof CR}return{...$,isFsReadStream:T}}var xz=()=>{if(!X0)xF(fF(),{auto:!0})};xz();class l extends Error{}class t$ extends l{constructor($,T,W,X){super(`${t$.makeMessage($,T,W)}`);this.status=$,this.headers=X,this.request_id=X?.["x-request-id"],this.error=T;let Y=T;this.code=Y?.code,this.param=Y?.param,this.type=Y?.type}static makeMessage($,T,W){let X=T?.message?typeof T.message==="string"?T.message:JSON.stringify(T.message):T?JSON.stringify(T):W;if($&&X)return`${$} ${X}`;if($)return`${$} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate($,T,W,X){if(!$||!X)return new Y0({message:W,cause:T8(T)});let Y=T?.error;if($===400)return new rY($,Y,W,X);if($===401)return new iY($,Y,W,X);if($===403)return new nY($,Y,W,X);if($===404)return new tY($,Y,W,X);if($===409)return new aY($,Y,W,X);if($===422)return new sY($,Y,W,X);if($===429)return new eY($,Y,W,X);if($>=500)return new $8($,Y,W,X);return new t$($,Y,W,X)}}class Y4 extends t${constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class Y0 extends t${constructor({message:$,cause:T}){super(void 0,void 0,$||"Connection error.",void 0);if(T)this.cause=T}}class U0 extends Y0{constructor({message:$}={}){super({message:$??"Request timed out."})}}class rY extends t${}class iY extends t${}class nY extends t${}class tY extends t${}class aY extends t${}class sY extends t${}class eY extends t${}class $8 extends t${}class nW extends l{constructor(){super("Could not parse response content as the length limit was reached")}}class tW extends l{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var W8=function($,T,W,X,Y){if(X==="m")throw new TypeError("Private method is not writable");if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?$!==T||!Y:!T.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?Y.call($,W):Y?Y.value=W:T.set($,W),W},G0=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},t4;class $T{constructor(){t4.set(this,void 0),this.buffer=new Uint8Array,W8(this,t4,null,"f")}decode($){if($==null)return[];let T=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,W=new Uint8Array(this.buffer.length+T.length);W.set(this.buffer),W.set(T,this.buffer.length),this.buffer=W;let X=[],Y;while((Y=jR(this.buffer,G0(this,t4,"f")))!=null){if(Y.carriage&&G0(this,t4,"f")==null){W8(this,t4,Y.index,"f");continue}if(G0(this,t4,"f")!=null&&(Y.index!==G0(this,t4,"f")+1||Y.carriage)){X.push(this.decodeText(this.buffer.slice(0,G0(this,t4,"f")-1))),this.buffer=this.buffer.slice(G0(this,t4,"f")),W8(this,t4,null,"f");continue}let U=G0(this,t4,"f")!==null?Y.preceding-1:Y.preceding,G=this.decodeText(this.buffer.slice(0,U));X.push(G),this.buffer=this.buffer.slice(Y.index),W8(this,t4,null,"f")}return X}decodeText($){if($==null)return"";if(typeof $==="string")return $;if(typeof Buffer!=="undefined"){if($ instanceof Buffer)return $.toString();if($ instanceof Uint8Array)return Buffer.from($).toString();throw new l(`Unexpected: received non-Uint8Array (${$.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($ instanceof Uint8Array||$ instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode($);throw new l(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new l("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
|
|
62
|
+
`)}}t4=new WeakMap;$T.NEWLINE_CHARS=new Set([`
|
|
63
|
+
`,"\r"]);$T.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jR($,T){for(let Y=T??0;Y<$.length;Y++){if($[Y]===10)return{preceding:Y,index:Y+1,carriage:!1};if($[Y]===13)return{preceding:Y,index:Y+1,carriage:!0}}return null}function yF($){for(let X=0;X<$.length-1;X++){if($[X]===10&&$[X+1]===10)return X+2;if($[X]===13&&$[X+1]===13)return X+2;if($[X]===13&&$[X+1]===10&&X+3<$.length&&$[X+2]===13&&$[X+3]===10)return X+4}return-1}function bz($){if($[Symbol.asyncIterator])return $;let T=$.getReader();return{async next(){try{let W=await T.read();if(W?.done)T.releaseLock();return W}catch(W){throw T.releaseLock(),W}},async return(){let W=T.cancel();return T.releaseLock(),await W,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class a4{constructor($,T){this.iterator=$,this.controller=T}static fromSSEResponse($,T){let W=!1;async function*X(){if(W)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let Y=!1;try{for await(let U of xR($,T)){if(Y)continue;if(U.data.startsWith("[DONE]")){Y=!0;continue}if(U.event===null||U.event.startsWith("response.")||U.event.startsWith("transcript.")){let G;try{G=JSON.parse(U.data)}catch(J){throw console.error("Could not parse message into JSON:",U.data),console.error("From chunk:",U.raw),J}if(G&&G.error)throw new t$(void 0,G.error,void 0,fz($.headers));yield G}else{let G;try{G=JSON.parse(U.data)}catch(J){throw console.error("Could not parse message into JSON:",U.data),console.error("From chunk:",U.raw),J}if(U.event=="error")throw new t$(void 0,G.error,G.message,void 0);yield{event:U.event,data:G}}}Y=!0}catch(U){if(U instanceof Error&&U.name==="AbortError")return;throw U}finally{if(!Y)T.abort()}}return new a4(X,T)}static fromReadableStream($,T){let W=!1;async function*X(){let U=new $T,G=bz($);for await(let J of G)for(let z of U.decode(J))yield z;for(let J of U.flush())yield J}async function*Y(){if(W)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let U=!1;try{for await(let G of X()){if(U)continue;if(G)yield JSON.parse(G)}U=!0}catch(G){if(G instanceof Error&&G.name==="AbortError")return;throw G}finally{if(!U)T.abort()}}return new a4(Y,T)}[Symbol.asyncIterator](){return this.iterator()}tee(){let $=[],T=[],W=this.iterator(),X=(Y)=>{return{next:()=>{if(Y.length===0){let U=W.next();$.push(U),T.push(U)}return Y.shift()}}};return[new a4(()=>X($),this.controller),new a4(()=>X(T),this.controller)]}toReadableStream(){let $=this,T,W=new TextEncoder;return new qz({async start(){T=$[Symbol.asyncIterator]()},async pull(X){try{let{value:Y,done:U}=await T.next();if(U)return X.close();let G=W.encode(JSON.stringify(Y)+`
|
|
64
|
+
`);X.enqueue(G)}catch(Y){X.error(Y)}},async cancel(){await T.return?.()}})}}async function*xR($,T){if(!$.body)throw T.abort(),new l("Attempted to iterate over a response with no body");let W=new hF,X=new $T,Y=bz($.body);for await(let U of bR(Y))for(let G of X.decode(U)){let J=W.decode(G);if(J)yield J}for(let U of X.flush()){let G=W.decode(U);if(G)yield G}}async function*bR($){let T=new Uint8Array;for await(let W of $){if(W==null)continue;let X=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?new TextEncoder().encode(W):W,Y=new Uint8Array(T.length+X.length);Y.set(T),Y.set(X,T.length),T=Y;let U;while((U=yF(T))!==-1)yield T.slice(0,U),T=T.slice(U)}if(T.length>0)yield T}class hF{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let Y={event:this.event,data:this.data.join(`
|
|
65
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Y}if(this.chunks.push($),$.startsWith(":"))return null;let[T,W,X]=fR($,":");if(X.startsWith(" "))X=X.substring(1);if(T==="event")this.event=X;else if(T==="data")this.data.push(X);return null}}function fR($,T){let W=$.indexOf(T);if(W!==-1)return[$.substring(0,W),T,$.substring(W+T.length)];return[$,"",""]}var gF=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",mF=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&aW($),aW=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",yR=($)=>{return mF($)||gF($)||vz($)};async function gz($,T,W){if($=await $,mF($))return $;if(gF($)){let Y=await $.blob();T||(T=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let U=aW(Y)?[await Y.arrayBuffer()]:[Y];return new oY(U,T,W)}let X=await hR($);if(T||(T=mR($)??"unknown_file"),!W?.type){let Y=X[0]?.type;if(typeof Y==="string")W={...W,type:Y}}return new oY(X,T,W)}async function hR($){let T=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)T.push($);else if(aW($))T.push(await $.arrayBuffer());else if(cR($))for await(let W of $)T.push(W);else throw new Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${gR($)}`);return T}function gR($){return`[${Object.getOwnPropertyNames($).map((W)=>`"${W}"`).join(", ")}]`}function mR($){return yz($.name)||yz($.filename)||yz($.path)?.split(/[\\/]/).pop()}var yz=($)=>{if(typeof $==="string")return $;if(typeof Buffer!=="undefined"&&$ instanceof Buffer)return String($);return},cR=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",mz=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody";var y4=async($)=>{let T=await cF($.body);return Pz(T,$)},cF=async($)=>{let T=new kz;return await Promise.all(Object.entries($||{}).map(([W,X])=>hz(T,W,X))),T};var hz=async($,T,W)=>{if(W===void 0)return;if(W==null)throw new TypeError(`Received null for "${T}"; to pass null in FormData, you must use the string 'null'`);if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")$.append(T,String(W));else if(yR(W)){let X=await gz(W);$.append(T,X)}else if(Array.isArray(W))await Promise.all(W.map((X)=>hz($,T+"[]",X)));else if(typeof W==="object")await Promise.all(Object.entries(W).map(([X,Y])=>hz($,`${T}[${X}]`,Y)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${W} instead`)};var pR=function($,T,W,X,Y){if(X==="m")throw new TypeError("Private method is not writable");if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?$!==T||!Y:!T.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?Y.call($,W):Y?Y.value=W:T.set($,W),W},dR=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},X8;xz();async function rF($){let{response:T}=$;if($.options.stream){if(i6("response",T.status,T.url,T.headers,T.body),$.options.__streamClass)return $.options.__streamClass.fromSSEResponse(T,$.controller);return a4.fromSSEResponse(T,$.controller)}if(T.status===204)return null;if($.options.__binaryResponse)return T;let X=T.headers.get("content-type")?.split(";")[0]?.trim();if(X?.includes("application/json")||X?.endsWith("+json")){let G=await T.json();return i6("response",T.status,T.url,T.headers,G),iF(G,T)}let U=await T.text();return i6("response",T.status,T.url,T.headers,U),U}function iF($,T){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:T.headers.get("x-request-id"),enumerable:!1})}class U8 extends Promise{constructor($,T=rF){super((W)=>{W(null)});this.responsePromise=$,this.parseResponse=T}_thenUnwrap($){return new U8(this.responsePromise,async(T)=>iF($(await this.parseResponse(T),T),T.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,T]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:T,request_id:T.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then($,T){return this.parse().then($,T)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}class uz{constructor({baseURL:$,maxRetries:T=2,timeout:W=600000,httpAgent:X,fetch:Y}){this.baseURL=$,this.maxRetries=cz("maxRetries",T),this.timeout=cz("timeout",W),this.httpAgent=X,this.fetch=Y??Iz}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...iR(),...this.authHeaders($)}}validateHeaders($,T){}defaultIdempotencyKey(){return`stainless-node-retry-${sR()}`}get($,T){return this.methodRequest("get",$,T)}post($,T){return this.methodRequest("post",$,T)}patch($,T){return this.methodRequest("patch",$,T)}put($,T){return this.methodRequest("put",$,T)}delete($,T){return this.methodRequest("delete",$,T)}methodRequest($,T,W){return this.request(Promise.resolve(W).then(async(X)=>{let Y=X&&aW(X?.body)?new DataView(await X.body.arrayBuffer()):X?.body instanceof DataView?X.body:X?.body instanceof ArrayBuffer?new DataView(X.body):X&&ArrayBuffer.isView(X?.body)?new DataView(X.body.buffer):X?.body;return{method:$,path:T,...X,body:Y}}))}getAPIList($,T,W){return this.requestAPIList(T,{method:"get",path:$,...W})}calculateContentLength($){if(typeof $==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength($,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode($).length.toString()}else if(ArrayBuffer.isView($))return $.byteLength.toString();return null}buildRequest($,{retryCount:T=0}={}){let W={...$},{method:X,path:Y,query:U,headers:G={}}=W,J=ArrayBuffer.isView(W.body)||W.__binaryRequest&&typeof W.body==="string"?W.body:mz(W.body)?W.body.body:W.body?JSON.stringify(W.body,null,2):null,z=this.calculateContentLength(J),w=this.buildURL(Y,U);if("timeout"in W)cz("timeout",W.timeout);W.timeout=W.timeout??this.timeout;let H=W.httpAgent??this.httpAgent??Cz(w),_=W.timeout+1000;if(typeof H?.options?.timeout==="number"&&_>(H.options.timeout??0))H.options.timeout=_;if(this.idempotencyHeader&&X!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();G[this.idempotencyHeader]=$.idempotencyKey}let F=this.buildHeaders({options:W,headers:G,contentLength:z,retryCount:T});return{req:{method:X,...J&&{body:J},headers:F,...H&&{agent:H},signal:W.signal??null},url:w,timeout:W.timeout}}buildHeaders({options:$,headers:T,contentLength:W,retryCount:X}){let Y={};if(W)Y["content-length"]=W;let U=this.defaultHeaders($);if(oF(Y,U),oF(Y,T),mz($.body)&&X0!=="node")delete Y["content-type"];if(Y8(U,"x-stainless-retry-count")===void 0&&Y8(T,"x-stainless-retry-count")===void 0)Y["x-stainless-retry-count"]=String(X);if(Y8(U,"x-stainless-timeout")===void 0&&Y8(T,"x-stainless-timeout")===void 0&&$.timeout)Y["x-stainless-timeout"]=String(Math.trunc($.timeout/1000));return this.validateHeaders(Y,T),Y}async prepareOptions($){}async prepareRequest($,{url:T,options:W}){}parseHeaders($){return!$?{}:(Symbol.iterator in $)?Object.fromEntries(Array.from($).map((T)=>[...T])):{...$}}makeStatusError($,T,W,X){return t$.generate($,T,W,X)}request($,T=null){return new U8(this.makeRequest($,T))}async makeRequest($,T){let W=await $,X=W.maxRetries??this.maxRetries;if(T==null)T=X;await this.prepareOptions(W);let{req:Y,url:U,timeout:G}=this.buildRequest(W,{retryCount:X-T});if(await this.prepareRequest(Y,{url:U,options:W}),i6("request",U,W,Y.headers),W.signal?.aborted)throw new Y4;let J=new AbortController,z=await this.fetchWithTimeout(U,Y,G,J).catch(T8);if(z instanceof Error){if(W.signal?.aborted)throw new Y4;if(T)return this.retryRequest(W,T);if(z.name==="AbortError")throw new U0;throw new Y0({cause:z})}let w=fz(z.headers);if(!z.ok){if(T&&this.shouldRetry(z)){let E=`retrying, ${T} attempts remaining`;return i6(`response (error; ${E})`,z.status,U,w),this.retryRequest(W,T,w)}let H=await z.text().catch((E)=>T8(E).message),_=nR(H),F=_?void 0:H;throw i6(`response (error; ${T?"(error; no more retries left)":"(error; not retryable)"})`,z.status,U,w,F),this.makeStatusError(z.status,_,F,w)}return{response:z,options:W,controller:J}}requestAPIList($,T){let W=this.makeRequest(T,null);return new nF(this,W,$)}buildURL($,T){let W=aR($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery();if(!tF(X))T={...X,...T};if(typeof T==="object"&&T&&!Array.isArray(T))W.search=this.stringifyQuery(T);return W.toString()}stringifyQuery($){return Object.entries($).filter(([T,W])=>typeof W!=="undefined").map(([T,W])=>{if(typeof W==="string"||typeof W==="number"||typeof W==="boolean")return`${encodeURIComponent(T)}=${encodeURIComponent(W)}`;if(W===null)return`${encodeURIComponent(T)}=`;throw new l(`Cannot stringify type ${typeof W}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout($,T,W,X){let{signal:Y,...U}=T||{};if(Y)Y.addEventListener("abort",()=>X.abort());let G=setTimeout(()=>X.abort(),W),J={signal:X.signal,...U};if(J.method)J.method=J.method.toUpperCase();return this.fetch.call(void 0,$,J).finally(()=>{clearTimeout(G)})}shouldRetry($){let T=$.headers.get("x-should-retry");if(T==="true")return!0;if(T==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,T,W){let X,Y=W?.["retry-after-ms"];if(Y){let G=parseFloat(Y);if(!Number.isNaN(G))X=G}let U=W?.["retry-after"];if(U&&!X){let G=parseFloat(U);if(!Number.isNaN(G))X=G*1000;else X=Date.parse(U)-Date.now()}if(!(X&&0<=X&&X<60000)){let G=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(T,G)}return await n6(X),this.makeRequest($,T-1)}calculateDefaultRetryTimeoutMillis($,T){let Y=T-$,U=Math.min(0.5*Math.pow(2,Y),8),G=1-Math.random()*0.25;return U*G*1000}getUserAgent(){return`${this.constructor.name}/JS ${W0}`}}class G8{constructor($,T,W,X){X8.set(this,void 0),pR(this,X8,$,"f"),this.options=X,this.response=T,this.body=W}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let $=this.nextPageInfo();if(!$)throw new l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let T={...this.options};if("params"in $&&typeof T.query==="object")T.query={...T.query,...$.params};else if("url"in $){let W=[...Object.entries(T.query||{}),...$.url.searchParams.entries()];for(let[X,Y]of W)$.url.searchParams.set(X,Y);T.query=void 0,T.path=$.url.toString()}return await dR(this,X8,"f").requestAPIList(this.constructor,T)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(X8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let T of $.getPaginatedItems())yield T}}class nF extends U8{constructor($,T,W){super(T,async(X)=>new W($,X.response,await rF(X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let T of $)yield T}}var fz=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(T,W){let X=W.toString();return T[X.toLowerCase()]||T[X]}})},oR={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},T$=($)=>{return typeof $==="object"&&$!==null&&!tF($)&&Object.keys($).every((T)=>aF(oR,T))},lR=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W0,"X-Stainless-OS":pF(Deno.build.os),"X-Stainless-Arch":uF(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":W0,"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":W0,"X-Stainless-OS":pF(process.platform),"X-Stainless-Arch":uF(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=rR();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function rR(){if(typeof navigator==="undefined"||!navigator)return null;let $=[{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:T,pattern:W}of $){let X=W.exec(navigator.userAgent);if(X){let Y=X[1]||0,U=X[2]||0,G=X[3]||0;return{browser:T,version:`${Y}.${U}.${G}`}}}return null}var uF=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},pF=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},dF,iR=()=>{return dF??(dF=lR())},nR=($)=>{try{return JSON.parse($)}catch(T){return}},tR=/^[a-z][a-z0-9+.-]*:/i,aR=($)=>{return tR.test($)},n6=($)=>new Promise((T)=>setTimeout(T,$)),cz=($,T)=>{if(typeof T!=="number"||!Number.isInteger(T))throw new l(`${$} must be an integer`);if(T<0)throw new l(`${$} must be a positive integer`);return T},T8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return new Error(JSON.stringify($))}catch{}return new Error($)};var sW=($)=>{if(typeof process!=="undefined")return process.env?.[$]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.($)?.trim();return};function tF($){if(!$)return!0;for(let T in $)return!1;return!0}function aF($,T){return Object.prototype.hasOwnProperty.call($,T)}function oF($,T){for(let W in T){if(!aF(T,W))continue;let X=W.toLowerCase();if(!X)continue;let Y=T[W];if(Y===null)delete $[X];else if(Y!==void 0)$[X]=Y}}var lF=new Set(["authorization","api-key"]);function i6($,...T){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true"){let W=T.map((X)=>{if(!X)return X;if(X.headers){let U={...X,headers:{...X.headers}};for(let G in X.headers)if(lF.has(G.toLowerCase()))U.headers[G]="REDACTED";return U}let Y=null;for(let U in X)if(lF.has(U.toLowerCase()))Y??(Y={...X}),Y[U]="REDACTED";return Y??X});console.log(`OpenAI:DEBUG:${$}`,...W)}}var sR=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let T=Math.random()*16|0;return($==="x"?T:T&3|8).toString(16)})},sF=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},eR=($)=>{return typeof $?.get==="function"};var Y8=($,T)=>{let W=T.toLowerCase();if(eR($)){let X=T[0]?.toUpperCase()+T.substring(1).replace(/([^\w])(\w)/g,(Y,U,G)=>U+G.toUpperCase());for(let Y of[T,W,T.toUpperCase(),X]){let U=$.get(Y);if(U)return U}}for(let[X,Y]of Object.entries($))if(X.toLowerCase()===W){if(Array.isArray(Y)){if(Y.length<=1)return Y[0];return console.warn(`Received ${Y.length} entries for the ${T} header, using the first entry.`),Y[0]}return Y}return};var eF=($)=>{if(typeof Buffer!=="undefined"){let T=Buffer.from($,"base64");return Array.from(new Float32Array(T.buffer,T.byteOffset,T.length/Float32Array.BYTES_PER_ELEMENT))}else{let T=atob($),W=T.length,X=new Uint8Array(W);for(let Y=0;Y<W;Y++)X[Y]=T.charCodeAt(Y);return Array.from(new Float32Array(X.buffer))}};function eW($){return $!=null&&typeof $==="object"&&!Array.isArray($)}class a6 extends G8{constructor($,T,W,X){super($,T,W,X);this.data=W.data||[],this.object=W.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class F$ extends G8{constructor($,T,W,X){super($,T,W,X);this.data=W.data||[],this.has_more=W.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let $=this.nextPageInfo();if(!$)return null;if("params"in $)return $.params;let T=Object.fromEntries($.url.searchParams);if(!Object.keys(T).length)return null;return T}nextPageInfo(){let $=this.getPaginatedItems();if(!$.length)return null;let T=$[$.length-1]?.id;if(!T)return null;return{params:{after:T}}}}class C{constructor($){this._client=$}}class $2 extends C{list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/chat/completions/${$}/messages`,pz,{query:T,...W})}}class J0 extends C{constructor(){super(...arguments);this.messages=new $2(this._client)}create($,T){return this._client.post("/chat/completions",{body:$,...T,stream:$.stream??!1})}retrieve($,T){return this._client.get(`/chat/completions/${$}`,T)}update($,T,W){return this._client.post(`/chat/completions/${$}`,{body:T,...W})}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/chat/completions",w0,{query:$,...T})}del($,T){return this._client.delete(`/chat/completions/${$}`,T)}}class w0 extends F${}class pz extends F${}J0.ChatCompletionsPage=w0;J0.Messages=$2;class k1 extends C{constructor(){super(...arguments);this.completions=new J0(this._client)}}k1.Completions=J0;k1.ChatCompletionsPage=w0;class T2 extends C{create($,T){return this._client.post("/audio/speech",{body:$,...T,headers:{Accept:"application/octet-stream",...T?.headers},__binaryResponse:!0})}}class W2 extends C{create($,T){return this._client.post("/audio/transcriptions",y4({body:$,...T,stream:$.stream??!1,__metadata:{model:$.model}}))}}class X2 extends C{create($,T){return this._client.post("/audio/translations",y4({body:$,...T,__metadata:{model:$.model}}))}}class s6 extends C{constructor(){super(...arguments);this.transcriptions=new W2(this._client),this.translations=new X2(this._client),this.speech=new T2(this._client)}}s6.Transcriptions=W2;s6.Translations=X2;s6.Speech=T2;class z0 extends C{create($,T){return this._client.post("/batches",{body:$,...T})}retrieve($,T){return this._client.get(`/batches/${$}`,T)}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/batches",TT,{query:$,...T})}cancel($,T){return this._client.post(`/batches/${$}/cancel`,T)}}class TT extends F${}z0.BatchesPage=TT;var E6=function($,T,W,X,Y){if(X==="m")throw new TypeError("Private method is not writable");if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?$!==T||!Y:!T.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?Y.call($,W):Y?Y.value=W:T.set($,W),W},p$=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},dz,J8,w8,Y2,U2,z8,G2,e6,J2,_8,H8,WT,$Q;class _0{constructor(){dz.add(this),this.controller=new AbortController,J8.set(this,void 0),w8.set(this,()=>{}),Y2.set(this,()=>{}),U2.set(this,void 0),z8.set(this,()=>{}),G2.set(this,()=>{}),e6.set(this,{}),J2.set(this,!1),_8.set(this,!1),H8.set(this,!1),WT.set(this,!1),E6(this,J8,new Promise(($,T)=>{E6(this,w8,$,"f"),E6(this,Y2,T,"f")}),"f"),E6(this,U2,new Promise(($,T)=>{E6(this,z8,$,"f"),E6(this,G2,T,"f")}),"f"),p$(this,J8,"f").catch(()=>{}),p$(this,U2,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},p$(this,dz,"m",$Q).bind(this))},0)}_connected(){if(this.ended)return;p$(this,w8,"f").call(this),this._emit("connect")}get ended(){return p$(this,J2,"f")}get errored(){return p$(this,_8,"f")}get aborted(){return p$(this,H8,"f")}abort(){this.controller.abort()}on($,T){return(p$(this,e6,"f")[$]||(p$(this,e6,"f")[$]=[])).push({listener:T}),this}off($,T){let W=p$(this,e6,"f")[$];if(!W)return this;let X=W.findIndex((Y)=>Y.listener===T);if(X>=0)W.splice(X,1);return this}once($,T){return(p$(this,e6,"f")[$]||(p$(this,e6,"f")[$]=[])).push({listener:T,once:!0}),this}emitted($){return new Promise((T,W)=>{if(E6(this,WT,!0,"f"),$!=="error")this.once("error",W);this.once($,T)})}async done(){E6(this,WT,!0,"f"),await p$(this,U2,"f")}_emit($,...T){if(p$(this,J2,"f"))return;if($==="end")E6(this,J2,!0,"f"),p$(this,z8,"f").call(this);let W=p$(this,e6,"f")[$];if(W)p$(this,e6,"f")[$]=W.filter((X)=>!X.once),W.forEach(({listener:X})=>X(...T));if($==="abort"){let X=T[0];if(!p$(this,WT,"f")&&!W?.length)Promise.reject(X);p$(this,Y2,"f").call(this,X),p$(this,G2,"f").call(this,X),this._emit("end");return}if($==="error"){let X=T[0];if(!p$(this,WT,"f")&&!W?.length)Promise.reject(X);p$(this,Y2,"f").call(this,X),p$(this,G2,"f").call(this,X),this._emit("end")}}_emitFinal(){}}J8=new WeakMap,w8=new WeakMap,Y2=new WeakMap,U2=new WeakMap,z8=new WeakMap,G2=new WeakMap,e6=new WeakMap,J2=new WeakMap,_8=new WeakMap,H8=new WeakMap,WT=new WeakMap,dz=new WeakSet,$Q=function $(T){if(E6(this,_8,!0,"f"),T instanceof Error&&T.name==="AbortError")T=new Y4;if(T instanceof Y4)return E6(this,H8,!0,"f"),this._emit("abort",T);if(T instanceof l)return this._emit("error",T);if(T instanceof Error){let W=new l(T.message);return W.cause=T,this._emit("error",W)}return this._emit("error",new l(String(T)))};var r=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},s4=function($,T,W,X,Y){if(X==="m")throw new TypeError("Private method is not writable");if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?$!==T||!Y:!T.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?Y.call($,W):Y?Y.value=W:T.set($,W),W},D4,oz,b6,F8,M6,F0,XT,H0,D8,e4,Q8,Z8,_2,w2,z2,TQ,WQ,XQ,YQ,UQ,GQ,JQ;class $6 extends _0{constructor(){super(...arguments);D4.add(this),oz.set(this,[]),b6.set(this,{}),F8.set(this,{}),M6.set(this,void 0),F0.set(this,void 0),XT.set(this,void 0),H0.set(this,void 0),D8.set(this,void 0),e4.set(this,void 0),Q8.set(this,void 0),Z8.set(this,void 0),_2.set(this,void 0)}[(oz=new WeakMap,b6=new WeakMap,F8=new WeakMap,M6=new WeakMap,F0=new WeakMap,XT=new WeakMap,H0=new WeakMap,D8=new WeakMap,e4=new WeakMap,Q8=new WeakMap,Z8=new WeakMap,_2=new WeakMap,D4=new WeakSet,Symbol.asyncIterator)](){let $=[],T=[],W=!1;return this.on("event",(X)=>{let Y=T.shift();if(Y)Y.resolve(X);else $.push(X)}),this.on("end",()=>{W=!0;for(let X of T)X.resolve(void 0);T.length=0}),this.on("abort",(X)=>{W=!0;for(let Y of T)Y.reject(X);T.length=0}),this.on("error",(X)=>{W=!0;for(let Y of T)Y.reject(X);T.length=0}),{next:async()=>{if(!$.length){if(W)return{value:void 0,done:!0};return new Promise((Y,U)=>T.push({resolve:Y,reject:U})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let T=new $6;return T._run(()=>T._fromReadableStream($)),T}async _fromReadableStream($,T){let W=T?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}this._connected();let X=a4.fromReadableStream($,this.controller);for await(let Y of X)r(this,D4,"m",w2).call(this,Y);if(X.controller.signal?.aborted)throw new Y4;return this._addRun(r(this,D4,"m",z2).call(this))}toReadableStream(){return new a4(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,T,W,X,Y){let U=new $6;return U._run(()=>U._runToolAssistantStream($,T,W,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),U}async _createToolAssistantStream($,T,W,X,Y){let U=Y?.signal;if(U){if(U.aborted)this.controller.abort();U.addEventListener("abort",()=>this.controller.abort())}let G={...X,stream:!0},J=await $.submitToolOutputs(T,W,G,{...Y,signal:this.controller.signal});this._connected();for await(let z of J)r(this,D4,"m",w2).call(this,z);if(J.controller.signal?.aborted)throw new Y4;return this._addRun(r(this,D4,"m",z2).call(this))}static createThreadAssistantStream($,T,W){let X=new $6;return X._run(()=>X._threadAssistantStream($,T,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}static createAssistantStream($,T,W,X){let Y=new $6;return Y._run(()=>Y._runAssistantStream($,T,W,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}currentEvent(){return r(this,Q8,"f")}currentRun(){return r(this,Z8,"f")}currentMessageSnapshot(){return r(this,M6,"f")}currentRunStepSnapshot(){return r(this,_2,"f")}async finalRunSteps(){return await this.done(),Object.values(r(this,b6,"f"))}async finalMessages(){return await this.done(),Object.values(r(this,F8,"f"))}async finalRun(){if(await this.done(),!r(this,F0,"f"))throw Error("Final run was not received.");return r(this,F0,"f")}async _createThreadAssistantStream($,T,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...T,stream:!0},U=await $.createAndRun(Y,{...W,signal:this.controller.signal});this._connected();for await(let G of U)r(this,D4,"m",w2).call(this,G);if(U.controller.signal?.aborted)throw new Y4;return this._addRun(r(this,D4,"m",z2).call(this))}async _createAssistantStream($,T,W,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let U={...W,stream:!0},G=await $.create(T,U,{...X,signal:this.controller.signal});this._connected();for await(let J of G)r(this,D4,"m",w2).call(this,J);if(G.controller.signal?.aborted)throw new Y4;return this._addRun(r(this,D4,"m",z2).call(this))}static accumulateDelta($,T){for(let[W,X]of Object.entries(T)){if(!$.hasOwnProperty(W)){$[W]=X;continue}let Y=$[W];if(Y===null||Y===void 0){$[W]=X;continue}if(W==="index"||W==="type"){$[W]=X;continue}if(typeof Y==="string"&&typeof X==="string")Y+=X;else if(typeof Y==="number"&&typeof X==="number")Y+=X;else if(eW(Y)&&eW(X))Y=this.accumulateDelta(Y,X);else if(Array.isArray(Y)&&Array.isArray(X)){if(Y.every((U)=>typeof U==="string"||typeof U==="number")){Y.push(...X);continue}for(let U of X){if(!eW(U))throw new Error(`Expected array delta entry to be an object but got: ${U}`);let G=U.index;if(G==null)throw console.error(U),new Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let J=Y[G];if(J==null)Y.push(U);else Y[G]=this.accumulateDelta(J,U)}continue}else throw Error(`Unhandled record type: ${W}, deltaValue: ${X}, accValue: ${Y}`);$[W]=Y}return $}_addRun($){return $}async _threadAssistantStream($,T,W){return await this._createThreadAssistantStream(T,$,W)}async _runAssistantStream($,T,W,X){return await this._createAssistantStream(T,$,W,X)}async _runToolAssistantStream($,T,W,X,Y){return await this._createToolAssistantStream(W,$,T,X,Y)}}w2=function $(T){if(this.ended)return;switch(s4(this,Q8,T,"f"),r(this,D4,"m",XQ).call(this,T),T.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":r(this,D4,"m",JQ).call(this,T);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":r(this,D4,"m",WQ).call(this,T);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":r(this,D4,"m",TQ).call(this,T);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:UI(T)}},z2=function $(){if(this.ended)throw new l("stream has ended, this shouldn't happen");if(!r(this,F0,"f"))throw Error("Final run has not been received");return r(this,F0,"f")},TQ=function $(T){let[W,X]=r(this,D4,"m",UQ).call(this,T,r(this,M6,"f"));s4(this,M6,W,"f"),r(this,F8,"f")[W.id]=W;for(let Y of X){let U=W.content[Y.index];if(U?.type=="text")this._emit("textCreated",U.text)}switch(T.event){case"thread.message.created":this._emit("messageCreated",T.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",T.data.delta,W),T.data.delta.content)for(let Y of T.data.delta.content){if(Y.type=="text"&&Y.text){let U=Y.text,G=W.content[Y.index];if(G&&G.type=="text")this._emit("textDelta",U,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(Y.index!=r(this,XT,"f")){if(r(this,H0,"f"))switch(r(this,H0,"f").type){case"text":this._emit("textDone",r(this,H0,"f").text,r(this,M6,"f"));break;case"image_file":this._emit("imageFileDone",r(this,H0,"f").image_file,r(this,M6,"f"));break}s4(this,XT,Y.index,"f")}s4(this,H0,W.content[Y.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(r(this,XT,"f")!==void 0){let Y=T.data.content[r(this,XT,"f")];if(Y)switch(Y.type){case"image_file":this._emit("imageFileDone",Y.image_file,r(this,M6,"f"));break;case"text":this._emit("textDone",Y.text,r(this,M6,"f"));break}}if(r(this,M6,"f"))this._emit("messageDone",T.data);s4(this,M6,void 0,"f")}},WQ=function $(T){let W=r(this,D4,"m",YQ).call(this,T);switch(s4(this,_2,W,"f"),T.event){case"thread.run.step.created":this._emit("runStepCreated",T.data);break;case"thread.run.step.delta":let X=T.data.delta;if(X.step_details&&X.step_details.type=="tool_calls"&&X.step_details.tool_calls&&W.step_details.type=="tool_calls")for(let U of X.step_details.tool_calls)if(U.index==r(this,D8,"f"))this._emit("toolCallDelta",U,W.step_details.tool_calls[U.index]);else{if(r(this,e4,"f"))this._emit("toolCallDone",r(this,e4,"f"));if(s4(this,D8,U.index,"f"),s4(this,e4,W.step_details.tool_calls[U.index],"f"),r(this,e4,"f"))this._emit("toolCallCreated",r(this,e4,"f"))}this._emit("runStepDelta",T.data.delta,W);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(s4(this,_2,void 0,"f"),T.data.step_details.type=="tool_calls"){if(r(this,e4,"f"))this._emit("toolCallDone",r(this,e4,"f")),s4(this,e4,void 0,"f")}this._emit("runStepDone",T.data,W);break;case"thread.run.step.in_progress":break}},XQ=function $(T){r(this,oz,"f").push(T),this._emit("event",T)},YQ=function $(T){switch(T.event){case"thread.run.step.created":return r(this,b6,"f")[T.data.id]=T.data,T.data;case"thread.run.step.delta":let W=r(this,b6,"f")[T.data.id];if(!W)throw Error("Received a RunStepDelta before creation of a snapshot");let X=T.data;if(X.delta){let Y=$6.accumulateDelta(W,X.delta);r(this,b6,"f")[T.data.id]=Y}return r(this,b6,"f")[T.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":r(this,b6,"f")[T.data.id]=T.data;break}if(r(this,b6,"f")[T.data.id])return r(this,b6,"f")[T.data.id];throw new Error("No snapshot available")},UQ=function $(T,W){let X=[];switch(T.event){case"thread.message.created":return[T.data,X];case"thread.message.delta":if(!W)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let Y=T.data;if(Y.delta.content)for(let U of Y.delta.content)if(U.index in W.content){let G=W.content[U.index];W.content[U.index]=r(this,D4,"m",GQ).call(this,U,G)}else W.content[U.index]=U,X.push(U);return[W,X];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(W)return[W,X];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},GQ=function $(T,W){return $6.accumulateDelta(W,T)},JQ=function $(T){switch(s4(this,Z8,T.data,"f"),T.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(s4(this,F0,T.data,"f"),r(this,e4,"f"))this._emit("toolCallDone",r(this,e4,"f")),s4(this,e4,void 0,"f");break;case"thread.run.cancelling":break}};function UI($){}class YT extends C{create($,T){return this._client.post("/assistants",{body:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}retrieve($,T){return this._client.get(`/assistants/${$}`,{...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}update($,T,W){return this._client.post(`/assistants/${$}`,{body:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/assistants",H2,{query:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}del($,T){return this._client.delete(`/assistants/${$}`,{...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}}class H2 extends F${}YT.AssistantsPage=H2;function lz($){return typeof $.parse==="function"}var q1=($)=>{return $?.role==="assistant"},rz=($)=>{return $?.role==="function"},iz=($)=>{return $?.role==="tool"};function F2($){return $?.$brand==="auto-parseable-response-format"}function Q0($){return $?.$brand==="auto-parseable-tool"}function wQ($,T){if(!T||!nz(T))return{...$,choices:$.choices.map((W)=>({...W,message:{...W.message,parsed:null,...W.message.tool_calls?{tool_calls:W.message.tool_calls}:void 0}}))};return Q2($,T)}function Q2($,T){let W=$.choices.map((X)=>{if(X.finish_reason==="length")throw new nW;if(X.finish_reason==="content_filter")throw new tW;return{...X,message:{...X.message,...X.message.tool_calls?{tool_calls:X.message.tool_calls?.map((Y)=>wI(T,Y))??void 0}:void 0,parsed:X.message.content&&!X.message.refusal?JI(T,X.message.content):null}}});return{...$,choices:W}}function JI($,T){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(T);return JSON.parse(T)}return null}function wI($,T){let W=$.tools?.find((X)=>X.function?.name===T.function.name);return{...T,function:{...T.function,parsed_arguments:Q0(W)?W.$parseRaw(T.function.arguments):W?.function.strict?JSON.parse(T.function.arguments):null}}}function zQ($,T){if(!$)return!1;let W=$.tools?.find((X)=>X.function?.name===T.function.name);return Q0(W)||W?.function.strict||!1}function nz($){if(F2($.response_format))return!0;return $.tools?.some((T)=>Q0(T)||T.type==="function"&&T.function.strict===!0)??!1}function _Q($){for(let T of $??[]){if(T.type!=="function")throw new l(`Currently only \`function\` tool types support auto-parsing; Received \`${T.type}\``);if(T.function.strict!==!0)throw new l(`The \`${T.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var h4=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},A4,tz,O8,az,sz,ez,FQ,$7,HQ=10;class Z2 extends _0{constructor(){super(...arguments);A4.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let T=$.choices[0]?.message;if(T)this._addMessage(T);return $}_addMessage($,T=!0){if(!("content"in $))$.content=null;if(this.messages.push($),T){if(this._emit("message",$),(rz($)||iz($))&&$.content)this._emit("functionCallResult",$.content);else if(q1($)&&$.function_call)this._emit("functionCall",$.function_call);else if(q1($)&&$.tool_calls){for(let W of $.tool_calls)if(W.type==="function")this._emit("functionCall",W.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new l("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),h4(this,A4,"m",tz).call(this)}async finalMessage(){return await this.done(),h4(this,A4,"m",O8).call(this)}async finalFunctionCall(){return await this.done(),h4(this,A4,"m",az).call(this)}async finalFunctionCallResult(){return await this.done(),h4(this,A4,"m",sz).call(this)}async totalUsage(){return await this.done(),h4(this,A4,"m",ez).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let T=h4(this,A4,"m",O8).call(this);if(T)this._emit("finalMessage",T);let W=h4(this,A4,"m",tz).call(this);if(W)this._emit("finalContent",W);let X=h4(this,A4,"m",az).call(this);if(X)this._emit("finalFunctionCall",X);let Y=h4(this,A4,"m",sz).call(this);if(Y!=null)this._emit("finalFunctionCallResult",Y);if(this._chatCompletions.some((U)=>U.usage))this._emit("totalUsage",h4(this,A4,"m",ez).call(this))}async _createChatCompletion($,T,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}h4(this,A4,"m",FQ).call(this,T);let Y=await $.chat.completions.create({...T,stream:!1},{...W,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Q2(Y,T))}async _runChatCompletion($,T,W){for(let X of T.messages)this._addMessage(X,!1);return await this._createChatCompletion($,T,W)}async _runFunctions($,T,W){let{function_call:Y="auto",stream:U,...G}=T,J=typeof Y!=="string"&&Y?.name,{maxChatCompletions:z=HQ}=W||{},w={};for(let _ of T.functions)w[_.name||_.function.name]=_;let H=T.functions.map((_)=>({name:_.name||_.function.name,parameters:_.parameters,description:_.description}));for(let _ of T.messages)this._addMessage(_,!1);for(let _=0;_<z;++_){let D=(await this._createChatCompletion($,{...G,function_call:Y,functions:H,messages:[...this.messages]},W)).choices[0]?.message;if(!D)throw new l("missing message in ChatCompletion response");if(!D.function_call)return;let{name:V,arguments:E}=D.function_call,R=w[V];if(!R){let k=`Invalid function_call: ${JSON.stringify(V)}. Available options are: ${H.map((y)=>JSON.stringify(y.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:V,content:k});continue}else if(J&&J!==V){let k=`Invalid function_call: ${JSON.stringify(V)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"function",name:V,content:k});continue}let P;try{P=lz(R)?await R.parse(E):E}catch(k){this._addMessage({role:"function",name:V,content:k instanceof Error?k.message:String(k)});continue}let A=await R.function(P,this),N=h4(this,A4,"m",$7).call(this,A);if(this._addMessage({role:"function",name:V,content:N}),J)return}}async _runTools($,T,W){let{tool_choice:Y="auto",stream:U,...G}=T,J=typeof Y!=="string"&&Y?.function?.name,{maxChatCompletions:z=HQ}=W||{},w=T.tools.map((F)=>{if(Q0(F)){if(!F.$callback)throw new l("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:F.$callback,name:F.function.name,description:F.function.description||"",parameters:F.function.parameters,parse:F.$parseRaw,strict:!0}}}return F}),H={};for(let F of w)if(F.type==="function")H[F.function.name||F.function.function.name]=F.function;let _="tools"in T?w.map((F)=>F.type==="function"?{type:"function",function:{name:F.function.name||F.function.function.name,parameters:F.function.parameters,description:F.function.description,strict:F.function.strict}}:F):void 0;for(let F of T.messages)this._addMessage(F,!1);for(let F=0;F<z;++F){let V=(await this._createChatCompletion($,{...G,tool_choice:Y,tools:_,messages:[...this.messages]},W)).choices[0]?.message;if(!V)throw new l("missing message in ChatCompletion response");if(!V.tool_calls?.length)return;for(let E of V.tool_calls){if(E.type!=="function")continue;let R=E.id,{name:P,arguments:A}=E.function,N=H[P];if(!N){let m=`Invalid tool_call: ${JSON.stringify(P)}. Available options are: ${Object.keys(H).map((J$)=>JSON.stringify(J$)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:m});continue}else if(J&&J!==P){let m=`Invalid tool_call: ${JSON.stringify(P)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:m});continue}let k;try{k=lz(N)?await N.parse(A):A}catch(m){let J$=m instanceof Error?m.message:String(m);this._addMessage({role:"tool",tool_call_id:R,content:J$});continue}let y=await N.function(k,this),x=h4(this,A4,"m",$7).call(this,y);if(this._addMessage({role:"tool",tool_call_id:R,content:x}),J)return}}return}}A4=new WeakSet,tz=function $(){return h4(this,A4,"m",O8).call(this).content??null},O8=function $(){let T=this.messages.length;while(T-- >0){let W=this.messages[T];if(q1(W)){let{function_call:X,...Y}=W,U={...Y,content:W.content??null,refusal:W.refusal??null};if(X)U.function_call=X;return U}}throw new l("stream ended without producing a ChatCompletionMessage with role=assistant")},az=function $(){for(let T=this.messages.length-1;T>=0;T--){let W=this.messages[T];if(q1(W)&&W?.function_call)return W.function_call;if(q1(W)&&W?.tool_calls?.length)return W.tool_calls.at(-1)?.function}return},sz=function $(){for(let T=this.messages.length-1;T>=0;T--){let W=this.messages[T];if(rz(W)&&W.content!=null)return W.content;if(iz(W)&&W.content!=null&&typeof W.content==="string"&&this.messages.some((X)=>X.role==="assistant"&&X.tool_calls?.some((Y)=>Y.type==="function"&&Y.id===W.tool_call_id)))return W.content}return},ez=function $(){let T={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:W}of this._chatCompletions)if(W)T.completion_tokens+=W.completion_tokens,T.prompt_tokens+=W.prompt_tokens,T.total_tokens+=W.total_tokens;return T},FQ=function $(T){if(T.n!=null&&T.n>1)throw new l("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},$7=function $(T){return typeof T==="string"?T:T===void 0?"undefined":JSON.stringify(T)};class UT extends Z2{static runFunctions($,T,W){let X=new UT,Y={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return X._run(()=>X._runFunctions($,T,Y)),X}static runTools($,T,W){let X=new UT,Y={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runTools"}};return X._run(()=>X._runTools($,T,Y)),X}_addMessage($,T=!0){if(super._addMessage($,T),q1($)&&$.content)this._emit("content",$.content)}}var H4={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 QQ extends Error{}class ZQ extends Error{}function zI($,T=H4.ALL){if(typeof $!=="string")throw new TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw new Error(`${$} is empty`);return _I($.trim(),T)}var _I=($,T)=>{let W=$.length,X=0,Y=(F)=>{throw new QQ(`${F} at position ${X}`)},U=(F)=>{throw new ZQ(`${F} at position ${X}`)},G=()=>{if(_(),X>=W)Y("Unexpected end of input");if($[X]==='"')return J();if($[X]==="{")return z();if($[X]==="[")return w();if($.substring(X,X+4)==="null"||H4.NULL&T&&W-X<4&&"null".startsWith($.substring(X)))return X+=4,null;if($.substring(X,X+4)==="true"||H4.BOOL&T&&W-X<4&&"true".startsWith($.substring(X)))return X+=4,!0;if($.substring(X,X+5)==="false"||H4.BOOL&T&&W-X<5&&"false".startsWith($.substring(X)))return X+=5,!1;if($.substring(X,X+8)==="Infinity"||H4.INFINITY&T&&W-X<8&&"Infinity".startsWith($.substring(X)))return X+=8,1/0;if($.substring(X,X+9)==="-Infinity"||H4.MINUS_INFINITY&T&&1<W-X&&W-X<9&&"-Infinity".startsWith($.substring(X)))return X+=9,-1/0;if($.substring(X,X+3)==="NaN"||H4.NAN&T&&W-X<3&&"NaN".startsWith($.substring(X)))return X+=3,NaN;return H()},J=()=>{let F=X,D=!1;X++;while(X<W&&($[X]!=='"'||D&&$[X-1]==="\\"))D=$[X]==="\\"?!D:!1,X++;if($.charAt(X)=='"')try{return JSON.parse($.substring(F,++X-Number(D)))}catch(V){U(String(V))}else if(H4.STR&T)try{return JSON.parse($.substring(F,X-Number(D))+'"')}catch(V){return JSON.parse($.substring(F,$.lastIndexOf("\\"))+'"')}Y("Unterminated string literal")},z=()=>{X++,_();let F={};try{while($[X]!=="}"){if(_(),X>=W&&H4.OBJ&T)return F;let D=J();_(),X++;try{let V=G();Object.defineProperty(F,D,{value:V,writable:!0,enumerable:!0,configurable:!0})}catch(V){if(H4.OBJ&T)return F;else throw V}if(_(),$[X]===",")X++}}catch(D){if(H4.OBJ&T)return F;else Y("Expected '}' at end of object")}return X++,F},w=()=>{X++;let F=[];try{while($[X]!=="]")if(F.push(G()),_(),$[X]===",")X++}catch(D){if(H4.ARR&T)return F;Y("Expected ']' at end of array")}return X++,F},H=()=>{if(X===0){if($==="-"&&H4.NUM&T)Y("Not sure what '-' is");try{return JSON.parse($)}catch(D){if(H4.NUM&T)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(V){}U(String(D))}}let F=X;if($[X]==="-")X++;while($[X]&&!",]}".includes($[X]))X++;if(X==W&&!(H4.NUM&T))Y("Unterminated number literal");try{return JSON.parse($.substring(F,X))}catch(D){if($.substring(F,X)==="-"&&H4.NUM&T)Y("Not sure what '-' is");try{return JSON.parse($.substring(F,$.lastIndexOf("e")))}catch(V){U(String(V))}}},_=()=>{while(X<W&&`
|
|
66
|
+
\r `.includes($[X]))X++};return G()},T7=($)=>zI($,H4.ALL^H4.NUM);var GT=function($,T,W,X,Y){if(X==="m")throw new TypeError("Private method is not writable");if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?$!==T||!Y:!T.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?Y.call($,W):Y?Y.value=W:T.set($,W),W},L$=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},U4,$1,JT,P1,W7,V8,X7,Y7,U7,K8,G7,DQ;class Z0 extends Z2{constructor($){super();U4.add(this),$1.set(this,void 0),JT.set(this,void 0),P1.set(this,void 0),GT(this,$1,$,"f"),GT(this,JT,[],"f")}get currentChatCompletionSnapshot(){return L$(this,P1,"f")}static fromReadableStream($){let T=new Z0(null);return T._run(()=>T._fromReadableStream($)),T}static createChatCompletion($,T,W){let X=new Z0(T);return X._run(()=>X._runChatCompletion($,{...T,stream:!0},{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createChatCompletion($,T,W){super._createChatCompletion;let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}L$(this,U4,"m",W7).call(this);let Y=await $.chat.completions.create({...T,stream:!0},{...W,signal:this.controller.signal});this._connected();for await(let U of Y)L$(this,U4,"m",X7).call(this,U);if(Y.controller.signal?.aborted)throw new Y4;return this._addChatCompletion(L$(this,U4,"m",K8).call(this))}async _fromReadableStream($,T){let W=T?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}L$(this,U4,"m",W7).call(this),this._connected();let X=a4.fromReadableStream($,this.controller),Y;for await(let U of X){if(Y&&Y!==U.id)this._addChatCompletion(L$(this,U4,"m",K8).call(this));L$(this,U4,"m",X7).call(this,U),Y=U.id}if(X.controller.signal?.aborted)throw new Y4;return this._addChatCompletion(L$(this,U4,"m",K8).call(this))}[($1=new WeakMap,JT=new WeakMap,P1=new WeakMap,U4=new WeakSet,W7=function $(){if(this.ended)return;GT(this,P1,void 0,"f")},V8=function $(T){let W=L$(this,JT,"f")[T.index];if(W)return W;return W={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},L$(this,JT,"f")[T.index]=W,W},X7=function $(T){if(this.ended)return;let W=L$(this,U4,"m",DQ).call(this,T);this._emit("chunk",T,W);for(let X of T.choices){let Y=W.choices[X.index];if(X.delta.content!=null&&Y.message?.role==="assistant"&&Y.message?.content)this._emit("content",X.delta.content,Y.message.content),this._emit("content.delta",{delta:X.delta.content,snapshot:Y.message.content,parsed:Y.message.parsed});if(X.delta.refusal!=null&&Y.message?.role==="assistant"&&Y.message?.refusal)this._emit("refusal.delta",{delta:X.delta.refusal,snapshot:Y.message.refusal});if(X.logprobs?.content!=null&&Y.message?.role==="assistant")this._emit("logprobs.content.delta",{content:X.logprobs?.content,snapshot:Y.logprobs?.content??[]});if(X.logprobs?.refusal!=null&&Y.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:X.logprobs?.refusal,snapshot:Y.logprobs?.refusal??[]});let U=L$(this,U4,"m",V8).call(this,Y);if(Y.finish_reason){if(L$(this,U4,"m",U7).call(this,Y),U.current_tool_call_index!=null)L$(this,U4,"m",Y7).call(this,Y,U.current_tool_call_index)}for(let G of X.delta.tool_calls??[]){if(U.current_tool_call_index!==G.index){if(L$(this,U4,"m",U7).call(this,Y),U.current_tool_call_index!=null)L$(this,U4,"m",Y7).call(this,Y,U.current_tool_call_index)}U.current_tool_call_index=G.index}for(let G of X.delta.tool_calls??[]){let J=Y.message.tool_calls?.[G.index];if(!J?.type)continue;if(J?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:J.function?.name,index:G.index,arguments:J.function.arguments,parsed_arguments:J.function.parsed_arguments,arguments_delta:G.function?.arguments??""});else VQ(J?.type)}}},Y7=function $(T,W){if(L$(this,U4,"m",V8).call(this,T).done_tool_calls.has(W))return;let Y=T.message.tool_calls?.[W];if(!Y)throw new Error("no tool call snapshot");if(!Y.type)throw new Error("tool call snapshot missing `type`");if(Y.type==="function"){let U=L$(this,$1,"f")?.tools?.find((G)=>G.type==="function"&&G.function.name===Y.function.name);this._emit("tool_calls.function.arguments.done",{name:Y.function.name,index:W,arguments:Y.function.arguments,parsed_arguments:Q0(U)?U.$parseRaw(Y.function.arguments):U?.function.strict?JSON.parse(Y.function.arguments):null})}else VQ(Y.type)},U7=function $(T){let W=L$(this,U4,"m",V8).call(this,T);if(T.message.content&&!W.content_done){W.content_done=!0;let X=L$(this,U4,"m",G7).call(this);this._emit("content.done",{content:T.message.content,parsed:X?X.$parseRaw(T.message.content):null})}if(T.message.refusal&&!W.refusal_done)W.refusal_done=!0,this._emit("refusal.done",{refusal:T.message.refusal});if(T.logprobs?.content&&!W.logprobs_content_done)W.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:T.logprobs.content});if(T.logprobs?.refusal&&!W.logprobs_refusal_done)W.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:T.logprobs.refusal})},K8=function $(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let T=L$(this,P1,"f");if(!T)throw new l("request ended without sending any chunks");return GT(this,P1,void 0,"f"),GT(this,JT,[],"f"),HI(T,L$(this,$1,"f"))},G7=function $(){let T=L$(this,$1,"f")?.response_format;if(F2(T))return T;return null},DQ=function $(T){var W,X,Y,U;let G=L$(this,P1,"f"),{choices:J,...z}=T;if(!G)G=GT(this,P1,{...z,choices:[]},"f");else Object.assign(G,z);for(let{delta:w,finish_reason:H,index:_,logprobs:F=null,...D}of T.choices){let V=G.choices[_];if(!V)V=G.choices[_]={finish_reason:H,index:_,message:{},logprobs:F,...D};if(F)if(!V.logprobs)V.logprobs=Object.assign({},F);else{let{content:y,refusal:x,...m}=F;if(OQ(m),Object.assign(V.logprobs,m),y)(W=V.logprobs).content??(W.content=[]),V.logprobs.content.push(...y);if(x)(X=V.logprobs).refusal??(X.refusal=[]),V.logprobs.refusal.push(...x)}if(H){if(V.finish_reason=H,L$(this,$1,"f")&&nz(L$(this,$1,"f"))){if(H==="length")throw new nW;if(H==="content_filter")throw new tW}}if(Object.assign(V,D),!w)continue;let{content:E,refusal:R,function_call:P,role:A,tool_calls:N,...k}=w;if(OQ(k),Object.assign(V.message,k),R)V.message.refusal=(V.message.refusal||"")+R;if(A)V.message.role=A;if(P)if(!V.message.function_call)V.message.function_call=P;else{if(P.name)V.message.function_call.name=P.name;if(P.arguments)(Y=V.message.function_call).arguments??(Y.arguments=""),V.message.function_call.arguments+=P.arguments}if(E){if(V.message.content=(V.message.content||"")+E,!V.message.refusal&&L$(this,U4,"m",G7).call(this))V.message.parsed=T7(V.message.content)}if(N){if(!V.message.tool_calls)V.message.tool_calls=[];for(let{index:y,id:x,type:m,function:J$,...m$}of N){let B=(U=V.message.tool_calls)[y]??(U[y]={});if(Object.assign(B,m$),x)B.id=x;if(m)B.type=m;if(J$)B.function??(B.function={name:J$.name??"",arguments:""});if(J$?.name)B.function.name=J$.name;if(J$?.arguments){if(B.function.arguments+=J$.arguments,zQ(L$(this,$1,"f"),B))B.function.parsed_arguments=T7(B.function.arguments)}}}}return G},Symbol.asyncIterator)](){let $=[],T=[],W=!1;return this.on("chunk",(X)=>{let Y=T.shift();if(Y)Y.resolve(X);else $.push(X)}),this.on("end",()=>{W=!0;for(let X of T)X.resolve(void 0);T.length=0}),this.on("abort",(X)=>{W=!0;for(let Y of T)Y.reject(X);T.length=0}),this.on("error",(X)=>{W=!0;for(let Y of T)Y.reject(X);T.length=0}),{next:async()=>{if(!$.length){if(W)return{value:void 0,done:!0};return new Promise((Y,U)=>T.push({resolve:Y,reject:U})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new a4(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function HI($,T){let{id:W,choices:X,created:Y,model:U,system_fingerprint:G,...J}=$,z={...J,id:W,choices:X.map(({message:w,finish_reason:H,index:_,logprobs:F,...D})=>{if(!H)throw new l(`missing finish_reason for choice ${_}`);let{content:V=null,function_call:E,tool_calls:R,...P}=w,A=w.role;if(!A)throw new l(`missing role for choice ${_}`);if(E){let{arguments:N,name:k}=E;if(N==null)throw new l(`missing function_call.arguments for choice ${_}`);if(!k)throw new l(`missing function_call.name for choice ${_}`);return{...D,message:{content:V,function_call:{arguments:N,name:k},role:A,refusal:w.refusal??null},finish_reason:H,index:_,logprobs:F}}if(R)return{...D,index:_,finish_reason:H,logprobs:F,message:{...P,role:A,content:V,refusal:w.refusal??null,tool_calls:R.map((N,k)=>{let{function:y,type:x,id:m,...J$}=N,{arguments:m$,name:B,...Z$}=y||{};if(m==null)throw new l(`missing choices[${_}].tool_calls[${k}].id
|
|
67
|
+
${E8($)}`);if(x==null)throw new l(`missing choices[${_}].tool_calls[${k}].type
|
|
68
|
+
${E8($)}`);if(B==null)throw new l(`missing choices[${_}].tool_calls[${k}].function.name
|
|
69
|
+
${E8($)}`);if(m$==null)throw new l(`missing choices[${_}].tool_calls[${k}].function.arguments
|
|
70
|
+
${E8($)}`);return{...J$,id:m,type:x,function:{...Z$,name:B,arguments:m$}}})}};return{...D,message:{...P,content:V,role:A,refusal:w.refusal??null},finish_reason:H,index:_,logprobs:F}}),created:Y,model:U,object:"chat.completion",...G?{system_fingerprint:G}:{}};return wQ(z,T)}function E8($){return JSON.stringify($)}function OQ($){return}function VQ($){}class D0 extends Z0{static fromReadableStream($){let T=new D0(null);return T._run(()=>T._fromReadableStream($)),T}static runFunctions($,T,W){let X=new D0(null),Y={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return X._run(()=>X._runFunctions($,T,Y)),X}static runTools($,T,W){let X=new D0(T),Y={...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"runTools"}};return X._run(()=>X._runTools($,T,Y)),X}}class M8 extends C{parse($,T){return _Q($.tools),this._client.chat.completions.create($,{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((W)=>Q2(W,$))}runFunctions($,T){if($.stream)return D0.runFunctions(this._client,$,T);return UT.runFunctions(this._client,$,T)}runTools($,T){if($.stream)return D0.runTools(this._client,$,T);return UT.runTools(this._client,$,T)}stream($,T){return Z0.createChatCompletion(this._client,$,T)}}class D2 extends C{constructor(){super(...arguments);this.completions=new M8(this._client)}}(function($){$.Completions=M8})(D2||(D2={}));class O2 extends C{create($,T){return this._client.post("/realtime/sessions",{body:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}}class V2 extends C{create($,T){return this._client.post("/realtime/transcription_sessions",{body:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}}class O0 extends C{constructor(){super(...arguments);this.sessions=new O2(this._client),this.transcriptionSessions=new V2(this._client)}}O0.Sessions=O2;O0.TranscriptionSessions=V2;class wT extends C{create($,T,W){return this._client.post(`/threads/${$}/messages`,{body:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}retrieve($,T,W){return this._client.get(`/threads/${$}/messages/${T}`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}update($,T,W,X){return this._client.post(`/threads/${$}/messages/${T}`,{body:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/threads/${$}/messages`,K2,{query:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}del($,T,W){return this._client.delete(`/threads/${$}/messages/${T}`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}}class K2 extends F${}wT.MessagesPage=K2;class zT extends C{retrieve($,T,W,X={},Y){if(T$(X))return this.retrieve($,T,W,{},X);return this._client.get(`/threads/${$}/runs/${T}/steps/${W}`,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list($,T,W={},X){if(T$(W))return this.list($,T,{},W);return this._client.getAPIList(`/threads/${$}/runs/${T}/steps`,E2,{query:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class E2 extends F${}zT.RunStepsPage=E2;class C1 extends C{constructor(){super(...arguments);this.steps=new zT(this._client)}create($,T,W){let{include:X,...Y}=T;return this._client.post(`/threads/${$}/runs`,{query:{include:X},body:Y,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers},stream:T.stream??!1})}retrieve($,T,W){return this._client.get(`/threads/${$}/runs/${T}`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}update($,T,W,X){return this._client.post(`/threads/${$}/runs/${T}`,{body:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/threads/${$}/runs`,M2,{query:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}cancel($,T,W){return this._client.post(`/threads/${$}/runs/${T}/cancel`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}async createAndPoll($,T,W){let X=await this.create($,T,W);return await this.poll($,X.id,W)}createAndStream($,T,W){return $6.createAssistantStream($,this._client.beta.threads.runs,T,W)}async poll($,T,W){let X={...W?.headers,"X-Stainless-Poll-Helper":"true"};if(W?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=W.pollIntervalMs.toString();while(!0){let{data:Y,response:U}=await this.retrieve($,T,{...W,headers:{...W?.headers,...X}}).withResponse();switch(Y.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=U.headers.get("openai-poll-after-ms");if(J){let z=parseInt(J);if(!isNaN(z))G=z}}await n6(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return Y}}}stream($,T,W){return $6.createAssistantStream($,this._client.beta.threads.runs,T,W)}submitToolOutputs($,T,W,X){return this._client.post(`/threads/${$}/runs/${T}/submit_tool_outputs`,{body:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers},stream:W.stream??!1})}async submitToolOutputsAndPoll($,T,W,X){let Y=await this.submitToolOutputs($,T,W,X);return await this.poll($,Y.id,X)}submitToolOutputsStream($,T,W,X){return $6.createToolAssistantStream($,T,this._client.beta.threads.runs,W,X)}}class M2 extends F${}C1.RunsPage=M2;C1.Steps=zT;C1.RunStepsPage=E2;class T1 extends C{constructor(){super(...arguments);this.runs=new C1(this._client),this.messages=new wT(this._client)}create($={},T){if(T$($))return this.create({},$);return this._client.post("/threads",{body:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}retrieve($,T){return this._client.get(`/threads/${$}`,{...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}update($,T,W){return this._client.post(`/threads/${$}`,{body:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}del($,T){return this._client.delete(`/threads/${$}`,{...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}createAndRun($,T){return this._client.post("/threads/runs",{body:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers},stream:$.stream??!1})}async createAndRunPoll($,T){let W=await this.createAndRun($,T);return await this.runs.poll(W.thread_id,W.id,T)}createAndRunStream($,T){return $6.createThreadAssistantStream($,this._client.beta.threads,T)}}T1.Runs=C1;T1.RunsPage=M2;T1.Messages=wT;T1.MessagesPage=K2;class f6 extends C{constructor(){super(...arguments);this.realtime=new O0(this._client),this.chat=new D2(this._client),this.assistants=new YT(this._client),this.threads=new T1(this._client)}}f6.Realtime=O0;f6.Assistants=YT;f6.AssistantsPage=H2;f6.Threads=T1;class _T extends C{create($,T){return this._client.post("/completions",{body:$,...T,stream:$.stream??!1})}}class A2 extends C{retrieve($,T,W){return this._client.get(`/containers/${$}/files/${T}/content`,{...W,headers:{Accept:"*/*",...W?.headers}})}}class V0 extends C{constructor(){super(...arguments);this.content=new A2(this._client)}create($,T,W){return this._client.post(`/containers/${$}/files`,y4({body:T,...W}))}retrieve($,T,W){return this._client.get(`/containers/${$}/files/${T}`,W)}list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/containers/${$}/files`,N2,{query:T,...W})}del($,T,W){return this._client.delete(`/containers/${$}/files/${T}`,{...W,headers:{Accept:"*/*",...W?.headers}})}}class N2 extends F${}V0.FileListResponsesPage=N2;V0.Content=A2;class W1 extends C{constructor(){super(...arguments);this.files=new V0(this._client)}create($,T){return this._client.post("/containers",{body:$,...T})}retrieve($,T){return this._client.get(`/containers/${$}`,T)}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/containers",HT,{query:$,...T})}del($,T){return this._client.delete(`/containers/${$}`,{...T,headers:{Accept:"*/*",...T?.headers}})}}class HT extends F${}W1.ContainerListResponsesPage=HT;W1.Files=V0;W1.FileListResponsesPage=N2;class FT extends C{create($,T){let W=!!$.encoding_format,X=W?$.encoding_format:"base64";if(W)i6("Request","User defined encoding_format:",$.encoding_format);let Y=this._client.post("/embeddings",{body:{...$,encoding_format:X},...T});if(W)return Y;return i6("response","Decoding base64 embeddings to float32 array"),Y._thenUnwrap((U)=>{if(U&&U.data)U.data.forEach((G)=>{let J=G.embedding;G.embedding=eF(J)});return U})}}class QT extends C{retrieve($,T,W,X){return this._client.get(`/evals/${$}/runs/${T}/output_items/${W}`,X)}list($,T,W={},X){if(T$(W))return this.list($,T,{},W);return this._client.getAPIList(`/evals/${$}/runs/${T}/output_items`,L2,{query:W,...X})}}class L2 extends F${}QT.OutputItemListResponsesPage=L2;class v1 extends C{constructor(){super(...arguments);this.outputItems=new QT(this._client)}create($,T,W){return this._client.post(`/evals/${$}/runs`,{body:T,...W})}retrieve($,T,W){return this._client.get(`/evals/${$}/runs/${T}`,W)}list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/evals/${$}/runs`,S2,{query:T,...W})}del($,T,W){return this._client.delete(`/evals/${$}/runs/${T}`,W)}cancel($,T,W){return this._client.post(`/evals/${$}/runs/${T}`,W)}}class S2 extends F${}v1.RunListResponsesPage=S2;v1.OutputItems=QT;v1.OutputItemListResponsesPage=L2;class X1 extends C{constructor(){super(...arguments);this.runs=new v1(this._client)}create($,T){return this._client.post("/evals",{body:$,...T})}retrieve($,T){return this._client.get(`/evals/${$}`,T)}update($,T,W){return this._client.post(`/evals/${$}`,{body:T,...W})}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/evals",ZT,{query:$,...T})}del($,T){return this._client.delete(`/evals/${$}`,T)}}class ZT extends F${}X1.EvalListResponsesPage=ZT;X1.Runs=v1;X1.RunListResponsesPage=S2;class K0 extends C{create($,T){return this._client.post("/files",y4({body:$,...T}))}retrieve($,T){return this._client.get(`/files/${$}`,T)}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/files",DT,{query:$,...T})}del($,T){return this._client.delete(`/files/${$}`,T)}content($,T){return this._client.get(`/files/${$}/content`,{...T,headers:{Accept:"application/binary",...T?.headers},__binaryResponse:!0})}retrieveContent($,T){return this._client.get(`/files/${$}/content`,T)}async waitForProcessing($,{pollInterval:T=5000,maxWait:W=1800000}={}){let X=new Set(["processed","error","deleted"]),Y=Date.now(),U=await this.retrieve($);while(!U.status||!X.has(U.status))if(await n6(T),U=await this.retrieve($),Date.now()-Y>W)throw new U0({message:`Giving up on waiting for file ${$} to finish processing after ${W} milliseconds.`});return U}}class DT extends F${}K0.FileObjectsPage=DT;class B2 extends C{}class R2 extends C{run($,T){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...T})}validate($,T){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...T})}}class OT extends C{constructor(){super(...arguments);this.graders=new R2(this._client)}}OT.Graders=R2;class VT extends C{create($,T,W){return this._client.getAPIList(`/fine_tuning/checkpoints/${$}/permissions`,I2,{body:T,method:"post",...W})}retrieve($,T={},W){if(T$(T))return this.retrieve($,{},T);return this._client.get(`/fine_tuning/checkpoints/${$}/permissions`,{query:T,...W})}del($,T,W){return this._client.delete(`/fine_tuning/checkpoints/${$}/permissions/${T}`,W)}}class I2 extends a6{}VT.PermissionCreateResponsesPage=I2;class E0 extends C{constructor(){super(...arguments);this.permissions=new VT(this._client)}}E0.Permissions=VT;E0.PermissionCreateResponsesPage=I2;class KT extends C{list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/fine_tuning/jobs/${$}/checkpoints`,k2,{query:T,...W})}}class k2 extends F${}KT.FineTuningJobCheckpointsPage=k2;class Y1 extends C{constructor(){super(...arguments);this.checkpoints=new KT(this._client)}create($,T){return this._client.post("/fine_tuning/jobs",{body:$,...T})}retrieve($,T){return this._client.get(`/fine_tuning/jobs/${$}`,T)}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/fine_tuning/jobs",q2,{query:$,...T})}cancel($,T){return this._client.post(`/fine_tuning/jobs/${$}/cancel`,T)}listEvents($,T={},W){if(T$(T))return this.listEvents($,{},T);return this._client.getAPIList(`/fine_tuning/jobs/${$}/events`,P2,{query:T,...W})}pause($,T){return this._client.post(`/fine_tuning/jobs/${$}/pause`,T)}resume($,T){return this._client.post(`/fine_tuning/jobs/${$}/resume`,T)}}class q2 extends F${}class P2 extends F${}Y1.FineTuningJobsPage=q2;Y1.FineTuningJobEventsPage=P2;Y1.Checkpoints=KT;Y1.FineTuningJobCheckpointsPage=k2;class G6 extends C{constructor(){super(...arguments);this.methods=new B2(this._client),this.jobs=new Y1(this._client),this.checkpoints=new E0(this._client),this.alpha=new OT(this._client)}}G6.Methods=B2;G6.Jobs=Y1;G6.FineTuningJobsPage=q2;G6.FineTuningJobEventsPage=P2;G6.Checkpoints=E0;G6.Alpha=OT;class C2 extends C{}class M0 extends C{constructor(){super(...arguments);this.graderModels=new C2(this._client)}}M0.GraderModels=C2;class ET extends C{createVariation($,T){return this._client.post("/images/variations",y4({body:$,...T}))}edit($,T){return this._client.post("/images/edits",y4({body:$,...T}))}generate($,T){return this._client.post("/images/generations",{body:$,...T})}}class A0 extends C{retrieve($,T){return this._client.get(`/models/${$}`,T)}list($){return this._client.getAPIList("/models",MT,$)}del($,T){return this._client.delete(`/models/${$}`,T)}}class MT extends a6{}A0.ModelsPage=MT;class AT extends C{create($,T){return this._client.post("/moderations",{body:$,...T})}}function KQ($,T){if(!T||!xI(T))return{...$,output_parsed:null,output:$.output.map((W)=>{if(W.type==="function_call")return{...W,parsed_arguments:null};if(W.type==="message")return{...W,content:W.content.map((X)=>({...X,parsed:null}))};else return W})};return J7($,T)}function J7($,T){let W=$.output.map((Y)=>{if(Y.type==="function_call")return{...Y,parsed_arguments:yI(T,Y)};if(Y.type==="message"){let U=Y.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:jI(T,G.text)};return G});return{...Y,content:U}}return Y}),X=Object.assign({},$,{output:W});if(!Object.getOwnPropertyDescriptor($,"output_text"))A8(X);return Object.defineProperty(X,"output_parsed",{enumerable:!0,get(){for(let Y of X.output){if(Y.type!=="message")continue;for(let U of Y.content)if(U.type==="output_text"&&U.parsed!==null)return U.parsed}return null}}),X}function jI($,T){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(T);return JSON.parse(T)}function xI($){if(F2($.text?.format))return!0;return!1}function bI($){return $?.$brand==="auto-parseable-tool"}function fI($,T){return $.find((W)=>W.type==="function"&&W.name===T)}function yI($,T){let W=fI($.tools??[],T.name);return{...T,...T,parsed_arguments:bI(W)?W.$parseRaw(T.arguments):W?.strict?JSON.parse(T.arguments):null}}function A8($){let T=[];for(let W of $.output){if(W.type!=="message")continue;for(let X of W.content)if(X.type==="output_text")T.push(X.text)}$.output_text=T.join("")}class v2 extends C{list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/responses/${$}/input_items`,w7,{query:T,...W})}}var NT=function($,T,W,X,Y){if(X==="m")throw new TypeError("Private method is not writable");if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?$!==T||!Y:!T.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?Y.call($,W):Y?Y.value=W:T.set($,W),W},j1=function($,T,W,X){if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?$!==T||!X:!T.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?X:W==="a"?X.call($):X?X.value:T.get($)},LT,N8,x1,L8,EQ,MQ,AQ,NQ;class S8 extends _0{constructor($){super();LT.add(this),N8.set(this,void 0),x1.set(this,void 0),L8.set(this,void 0),NT(this,N8,$,"f")}static createResponse($,T,W){let X=new S8(T);return X._run(()=>X._createOrRetrieveResponse($,T,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createOrRetrieveResponse($,T,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}j1(this,LT,"m",EQ).call(this);let Y,U=null;if("response_id"in T)Y=await $.responses.retrieve(T.response_id,{stream:!0},{...W,signal:this.controller.signal,stream:!0}),U=T.starting_after??null;else Y=await $.responses.create({...T,stream:!0},{...W,signal:this.controller.signal});this._connected();for await(let G of Y)j1(this,LT,"m",MQ).call(this,G,U);if(Y.controller.signal?.aborted)throw new Y4;return j1(this,LT,"m",AQ).call(this)}[(N8=new WeakMap,x1=new WeakMap,L8=new WeakMap,LT=new WeakSet,EQ=function $(){if(this.ended)return;NT(this,x1,void 0,"f")},MQ=function $(T,W){if(this.ended)return;let X=(U,G)=>{if(W==null||G.sequence_number>W)this._emit(U,G)},Y=j1(this,LT,"m",NQ).call(this,T);switch(X("event",T),T.type){case"response.output_text.delta":{let U=Y.output[T.output_index];if(!U)throw new l(`missing output at index ${T.output_index}`);if(U.type==="message"){let G=U.content[T.content_index];if(!G)throw new l(`missing content at index ${T.content_index}`);if(G.type!=="output_text")throw new l(`expected content to be 'output_text', got ${G.type}`);X("response.output_text.delta",{...T,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let U=Y.output[T.output_index];if(!U)throw new l(`missing output at index ${T.output_index}`);if(U.type==="function_call")X("response.function_call_arguments.delta",{...T,snapshot:U.arguments});break}default:X(T.type,T);break}},AQ=function $(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let T=j1(this,x1,"f");if(!T)throw new l("request ended without sending any events");NT(this,x1,void 0,"f");let W=gI(T,j1(this,N8,"f"));return NT(this,L8,W,"f"),W},NQ=function $(T){let W=j1(this,x1,"f");if(!W){if(T.type!=="response.created")throw new l(`When snapshot hasn't been set yet, expected 'response.created' event, got ${T.type}`);return W=NT(this,x1,T.response,"f"),W}switch(T.type){case"response.output_item.added":{W.output.push(T.item);break}case"response.content_part.added":{let X=W.output[T.output_index];if(!X)throw new l(`missing output at index ${T.output_index}`);if(X.type==="message")X.content.push(T.part);break}case"response.output_text.delta":{let X=W.output[T.output_index];if(!X)throw new l(`missing output at index ${T.output_index}`);if(X.type==="message"){let Y=X.content[T.content_index];if(!Y)throw new l(`missing content at index ${T.content_index}`);if(Y.type!=="output_text")throw new l(`expected content to be 'output_text', got ${Y.type}`);Y.text+=T.delta}break}case"response.function_call_arguments.delta":{let X=W.output[T.output_index];if(!X)throw new l(`missing output at index ${T.output_index}`);if(X.type==="function_call")X.arguments+=T.delta;break}case"response.completed":{NT(this,x1,T.response,"f");break}}return W},Symbol.asyncIterator)](){let $=[],T=[],W=!1;return this.on("event",(X)=>{let Y=T.shift();if(Y)Y.resolve(X);else $.push(X)}),this.on("end",()=>{W=!0;for(let X of T)X.resolve(void 0);T.length=0}),this.on("abort",(X)=>{W=!0;for(let Y of T)Y.reject(X);T.length=0}),this.on("error",(X)=>{W=!0;for(let Y of T)Y.reject(X);T.length=0}),{next:async()=>{if(!$.length){if(W)return{value:void 0,done:!0};return new Promise((Y,U)=>T.push({resolve:Y,reject:U})).then((Y)=>Y?{value:Y,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=j1(this,L8,"f");if(!$)throw new l("stream ended without producing a ChatCompletion");return $}}function gI($,T){return KQ($,T)}class N0 extends C{constructor(){super(...arguments);this.inputItems=new v2(this._client)}create($,T){return this._client.post("/responses",{body:$,...T,stream:$.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")A8(W);return W})}retrieve($,T={},W){if(T$(T)&&W===void 0)return this.retrieve($,{},T);return this._client.get(`/responses/${$}`,{query:T,...W,stream:T.stream??!1})._thenUnwrap((X)=>{if("object"in X&&X.object==="response")A8(X);return X})}del($,T){return this._client.delete(`/responses/${$}`,{...T,headers:{Accept:"*/*",...T?.headers}})}parse($,T){return this._client.responses.create($,T)._thenUnwrap((W)=>J7(W,$))}stream($,T){return S8.createResponse(this._client,$,T)}cancel($,T){return this._client.post(`/responses/${$}/cancel`,{...T,headers:{Accept:"*/*",...T?.headers}})}}class w7 extends F${}N0.InputItems=v2;class j2 extends C{create($,T,W){return this._client.post(`/uploads/${$}/parts`,y4({body:T,...W}))}}class L0 extends C{constructor(){super(...arguments);this.parts=new j2(this._client)}create($,T){return this._client.post("/uploads",{body:$,...T})}cancel($,T){return this._client.post(`/uploads/${$}/cancel`,T)}complete($,T,W){return this._client.post(`/uploads/${$}/complete`,{body:T,...W})}}L0.Parts=j2;var LQ=async($)=>{let T=await Promise.allSettled($),W=T.filter((Y)=>Y.status==="rejected");if(W.length){for(let Y of W)console.error(Y.reason);throw new Error(`${W.length} promise(s) failed - see the above errors`)}let X=[];for(let Y of T)if(Y.status==="fulfilled")X.push(Y.value);return X};class S0 extends C{create($,T,W){return this._client.post(`/vector_stores/${$}/files`,{body:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}retrieve($,T,W){return this._client.get(`/vector_stores/${$}/files/${T}`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}update($,T,W,X){return this._client.post(`/vector_stores/${$}/files/${T}`,{body:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list($,T={},W){if(T$(T))return this.list($,{},T);return this._client.getAPIList(`/vector_stores/${$}/files`,B0,{query:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}del($,T,W){return this._client.delete(`/vector_stores/${$}/files/${T}`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}async createAndPoll($,T,W){let X=await this.create($,T,W);return await this.poll($,X.id,W)}async poll($,T,W){let X={...W?.headers,"X-Stainless-Poll-Helper":"true"};if(W?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=W.pollIntervalMs.toString();while(!0){let Y=await this.retrieve($,T,{...W,headers:X}).withResponse(),U=Y.data;switch(U.status){case"in_progress":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=Y.response.headers.get("openai-poll-after-ms");if(J){let z=parseInt(J);if(!isNaN(z))G=z}}await n6(G);break;case"failed":case"completed":return U}}}async upload($,T,W){let X=await this._client.files.create({file:T,purpose:"assistants"},W);return this.create($,{file_id:X.id},W)}async uploadAndPoll($,T,W){let X=await this.upload($,T,W);return await this.poll($,X.id,W)}content($,T,W){return this._client.getAPIList(`/vector_stores/${$}/files/${T}/content`,x2,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}}class B0 extends F${}class x2 extends a6{}S0.VectorStoreFilesPage=B0;S0.FileContentResponsesPage=x2;class b2 extends C{create($,T,W){return this._client.post(`/vector_stores/${$}/file_batches`,{body:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}retrieve($,T,W){return this._client.get(`/vector_stores/${$}/file_batches/${T}`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}cancel($,T,W){return this._client.post(`/vector_stores/${$}/file_batches/${T}/cancel`,{...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}async createAndPoll($,T,W){let X=await this.create($,T);return await this.poll($,X.id,W)}listFiles($,T,W={},X){if(T$(W))return this.listFiles($,T,{},W);return this._client.getAPIList(`/vector_stores/${$}/file_batches/${T}/files`,B0,{query:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async poll($,T,W){let X={...W?.headers,"X-Stainless-Poll-Helper":"true"};if(W?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=W.pollIntervalMs.toString();while(!0){let{data:Y,response:U}=await this.retrieve($,T,{...W,headers:X}).withResponse();switch(Y.status){case"in_progress":let G=5000;if(W?.pollIntervalMs)G=W.pollIntervalMs;else{let J=U.headers.get("openai-poll-after-ms");if(J){let z=parseInt(J);if(!isNaN(z))G=z}}await n6(G);break;case"failed":case"cancelled":case"completed":return Y}}}async uploadAndPoll($,{files:T,fileIds:W=[]},X){if(T==null||T.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let Y=X?.maxConcurrency??5,U=Math.min(Y,T.length),G=this._client,J=T.values(),z=[...W];async function w(_){for(let F of _){let D=await G.files.create({file:F,purpose:"assistants"},X);z.push(D.id)}}let H=Array(U).fill(J).map(w);return await LQ(H),await this.createAndPoll($,{file_ids:z})}}class J6 extends C{constructor(){super(...arguments);this.files=new S0(this._client),this.fileBatches=new b2(this._client)}create($,T){return this._client.post("/vector_stores",{body:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}retrieve($,T){return this._client.get(`/vector_stores/${$}`,{...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}update($,T,W){return this._client.post(`/vector_stores/${$}`,{body:T,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}list($={},T){if(T$($))return this.list({},$);return this._client.getAPIList("/vector_stores",ST,{query:$,...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}del($,T){return this._client.delete(`/vector_stores/${$}`,{...T,headers:{"OpenAI-Beta":"assistants=v2",...T?.headers}})}search($,T,W){return this._client.getAPIList(`/vector_stores/${$}/search`,BT,{body:T,method:"post",...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}}class ST extends F${}class BT extends a6{}J6.VectorStoresPage=ST;J6.VectorStoreSearchResponsesPage=BT;J6.Files=S0;J6.VectorStoreFilesPage=B0;J6.FileContentResponsesPage=x2;J6.FileBatches=b2;var SQ;class X$ extends uz{constructor({baseURL:$=sW("OPENAI_BASE_URL"),apiKey:T=sW("OPENAI_API_KEY"),organization:W=sW("OPENAI_ORG_ID")??null,project:X=sW("OPENAI_PROJECT_ID")??null,...Y}={}){if(T===void 0)throw new l("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 U={apiKey:T,organization:W,project:X,...Y,baseURL:$||"https://api.openai.com/v1"};if(!U.dangerouslyAllowBrowser&&sF())throw new l(`It looks like you're running in a browser-like environment.
|
|
47
71
|
|
|
48
72
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
49
73
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -52,21 +76,21 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
52
76
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
53
77
|
|
|
54
78
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
55
|
-
`);super({baseURL:
|
|
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 WO(W){let Y=Object.keys(lH).filter((X)=>W.startsWith(X)).sort((X,G)=>G.length-X.length)[0];if(!Y)return;return lH[Y]}function $O(W){return async function $(Y,X){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({...Y,stream:!1,response_format:{type:"json_object"}},X),J=G.choices[0].message?.content,{usage:H}=G;if(J&&H){let T=H.prompt_tokens,Q=H.prompt_tokens_details?.cached_tokens??0,_=T-Q,z=H.completion_tokens,F=WO(Y.model),w=0;if(F)w=T*F.promptPricePerToken+_*(F.promptPricePerTokenCached??0)+z*F.completionPricePerToken;else console.warn(`No pricing facts found for model ${Y.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:Y,apiKey:X,cachingMode:G,cacheKey:J="openai-safegen",logger:H}){this.usdBudget=$,this.usdMinimum=Y,this.squirrel=new l3(G);let T=oH.get(X);if(G!=="read"){if(!T)T=new dH({apiKey:X,dangerouslyAllowBrowser:!1}),oH.set(X,T);this.client=T}this.getUnknownJsonFromOpenAi=$O(this.client),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(J,this.getUnknownJsonFromOpenAi),this.from=k3(async(...Q)=>{if(this.usdBudget<this.usdMinimum)return H?.warn("SafeGen budget exhausted"),Q[1];let _=eV(W,...Q),z=Q[0],F=Q[3],{data:w,usage:O,usdPrice:V}=await this.getUnknownJsonFromOpenAiSquirreled.for(`${z.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${F.length}`).get(_);return this.lastUsage=O,this.usdBudget-=V,w},H)}from};import{exec as _Z}from"child_process";class TX{supported;constructor(W){this.supported=W}refine(W){for(let[$,Y]of Object.entries(this.supported))try{if(Y(W)===!0&&Y!==Boolean)return{type:$,data:W}}catch(X){try{if(W instanceof Y)return{type:$,data:W}}catch(G){}}return null}}var YO=new TX({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 GO=new TX({object:XO,array:(W)=>Array.isArray(W)}),JO=new TX({...YO.supported,...GO.supported}),nH=(W)=>{if(W===void 0)return"undefined";let $=JO.refine(W);if($)return $.type;return Object.getPrototypeOf(W).constructor.name};var D=Symbol.for("drizzle:entityKind"),kb=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 Y=Object.getPrototypeOf(W).constructor;if(Y)while(Y){if(D in Y&&Y[D]===$[D])return!0;Y=Object.getPrototypeOf(Y)}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 m5{static[D]="ColumnBuilder";config;constructor(W,$,Y){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:Y,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 p5{static[D]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(W,$){if(this.reference=()=>{let{name:Y,columns:X,foreignColumns:G}=W();return{name:Y,columns:X,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:Y}=this.reference(),X=$.map((H)=>H.name),G=Y.map((H)=>H.name),J=[this.table[RW],...X,Y[0].table[RW],...G];return W??`${J.join("_")}_fk`}}function QX(W,...$){return W(...$)}function tH(W,$){return`${W[RW]}_${$.join("_")}_unique`}function aH(W,$,Y){for(let X=$;X<W.length;X++){let G=W[X];if(G==="\\"){X++;continue}if(G==='"')return[W.slice($,X).replace(/\\/g,""),X+1];if(Y)continue;if(G===","||G==="}")return[W.slice($,X).replace(/\\/g,""),X]}return[W.slice($).replace(/\\/g,""),W.length]}function sH(W,$=0){let Y=[],X=$,G=!1;while(X<W.length){let J=W[X];if(J===","){if(G||X===$)Y.push("");G=!0,X++;continue}if(G=!1,J==="\\"){X+=2;continue}if(J==='"'){let[Q,_]=aH(W,X+1,!0);Y.push(Q),X=_;continue}if(J==="}")return[Y,X+1];if(J==="{"){let[Q,_]=sH(W,X+1);Y.push(Q),X=_;continue}let[H,T]=aH(W,X,!1);Y.push(H),X=T}return[Y,X]}function eH(W){let[$]=sH(W,1);return $}function u5(W){return`{${W.map(($)=>{if(Array.isArray($))return u5($);if(typeof $==="string")return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${$}`}).join(",")}}`}class c extends m5{foreignKeyConfigs=[];static[D]="PgColumnBuilder";array(W){return new $T(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:Y,actions:X})=>{return QX((G,J)=>{let H=new p5(()=>{let T=G();return{columns:[W],foreignColumns:[T]}});if(J.onUpdate)H.onUpdate(J.onUpdate);if(J.onDelete)H.onDelete(J.onDelete);return H.build($)},Y,X)})}buildExtraConfigColumn(W){return new WT(W,this.config)}}class b extends q0{constructor(W,$){if(!$.uniqueName)$.uniqueName=tH(W,[$.name]);super(W,$);this.table=W}static[D]="PgColumn"}class WT extends b{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 T6{static[D]="IndexedColumn";constructor(W,$,Y,X){this.name=W,this.keyAsName=$,this.type=Y,this.indexConfig=X}name;keyAsName;type;indexConfig}class $T extends c{static[D]="PgArrayBuilder";constructor(W,$,Y){super(W,"array","PgArray");this.config.baseBuilder=$,this.config.size=Y}build(W){let $=this.config.baseBuilder.build(W);return new c5(W,this.config,$)}}class c5 extends b{constructor(W,$,Y,X){super(W,$);this.baseColumn=Y,this.range=X,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 Y=W.map((X)=>X===null?null:L(this.baseColumn,c5)?this.baseColumn.mapToDriverValue(X,!0):this.baseColumn.mapToDriverValue(X));if($)return Y;return u5(Y)}}class YT extends c{static[D]="PgEnumObjectColumnBuilder";constructor(W,$){super(W,"string","PgEnumObjectColumn");this.config.enum=$}build(W){return new XT(W,this.config)}}class XT extends b{static[D]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var _X=Symbol.for("drizzle:isPgEnum");function GT(W){return!!W&&typeof W==="function"&&_X in W&&W[_X]===!0}class JT extends c{static[D]="PgEnumColumnBuilder";constructor(W,$){super(W,"string","PgEnumColumn");this.config.enum=$}build(W){return new HT(W,this.config)}}class HT extends b{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 Q6(W,$){return Array.isArray($)?HO(W,[...$],void 0):TO(W,$,void 0)}function HO(W,$,Y){let X=Object.assign((G)=>new JT(G??"",X),{enumName:W,enumValues:$,schema:Y,[_X]:!0});return X}function TO(W,$,Y){let X=Object.assign((G)=>new YT(G??"",X),{enumName:W,enumValues:Object.values($),schema:Y,[_X]:!0});return X}class H1{static[D]="Subquery";constructor(W,$,Y,X=!1){this._={brand:"Subquery",sql:W,selectedFields:$,alias:Y,isWith:X}}}class _6 extends H1{static[D]="WithSubquery"}var TT="0.43.1";var d5,l5,C0={startActiveSpan(W,$){if(!d5)return $();if(!l5)l5=d5.trace.getTracer("drizzle-orm",TT);return QX((Y,X)=>X.startActiveSpan(W,(G)=>{try{return $(G)}catch(J){throw G.setStatus({code:Y.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),d5,l5)}};var f0=Symbol.for("drizzle:ViewBaseConfig");var zX=Symbol.for("drizzle:Schema"),FX=Symbol.for("drizzle:Columns"),QT=Symbol.for("drizzle:ExtraConfigColumns"),o5=Symbol.for("drizzle:OriginalName"),i5=Symbol.for("drizzle:BaseName"),z6=Symbol.for("drizzle:IsAlias"),_T=Symbol.for("drizzle:ExtraConfigBuilder"),QO=Symbol.for("drizzle:IsDrizzleTable");class m{static[D]="Table";static Symbol={Name:RW,Schema:zX,OriginalName:o5,Columns:FX,ExtraConfigColumns:QT,BaseName:i5,IsAlias:z6,ExtraConfigBuilder:_T};[RW];[o5];[zX];[FX];[QT];[i5];[z6]=!1;[QO]=!0;[_T]=void 0;constructor(W,$,Y){this[RW]=this[o5]=W,this[zX]=$,this[i5]=Y}}function w1(W){return W[RW]}function L2(W){return`${W[zX]??"public"}.${W[RW]}`}function n5(W){return W!==null&&W!==void 0&&typeof W.getSQL==="function"}function _O(W){let $={sql:"",params:[]};for(let Y of W)if($.sql+=Y.sql,$.params.push(...Y.params),Y.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...Y.typings)}return $}class T1{static[D]="StringChunk";value;constructor(W){this.value=Array.isArray(W)?W:[W]}getSQL(){return new u([this])}}class u{constructor(W){this.queryChunks=W}static[D]="SQL";decoder=FT;shouldInlineParams=!1;append(W){return this.queryChunks.push(...W.queryChunks),this}toQuery(W){return C0.startActiveSpan("drizzle.buildSQL",($)=>{let Y=this.buildQueryFromSourceParams(this.queryChunks,W);return $?.setAttributes({"drizzle.query.text":Y.sql,"drizzle.query.params":JSON.stringify(Y.params)}),Y})}buildQueryFromSourceParams(W,$){let Y=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:X,escapeName:G,escapeParam:J,prepareTyping:H,inlineParams:T,paramStartIndex:Q}=Y;return _O(W.map((_)=>{if(L(_,T1))return{sql:_.value.join(""),params:[]};if(L(_,wX))return{sql:G(_.value),params:[]};if(_===void 0)return{sql:"",params:[]};if(Array.isArray(_)){let z=[new T1("(")];for(let[F,w]of _.entries())if(z.push(w),F<_.length-1)z.push(new T1(", "));return z.push(new T1(")")),this.buildQueryFromSourceParams(z,Y)}if(L(_,u))return this.buildQueryFromSourceParams(_.queryChunks,{...Y,inlineParams:T||_.shouldInlineParams});if(L(_,m)){let z=_[m.Symbol.Schema],F=_[m.Symbol.Name];return{sql:z===void 0||_[z6]?G(F):G(z)+"."+G(F),params:[]}}if(L(_,q0)){let z=X.getColumnCasing(_);if($.invokeSource==="indexes")return{sql:G(z),params:[]};let F=_.table[m.Symbol.Schema];return{sql:_.table[z6]||F===void 0?G(_.table[m.Symbol.Name])+"."+G(z):G(F)+"."+G(_.table[m.Symbol.Name])+"."+G(z),params:[]}}if(L(_,g1)){let z=_[f0].schema,F=_[f0].name;return{sql:z===void 0||_[f0].isAlias?G(F):G(z)+"."+G(F),params:[]}}if(L(_,WW)){if(L(_.value,x$))return{sql:J(Q.value++,_),params:[_],typings:["none"]};let z=_.value===null?null:_.encoder.mapToDriverValue(_.value);if(L(z,u))return this.buildQueryFromSourceParams([z],Y);if(T)return{sql:this.mapInlineParam(z,Y),params:[]};let F=["none"];if(H)F=[H(_.encoder)];return{sql:J(Q.value++,z),params:[z],typings:F}}if(L(_,x$))return{sql:J(Q.value++,_),params:[_],typings:["none"]};if(L(_,u.Aliased)&&_.fieldAlias!==void 0)return{sql:G(_.fieldAlias),params:[]};if(L(_,H1)){if(_._.isWith)return{sql:G(_._.alias),params:[]};return this.buildQueryFromSourceParams([new T1("("),_._.sql,new T1(") "),new wX(_._.alias)],Y)}if(GT(_)){if(_.schema)return{sql:G(_.schema)+"."+G(_.enumName),params:[]};return{sql:G(_.enumName),params:[]}}if(n5(_)){if(_.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([_.getSQL()],Y);return this.buildQueryFromSourceParams([new T1("("),_.getSQL(),new T1(")")],Y)}if(T)return{sql:this.mapInlineParam(_,Y),params:[]};return{sql:J(Q.value++,_),params:[_],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 Y=W.toString();if(Y==="[object Object]")return $(JSON.stringify(W));return $(Y)}throw new Error("Unexpected param value: "+W)}getSQL(){return this}as(W){if(W===void 0)return this;return new u.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 wX{constructor(W){this.value=W}static[D]="Name";brand;getSQL(){return new u([this])}}function zT(W){return typeof W==="object"&&W!==null&&"mapToDriverValue"in W&&typeof W.mapToDriverValue==="function"}var FT={mapFromDriverValue:(W)=>W},wT={mapToDriverValue:(W)=>W},Ox={...FT,...wT};class WW{constructor(W,$=wT){this.value=W,this.encoder=$}static[D]="Param";brand;getSQL(){return new u([this])}}function M(W,...$){let Y=[];if($.length>0||W.length>0&&W[0]!=="")Y.push(new T1(W[0]));for(let[X,G]of $.entries())Y.push(G,new T1(W[X+1]));return new u(Y)}((W)=>{function $(){return new u([])}W.empty=$;function Y(Q){return new u(Q)}W.fromList=Y;function X(Q){return new u([new T1(Q)])}W.raw=X;function G(Q,_){let z=[];for(let[F,w]of Q.entries()){if(F>0&&_!==void 0)z.push(_);z.push(w)}return new u(z)}W.join=G;function J(Q){return new wX(Q)}W.identifier=J;function H(Q){return new x$(Q)}W.placeholder=H;function T(Q,_){return new WW(Q,_)}W.param=T})(M||(M={}));((W)=>{class ${constructor(Y,X){this.sql=Y,this.fieldAlias=X}static[D]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}W.Aliased=$})(u||(u={}));class x${constructor(W){this.name=W}static[D]="Placeholder";getSQL(){return new u([this])}}function r5(W,$){return W.map((Y)=>{if(L(Y,x$)){if(!(Y.name in $))throw new Error(`No value for placeholder "${Y.name}" was provided`);return $[Y.name]}if(L(Y,WW)&&L(Y.value,x$)){if(!(Y.value.name in $))throw new Error(`No value for placeholder "${Y.value.name}" was provided`);return Y.encoder.mapToDriverValue($[Y.value.name])}return Y})}var zO=Symbol.for("drizzle:IsDrizzleView");class g1{static[D]="View";[f0];[zO]=!0;constructor({name:W,schema:$,selectedFields:Y,query:X}){this[f0]={name:W,originalName:W,schema:$,selectedFields:Y,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new u([this])}}q0.prototype.getSQL=function(){return new u([this])};m.prototype.getSQL=function(){return new u([this])};H1.prototype.getSQL=function(){return new u([this])};class K8{constructor(W){this.table=W}static[D]="ColumnAliasProxyHandler";get(W,$){if($==="table")return this.table;return W[$]}}class F6{constructor(W,$){this.alias=W,this.replaceOriginalName=$}static[D]="TableAliasProxyHandler";get(W,$){if($===m.Symbol.IsAlias)return!0;if($===m.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===m.Symbol.OriginalName)return this.alias;if($===f0)return{...W[f0],name:this.alias,isAlias:!0};if($===m.Symbol.Columns){let X=W[m.Symbol.Columns];if(!X)return X;let G={};return Object.keys(X).map((J)=>{G[J]=new Proxy(X[J],new K8(new Proxy(W,this)))}),G}let Y=W[$];if(L(Y,q0))return new Proxy(Y,new K8(new Proxy(W,this)));return Y}}function UX(W,$){return new Proxy(W,new F6($,!1))}function mW(W,$){return new Proxy(W,new K8(new Proxy(W.table,new F6($,!1))))}function t5(W,$){return new u.Aliased(w6(W.sql,$),W.fieldAlias)}function w6(W,$){return M.join(W.queryChunks.map((Y)=>{if(L(Y,q0))return mW(Y,$);if(L(Y,u))return w6(Y,$);if(L(Y,u.Aliased))return t5(Y,$);return Y}))}class DX extends Error{static[D]="DrizzleError";constructor({message:W,cause:$}){super(W);this.name="DrizzleError",this.cause=$}}class a5 extends DX{static[D]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class UT{static[D]="ConsoleLogWriter";write(W){console.log(W)}}class s5{static[D]="DefaultLogger";writer;constructor(W){this.writer=W?.writer??new UT}logQuery(W,$){let Y=$.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),X=Y.length?` -- params: [${Y.join(", ")}]`:"";this.writer.write(`Query: ${W}${X}`)}}class e5{static[D]="NoopLogger";logQuery(){}}class I1{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 DT(W,$,Y){let X={},G=W.reduce((J,{path:H,field:T},Q)=>{let _;if(L(T,q0))_=T;else if(L(T,u))_=T.decoder;else _=T.sql.decoder;let z=J;for(let[F,w]of H.entries())if(F<H.length-1){if(!(w in z))z[w]={};z=z[w]}else{let O=$[Q],V=z[w]=O===null?null:_.mapFromDriverValue(O);if(Y&&L(T,q0)&&H.length===2){let E=H[0];if(!(E in X))X[E]=V===null?w1(T.table):!1;else if(typeof X[E]==="string"&&X[E]!==w1(T.table))X[E]=!1}}return J},{});if(Y&&Object.keys(X).length>0){for(let[J,H]of Object.entries(X))if(typeof H==="string"&&!Y[H])G[J]=null}return G}function QW(W,$){return Object.entries(W).reduce((Y,[X,G])=>{if(typeof X!=="string")return Y;let J=$?[...$,X]:[X];if(L(G,q0)||L(G,u)||L(G,u.Aliased))Y.push({path:J,field:G});else if(L(G,m))Y.push(...QW(G[m.Symbol.Columns],J));else Y.push(...QW(G,J));return Y},[])}function U6(W,$){let Y=Object.keys(W),X=Object.keys($);if(Y.length!==X.length)return!1;for(let[G,J]of Y.entries())if(J!==X[G])return!1;return!0}function MX(W,$){let Y=Object.entries($).filter(([,X])=>X!==void 0).map(([X,G])=>{if(L(G,u)||L(G,q0))return[X,G];else return[X,new WW(G,W[m.Symbol.Columns][X])]});if(Y.length===0)throw new Error("No values to set");return Object.fromEntries(Y)}function MT(W,$){for(let Y of $)for(let X of Object.getOwnPropertyNames(Y.prototype)){if(X==="constructor")continue;Object.defineProperty(W.prototype,X,Object.getOwnPropertyDescriptor(Y.prototype,X)||Object.create(null))}}function VT(W){return W[m.Symbol.Columns]}function J$(W){return L(W,H1)?W._.alias:L(W,g1)?W[f0].name:L(W,u)?void 0:W[m.Symbol.IsAlias]?W[m.Symbol.Name]:W[m.Symbol.BaseName]}function O0(W,$){return{name:typeof W==="string"&&W.length>0?W:"",config:typeof W==="object"?W:$}}function OT(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 v$ extends c{static[D]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(W){if(W){let{name:$,...Y}=W;this.config.generatedIdentity={type:"always",sequenceName:$,sequenceOptions:Y}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(W){if(W){let{name:$,...Y}=W;this.config.generatedIdentity={type:"byDefault",sequenceName:$,sequenceOptions:Y}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class KT extends v${static[D]="PgBigInt53Builder";constructor(W){super(W,"number","PgBigInt53")}build(W){return new ET(W,this.config)}}class ET extends b{static[D]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class AT extends v${static[D]="PgBigInt64Builder";constructor(W){super(W,"bigint","PgBigInt64")}build(W){return new LT(W,this.config)}}class LT extends b{static[D]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(W){return BigInt(W)}}function ZT(W,$){let{name:Y,config:X}=O0(W,$);if(X.mode==="number")return new KT(Y);return new AT(Y)}class NT extends c{static[D]="PgBigSerial53Builder";constructor(W){super(W,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new RT(W,this.config)}}class RT extends b{static[D]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class BT extends c{static[D]="PgBigSerial64Builder";constructor(W){super(W,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(W){return new ST(W,this.config)}}class ST extends b{static[D]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(W){return BigInt(W)}}function qT(W,$){let{name:Y,config:X}=O0(W,$);if(X.mode==="number")return new NT(Y);return new BT(Y)}class CT extends c{static[D]="PgBooleanBuilder";constructor(W){super(W,"boolean","PgBoolean")}build(W){return new kT(W,this.config)}}class kT extends b{static[D]="PgBoolean";getSQLType(){return"boolean"}}function D6(W){return new CT(W??"")}class jT extends c{static[D]="PgCharBuilder";constructor(W,$){super(W,"string","PgChar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new IT(W,this.config)}}class IT extends b{static[D]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function PT(W,$={}){let{name:Y,config:X}=O0(W,$);return new jT(Y,X)}class fT extends c{static[D]="PgCidrBuilder";constructor(W){super(W,"string","PgCidr")}build(W){return new bT(W,this.config)}}class bT extends b{static[D]="PgCidr";getSQLType(){return"cidr"}}function xT(W){return new fT(W??"")}class vT extends c{static[D]="PgCustomColumnBuilder";constructor(W,$,Y){super(W,"custom","PgCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=Y}build(W){return new yT(W,this.config)}}class yT extends b{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 hT(W){return($,Y)=>{let{name:X,config:G}=O0($,Y);return new vT(X,G,W)}}class H$ extends c{static[D]="PgDateColumnBaseBuilder";defaultNow(){return this.default(M`now()`)}}class gT extends H${static[D]="PgDateBuilder";constructor(W){super(W,"date","PgDate")}build(W){return new VX(W,this.config)}}class VX extends b{static[D]="PgDate";getSQLType(){return"date"}mapFromDriverValue(W){return new Date(W)}mapToDriverValue(W){return W.toISOString()}}class mT extends H${static[D]="PgDateStringBuilder";constructor(W){super(W,"string","PgDateString")}build(W){return new OX(W,this.config)}}class OX extends b{static[D]="PgDateString";getSQLType(){return"date"}}function pT(W,$){let{name:Y,config:X}=O0(W,$);if(X?.mode==="date")return new gT(Y);return new mT(Y)}class uT extends c{static[D]="PgDoublePrecisionBuilder";constructor(W){super(W,"number","PgDoublePrecision")}build(W){return new cT(W,this.config)}}class cT extends b{static[D]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseFloat(W);return W}}function dT(W){return new uT(W??"")}class lT extends c{static[D]="PgInetBuilder";constructor(W){super(W,"string","PgInet")}build(W){return new oT(W,this.config)}}class oT extends b{static[D]="PgInet";getSQLType(){return"inet"}}function iT(W){return new lT(W??"")}class nT extends v${static[D]="PgIntegerBuilder";constructor(W){super(W,"number","PgInteger")}build(W){return new rT(W,this.config)}}class rT extends b{static[D]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseInt(W);return W}}function M6(W){return new nT(W??"")}class tT extends c{static[D]="PgIntervalBuilder";constructor(W,$){super(W,"string","PgInterval");this.config.intervalConfig=$}build(W){return new aT(W,this.config)}}class aT extends b{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 sT(W,$={}){let{name:Y,config:X}=O0(W,$);return new tT(Y,X)}class eT extends c{static[D]="PgJsonBuilder";constructor(W){super(W,"json","PgJson")}build(W){return new KX(W,this.config)}}class KX extends b{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 WQ(W){return new eT(W??"")}class $Q extends c{static[D]="PgJsonbBuilder";constructor(W){super(W,"json","PgJsonb")}build(W){return new EX(W,this.config)}}class EX extends b{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 YQ(W){return new $Q(W??"")}class XQ extends c{static[D]="PgLineBuilder";constructor(W){super(W,"array","PgLine")}build(W){return new GQ(W,this.config)}}class GQ extends b{static[D]="PgLine";getSQLType(){return"line"}mapFromDriverValue(W){let[$,Y,X]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(Y),Number.parseFloat(X)]}mapToDriverValue(W){return`{${W[0]},${W[1]},${W[2]}}`}}class JQ extends c{static[D]="PgLineABCBuilder";constructor(W){super(W,"json","PgLineABC")}build(W){return new HQ(W,this.config)}}class HQ extends b{static[D]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(W){let[$,Y,X]=W.slice(1,-1).split(",");return{a:Number.parseFloat($),b:Number.parseFloat(Y),c:Number.parseFloat(X)}}mapToDriverValue(W){return`{${W.a},${W.b},${W.c}}`}}function TQ(W,$){let{name:Y,config:X}=O0(W,$);if(!X?.mode||X.mode==="tuple")return new XQ(Y);return new JQ(Y)}class QQ extends c{static[D]="PgMacaddrBuilder";constructor(W){super(W,"string","PgMacaddr")}build(W){return new _Q(W,this.config)}}class _Q extends b{static[D]="PgMacaddr";getSQLType(){return"macaddr"}}function zQ(W){return new QQ(W??"")}class FQ extends c{static[D]="PgMacaddr8Builder";constructor(W){super(W,"string","PgMacaddr8")}build(W){return new wQ(W,this.config)}}class wQ extends b{static[D]="PgMacaddr8";getSQLType(){return"macaddr8"}}function UQ(W){return new FQ(W??"")}class DQ extends c{static[D]="PgNumericBuilder";constructor(W,$,Y){super(W,"string","PgNumeric");this.config.precision=$,this.config.scale=Y}build(W){return new AX(W,this.config)}}class AX extends b{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 MQ extends c{static[D]="PgNumericNumberBuilder";constructor(W,$,Y){super(W,"number","PgNumericNumber");this.config.precision=$,this.config.scale=Y}build(W){return new VQ(W,this.config)}}class VQ extends b{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 OQ extends c{static[D]="PgNumericBigIntBuilder";constructor(W,$,Y){super(W,"bigint","PgNumericBigInt");this.config.precision=$,this.config.scale=Y}build(W){return new KQ(W,this.config)}}class KQ extends b{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 EQ(W,$){let{name:Y,config:X}=O0(W,$),G=X?.mode;return G==="number"?new MQ(Y,X?.precision,X?.scale):G==="bigint"?new OQ(Y,X?.precision,X?.scale):new DQ(Y,X?.precision,X?.scale)}class AQ extends c{static[D]="PgPointTupleBuilder";constructor(W){super(W,"array","PgPointTuple")}build(W){return new LQ(W,this.config)}}class LQ extends b{static[D]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,Y]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(Y)]}return[W.x,W.y]}mapToDriverValue(W){return`(${W[0]},${W[1]})`}}class ZQ extends c{static[D]="PgPointObjectBuilder";constructor(W){super(W,"json","PgPointObject")}build(W){return new NQ(W,this.config)}}class NQ extends b{static[D]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,Y]=W.slice(1,-1).split(",");return{x:Number.parseFloat($),y:Number.parseFloat(Y)}}return W}mapToDriverValue(W){return`(${W.x},${W.y})`}}function RQ(W,$){let{name:Y,config:X}=O0(W,$);if(!X?.mode||X.mode==="tuple")return new AQ(Y);return new ZQ(Y)}function FO(W){let $=[];for(let Y=0;Y<W.length;Y+=2)$.push(Number.parseInt(W.slice(Y,Y+2),16));return new Uint8Array($)}function BQ(W,$){let Y=new ArrayBuffer(8),X=new DataView(Y);for(let G=0;G<8;G++)X.setUint8(G,W[$+G]);return X.getFloat64(0,!0)}function W7(W){let $=FO(W),Y=0,X=$[Y];Y+=1;let G=new DataView($.buffer),J=G.getUint32(Y,X===1);Y+=4;let H;if(J&536870912)H=G.getUint32(Y,X===1),Y+=4;if((J&65535)===1){let T=BQ($,Y);Y+=8;let Q=BQ($,Y);return Y+=8,[T,Q]}throw new Error("Unsupported geometry type")}class SQ extends c{static[D]="PgGeometryBuilder";constructor(W){super(W,"array","PgGeometry")}build(W){return new qQ(W,this.config)}}class qQ extends b{static[D]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){return W7(W)}mapToDriverValue(W){return`point(${W[0]} ${W[1]})`}}class CQ extends c{static[D]="PgGeometryObjectBuilder";constructor(W){super(W,"json","PgGeometryObject")}build(W){return new kQ(W,this.config)}}class kQ extends b{static[D]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){let $=W7(W);return{x:$[0],y:$[1]}}mapToDriverValue(W){return`point(${W.x} ${W.y})`}}function jQ(W,$){let{name:Y,config:X}=O0(W,$);if(!X?.mode||X.mode==="tuple")return new SQ(Y);return new CQ(Y)}class IQ extends c{static[D]="PgRealBuilder";constructor(W,$){super(W,"number","PgReal");this.config.length=$}build(W){return new PQ(W,this.config)}}class PQ extends b{static[D]="PgReal";constructor(W,$){super(W,$)}getSQLType(){return"real"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number.parseFloat(W);return W}}function fQ(W){return new IQ(W??"")}class bQ extends c{static[D]="PgSerialBuilder";constructor(W){super(W,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new xQ(W,this.config)}}class xQ extends b{static[D]="PgSerial";getSQLType(){return"serial"}}function vQ(W){return new bQ(W??"")}class yQ extends v${static[D]="PgSmallIntBuilder";constructor(W){super(W,"number","PgSmallInt")}build(W){return new hQ(W,this.config)}}class hQ extends b{static[D]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number(W);return W}}function gQ(W){return new yQ(W??"")}class mQ extends c{static[D]="PgSmallSerialBuilder";constructor(W){super(W,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new pQ(W,this.config)}}class pQ extends b{static[D]="PgSmallSerial";getSQLType(){return"smallserial"}}function uQ(W){return new mQ(W??"")}class cQ extends c{static[D]="PgTextBuilder";constructor(W,$){super(W,"string","PgText");this.config.enumValues=$.enum}build(W){return new dQ(W,this.config)}}class dQ extends b{static[D]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function lQ(W,$={}){let{name:Y,config:X}=O0(W,$);return new cQ(Y,X)}class oQ extends H${constructor(W,$,Y){super(W,"string","PgTime");this.withTimezone=$,this.precision=Y,this.config.withTimezone=$,this.config.precision=Y}static[D]="PgTimeBuilder";build(W){return new LX(W,this.config)}}class LX extends b{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 iQ(W,$={}){let{name:Y,config:X}=O0(W,$);return new oQ(Y,X.withTimezone??!1,X.precision)}class nQ extends H${static[D]="PgTimestampBuilder";constructor(W,$,Y){super(W,"date","PgTimestamp");this.config.withTimezone=$,this.config.precision=Y}build(W){return new ZX(W,this.config)}}class ZX extends b{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 rQ extends H${static[D]="PgTimestampStringBuilder";constructor(W,$,Y){super(W,"string","PgTimestampString");this.config.withTimezone=$,this.config.precision=Y}build(W){return new NX(W,this.config)}}class NX extends b{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 BW(W,$={}){let{name:Y,config:X}=O0(W,$);if(X?.mode==="string")return new rQ(Y,X.withTimezone??!1,X.precision);return new nQ(Y,X?.withTimezone??!1,X?.precision)}class tQ extends c{static[D]="PgUUIDBuilder";constructor(W){super(W,"string","PgUUID")}defaultRandom(){return this.default(M`gen_random_uuid()`)}build(W){return new RX(W,this.config)}}class RX extends b{static[D]="PgUUID";getSQLType(){return"uuid"}}function _W(W){return new tQ(W??"")}class aQ extends c{static[D]="PgVarcharBuilder";constructor(W,$){super(W,"string","PgVarchar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new sQ(W,this.config)}}class sQ extends b{static[D]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function P1(W,$={}){let{name:Y,config:X}=O0(W,$);return new aQ(Y,X)}class eQ extends c{static[D]="PgBinaryVectorBuilder";constructor(W,$){super(W,"string","PgBinaryVector");this.config.dimensions=$.dimensions}build(W){return new W_(W,this.config)}}class W_ extends b{static[D]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function $_(W,$){let{name:Y,config:X}=O0(W,$);return new eQ(Y,X)}class Y_ extends c{static[D]="PgHalfVectorBuilder";constructor(W,$){super(W,"array","PgHalfVector");this.config.dimensions=$.dimensions}build(W){return new X_(W,this.config)}}class X_ extends b{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 G_(W,$){let{name:Y,config:X}=O0(W,$);return new Y_(Y,X)}class J_ extends c{static[D]="PgSparseVectorBuilder";constructor(W,$){super(W,"string","PgSparseVector");this.config.dimensions=$.dimensions}build(W){return new H_(W,this.config)}}class H_ extends b{static[D]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function T_(W,$){let{name:Y,config:X}=O0(W,$);return new J_(Y,X)}class Q_ extends c{static[D]="PgVectorBuilder";constructor(W,$){super(W,"array","PgVector");this.config.dimensions=$.dimensions}build(W){return new __(W,this.config)}}class __ extends b{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 z_(W,$){let{name:Y,config:X}=O0(W,$);return new Q_(Y,X)}function F_(){return{bigint:ZT,bigserial:qT,boolean:D6,char:PT,cidr:xT,customType:hT,date:pT,doublePrecision:dT,inet:iT,integer:M6,interval:sT,json:WQ,jsonb:YQ,line:TQ,macaddr:zQ,macaddr8:UQ,numeric:EQ,point:RQ,geometry:jQ,real:fQ,serial:vQ,smallint:gQ,smallserial:uQ,text:lQ,time:iQ,timestamp:BW,uuid:_W,varchar:P1,bit:$_,halfvec:G_,sparsevec:T_,vector:z_}}var $7=Symbol.for("drizzle:PgInlineForeignKeys"),w_=Symbol.for("drizzle:EnableRLS");class M1 extends m{static[D]="PgTable";static Symbol=Object.assign({},m.Symbol,{InlineForeignKeys:$7,EnableRLS:w_});[$7]=[];[w_]=!1;[m.Symbol.ExtraConfigBuilder]=void 0;[m.Symbol.ExtraConfigColumns]={}}function wO(W,$,Y,X,G=W){let J=new M1(W,X,G),H=typeof $==="function"?$(F_()):$,T=Object.fromEntries(Object.entries(H).map(([z,F])=>{let w=F;w.setName(z);let O=w.build(J);return J[$7].push(...w.buildForeignKeys(O,J)),[z,O]})),Q=Object.fromEntries(Object.entries(H).map(([z,F])=>{let w=F;w.setName(z);let O=w.buildExtraConfigColumn(J);return[z,O]})),_=Object.assign(J,T);if(_[m.Symbol.Columns]=T,_[m.Symbol.ExtraConfigColumns]=Q,Y)_[M1.Symbol.ExtraConfigBuilder]=Y;return Object.assign(_,{enableRLS:()=>{return _[M1.Symbol.EnableRLS]=!0,_}})}var y$=(W,$,Y)=>{return wO(W,$,Y,void 0)};function U_(...W){if(W[0].columns)return new V6(W[0].columns,W[0].name);return new V6(W)}class V6{static[D]="PgPrimaryKeyBuilder";columns;name;constructor(W,$){this.columns=W,this.name=$}build(W){return new D_(W,this.columns,this.name)}}class D_{constructor(W,$,Y){this.table=W,this.columns=$,this.name=Y}static[D]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[M1.Symbol.Name]}_${this.columns.map((W)=>W.name).join("_")}_pk`}}function m1(W,$){if(zT($)&&!n5(W)&&!L(W,WW)&&!L(W,x$)&&!L(W,q0)&&!L(W,m)&&!L(W,g1))return new WW(W,$);return W}var BX=(W,$)=>{return M`${W} = ${m1($,W)}`},M_=(W,$)=>{return M`${W} <> ${m1($,W)}`};function O6(...W){let $=W.filter((Y)=>Y!==void 0);if($.length===0)return;if($.length===1)return new u($);return new u([new T1("("),M.join($,new T1(" and ")),new T1(")")])}function V_(...W){let $=W.filter((Y)=>Y!==void 0);if($.length===0)return;if($.length===1)return new u($);return new u([new T1("("),M.join($,new T1(" or ")),new T1(")")])}function O_(W){return M`not ${W}`}var SX=(W,$)=>{return M`${W} > ${m1($,W)}`},K_=(W,$)=>{return M`${W} >= ${m1($,W)}`},E_=(W,$)=>{return M`${W} < ${m1($,W)}`},A_=(W,$)=>{return M`${W} <= ${m1($,W)}`};function L_(W,$){if(Array.isArray($)){if($.length===0)return M`false`;return M`${W} in ${$.map((Y)=>m1(Y,W))}`}return M`${W} in ${m1($,W)}`}function Z_(W,$){if(Array.isArray($)){if($.length===0)return M`true`;return M`${W} not in ${$.map((Y)=>m1(Y,W))}`}return M`${W} not in ${m1($,W)}`}function N_(W){return M`${W} is null`}function R_(W){return M`${W} is not null`}function B_(W){return M`exists ${W}`}function S_(W){return M`not exists ${W}`}function q_(W,$,Y){return M`${W} between ${m1($,W)} and ${m1(Y,W)}`}function C_(W,$,Y){return M`${W} not between ${m1($,W)} and ${m1(Y,W)}`}function k_(W,$){return M`${W} like ${$}`}function j_(W,$){return M`${W} not like ${$}`}function I_(W,$){return M`${W} ilike ${$}`}function P_(W,$){return M`${W} not ilike ${$}`}function f_(W){return M`${W} asc`}function b_(W){return M`${W} desc`}class Y7{constructor(W,$,Y){this.sourceTable=W,this.referencedTable=$,this.relationName=Y,this.referencedTableName=$[m.Symbol.Name]}static[D]="Relation";referencedTableName;fieldName}class x_{constructor(W,$){this.table=W,this.config=$}static[D]="Relations"}class h$ extends Y7{constructor(W,$,Y,X){super(W,$,Y?.relationName);this.config=Y,this.isNullable=X}static[D]="One";withFieldName(W){let $=new h$(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=W,$}}class K6 extends Y7{constructor(W,$,Y){super(W,$,Y?.relationName);this.config=Y}static[D]="Many";withFieldName(W){let $=new K6(this.sourceTable,this.referencedTable,this.config);return $.fieldName=W,$}}function v_(){return{and:O6,between:q_,eq:BX,exists:B_,gt:SX,gte:K_,ilike:I_,inArray:L_,isNull:N_,isNotNull:R_,like:k_,lt:E_,lte:A_,ne:M_,not:O_,notBetween:C_,notExists:S_,notLike:j_,notIlike:P_,notInArray:Z_,or:V_,sql:M}}function y_(){return{sql:M,asc:f_,desc:b_}}function h_(W,$){if(Object.keys(W).length===1&&"default"in W&&!L(W.default,m))W=W.default;let Y={},X={},G={};for(let[J,H]of Object.entries(W))if(L(H,m)){let T=L2(H),Q=X[T];Y[T]=J,G[J]={tsName:J,dbName:H[m.Symbol.Name],schema:H[m.Symbol.Schema],columns:H[m.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(H[m.Symbol.Columns]))if(z.primary)G[J].primaryKey.push(z);let _=H[m.Symbol.ExtraConfigBuilder]?.(H[m.Symbol.ExtraConfigColumns]);if(_){for(let z of Object.values(_))if(L(z,V6))G[J].primaryKey.push(...z.columns)}}else if(L(H,x_)){let T=L2(H.table),Q=Y[T],_=H.config($(H.table)),z;for(let[F,w]of Object.entries(_))if(Q){let O=G[Q];if(O.relations[F]=w,z)O.primaryKey.push(...z)}else{if(!(T in X))X[T]={relations:{},primaryKey:z};X[T].relations[F]=w}}return{tables:G,tableNamesMap:Y}}function UO(W){return function $(Y,X){return new h$(W,Y,X,X?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function DO(W){return function $(Y,X){return new K6(W,Y,X)}}function g_(W,$,Y){if(L(Y,h$)&&Y.config)return{fields:Y.config.fields,references:Y.config.references};let X=$[L2(Y.referencedTable)];if(!X)throw new Error(`Table "${Y.referencedTable[m.Symbol.Name]}" not found in schema`);let G=W[X];if(!G)throw new Error(`Table "${X}" not found in schema`);let J=Y.sourceTable,H=$[L2(J)];if(!H)throw new Error(`Table "${J[m.Symbol.Name]}" not found in schema`);let T=[];for(let Q of Object.values(G.relations))if(Y.relationName&&Y!==Q&&Q.relationName===Y.relationName||!Y.relationName&&Q.referencedTable===Y.sourceTable)T.push(Q);if(T.length>1)throw Y.relationName?new Error(`There are multiple relations with name "${Y.relationName}" in table "${X}"`):new Error(`There are multiple relations between "${X}" and "${Y.sourceTable[m.Symbol.Name]}". Please specify relation name`);if(T[0]&&L(T[0],h$)&&T[0].config)return{fields:T[0].config.references,references:T[0].config.fields};throw new Error(`There is not enough information to infer relation "${H}.${Y.fieldName}"`)}function m_(W){return{one:UO(W),many:DO(W)}}function qX(W,$,Y,X,G=(J)=>J){let J={};for(let[H,T]of X.entries())if(T.isJson){let Q=$.relations[T.tsKey],_=Y[H],z=typeof _==="string"?JSON.parse(_):_;J[T.tsKey]=L(Q,h$)?z&&qX(W,W[T.relationTableTsKey],z,T.selection,G):z.map((F)=>qX(W,W[T.relationTableTsKey],F,T.selection,G))}else{let Q=G(Y[H]),_=T.field,z;if(L(_,q0))z=_;else if(L(_,u))z=_.decoder;else z=_.sql.decoder;J[T.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return J}import XZ from"path";import hO from"os";import gO from"fs";var CX=new Map,X7=new Map,G7=Symbol("OriginError"),E8={};class zW extends Promise{constructor(W,$,Y,X,G={}){let J,H;super((T,Q)=>{J=T,H=Q});this.tagged=Array.isArray(W.raw),this.strings=W,this.args=$,this.handler=Y,this.canceller=X,this.options=G,this.state=null,this.statement=null,this.resolve=(T)=>(this.active=!1,J(T)),this.reject=(T)=>(this.active=!1,H(T)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[G7]=this.handler.debug?new Error:this.tagged&&MO(this.strings)}get origin(){return(this.handler.debug?this[G7].stack:this.tagged&&X7.has(this.strings)?X7.get(this.strings):X7.set(this.strings,this[G7].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 Y;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};Y&&Y();let X=new Promise((G,J)=>{this.cursorFn=(H)=>{return G({value:H,done:!1}),new Promise((T)=>Y=T)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(H)=>(this.active=!1,J(H))});return this.execute(),X},return(){return Y&&Y(E8),{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 MO(W){if(CX.has(W))return CX.get(W);let $=Error.stackTraceLimit;return Error.stackTraceLimit=4,CX.set(W,new Error),Error.stackTraceLimit=$,CX.get(W)}class A8 extends Error{constructor(W){super(W.message);this.name=this.constructor.name,Object.assign(this,W)}}var a0={connection:p_,postgres:u_,generic:c_,notSupported:d_};function p_(W,$,Y){let{host:X,port:G}=Y||$,J=Object.assign(new Error("write "+W+" "+($.path||X+":"+G)),{code:W,errno:W,address:$.path||X},$.path?{}:{port:G});return Error.captureStackTrace(J,p_),J}function u_(W){let $=new A8(W);return Error.captureStackTrace($,u_),$}function c_(W,$){let Y=Object.assign(new Error(W+": "+$),{code:W});return Error.captureStackTrace(Y,c_),Y}function d_(W){let $=Object.assign(new Error(W+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:W});return Error.captureStackTrace($,d_),$}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 IX{then(){J7()}catch(){J7()}finally(){J7()}}class Z6 extends IX{constructor(W){super();this.value=bX(W)}}class pW extends IX{constructor(W,$,Y){super();this.value=W,this.type=$,this.array=Y}}class PX extends IX{constructor(W,$){super();this.first=W,this.rest=$}build(W,$,Y,X){let G=OO.map(([J,H])=>({fn:H,i:W.search(J)})).sort((J,H)=>J.i-H.i).pop();return G.i===-1?z7(this.first,X):G.fn(this.first,this.rest,$,Y,X)}}function fX(W,$,Y,X){let G=W instanceof pW?W.value:W;if(G===void 0){if(W instanceof pW?W.value=X.transform.undefined:G=W=X.transform.undefined,G===void 0)throw a0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+Y.push(W instanceof pW?($.push(W.value),W.array?W.array[W.type||jX(W.value)]||W.type||n_(W.value):W.type):($.push(W),jX(W)))}var o_=t_(VO);function Q7(W,$,Y,X,G,J){for(let H=1;H<W.strings.length;H++)$+=_7($,Y,X,G,J)+W.strings[H],Y=W.args[H];return $}function _7(W,$,Y,X,G){return $ instanceof PX?$.build(W,Y,X,G):$ instanceof zW?T7($,Y,X,G):$ instanceof Z6?$.value:$&&$[0]instanceof zW?$.reduce((J,H)=>J+" "+T7(H,Y,X,G),""):fX($,Y,X,G)}function T7(W,$,Y,X){return W.fragment=!0,Q7(W,W.strings[0],W.args[0],$,Y,X)}function i_(W,$,Y,X,G){return W.map((J)=>"("+X.map((H)=>_7("values",J[H],$,Y,G)).join(",")+")").join(",")}function l_(W,$,Y,X,G){let J=Array.isArray(W[0]),H=$.length?$.flat():Object.keys(J?W[0]:W);return i_(J?W:[W],Y,X,H,G)}function kX(W,$,Y,X,G){if(typeof W==="string"&&(W=[W].concat($)),Array.isArray(W))return z7(W,G);let J;return($.length?$.flat():Object.keys(W)).map((T)=>{return J=W[T],(J instanceof zW?T7(J,Y,X,G):J instanceof Z6?J.value:fX(J,Y,X,G))+" as "+bX(G.transform.column.to?G.transform.column.to(T):T)}).join(",")}var OO=Object.entries({values:l_,in:(...W)=>{let $=l_(...W);return $==="()"?"(null)":$},select:kX,as:kX,returning:kX,"\\(":kX,update(W,$,Y,X,G){return($.length?$.flat():Object.keys(W)).map((J)=>bX(G.transform.column.to?G.transform.column.to(J):J)+"="+_7("values",W[J],Y,X,G))},insert(W,$,Y,X,G){let J=$.length?$.flat():Object.keys(Array.isArray(W)?W[0]:W);return"("+z7(J,G)+")values"+i_(Array.isArray(W)?W:[W],Y,X,J,G)}}).map(([W,$])=>[new RegExp("((?:^|[\\s(])"+W+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),$]);function J7(){throw a0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:KO,parsers:EO}=o_;function n_(W){if(Array.isArray(W))return n_(W[0]);return typeof W==="string"?1009:0}var r_=function(W){let $=t_(W||{});return{serializers:Object.assign({},KO,$.serializers),parsers:Object.assign({},EO,$.parsers)}};function t_(W){return Object.keys(W).reduce(($,Y)=>{if(W[Y].from&&[].concat(W[Y].from).forEach((X)=>$.parsers[X]=W[Y].parse),W[Y].serialize)$.serializers[W[Y].to]=W[Y].serialize,W[Y].from&&[].concat(W[Y].from).forEach((X)=>$.serializers[X]=W[Y].serialize);return $},{parsers:{},serializers:{}})}function z7(W,{transform:{column:$}}){return W.map((Y)=>bX($.to?$.to(Y):Y)).join(",")}var bX=function W($){return'"'+$.replace(/"/g,'""').replace(/\./g,'"."')+'"'},jX=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,LO=/"/g;function ZO(W){return W.replace(AO,"\\\\").replace(LO,"\\\"")}var a_=function W($,Y,X,G){if(Array.isArray($)===!1)return $;if(!$.length)return"{}";let J=$[0],H=G===1020?";":",";if(Array.isArray(J)&&!J.type)return"{"+$.map((T)=>W(T,Y,X,G)).join(H)+"}";return"{"+$.map((T)=>{if(T===void 0){if(T=X.transform.undefined,T===void 0)throw a0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return T===null?"null":'"'+ZO(Y?Y(T.type?T.value:T):""+T)+'"'}).join(H)+"}"},H7={i:0,char:null,str:"",quoted:!1,last:0},s_=function W($,Y,X){return H7.i=H7.last=0,e_(H7,$,Y,X)};function e_(W,$,Y,X){let G=[],J=X===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(Y?Y(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(e_(W,$,Y,X));else if(W.char==="}"){W.quoted=!1,W.last<W.i&&G.push(Y?Y($.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(Y?Y($.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(Y?Y($.slice(W.last,W.i+1)):$.slice(W.last,W.i+1)),G}var Z2=(W)=>{let $=W[0];for(let Y=1;Y<W.length;Y++)$+=W[Y]==="_"?W[++Y].toUpperCase():W[Y];return $},N2=(W)=>{let $=W[0].toUpperCase();for(let Y=1;Y<W.length;Y++)$+=W[Y]==="_"?W[++Y].toUpperCase():W[Y];return $},R2=(W)=>W.replace(/_/g,"-"),E6=(W)=>W.replace(/([A-Z])/g,"_$1").toLowerCase(),A6=(W)=>(W.slice(0,1)+W.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),L6=(W)=>W.replace(/-/g,"_");function F7(W){return function $(Y,X){return typeof Y==="object"&&Y!==null&&(X.type===114||X.type===3802)?Array.isArray(Y)?Y.map((G)=>$(G,X)):Object.entries(Y).reduce((G,[J,H])=>Object.assign(G,{[W(J)]:$(H,X)}),{}):Y}}Z2.column={from:Z2};Z2.value={from:F7(Z2)};E6.column={to:E6};var w7={...Z2};w7.column.to=E6;N2.column={from:N2};N2.value={from:F7(N2)};A6.column={to:A6};var U7={...N2};U7.column.to=A6;R2.column={from:R2};R2.value={from:F7(R2)};L6.column={to:L6};var D7={...R2};D7.column.to=L6;import Wz from"net";import SO from"tls";import N6 from"crypto";import M7 from"stream";import{performance as $z}from"perf_hooks";class B2 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 $W=NO;function NO(W=[]){let $=W.slice(),Y=0;return{get length(){return $.length-Y},remove:(X)=>{let G=$.indexOf(X);return G===-1?null:($.splice(G,1),X)},push:(X)=>($.push(X),X),shift:()=>{let X=$[Y++];if(Y===$.length)Y=0,$=[];else $[Y-1]=void 0;return X}}}var N1=Buffer.allocUnsafe(256),RO="BCcDdEFfHPpQSX".split("").reduce((W,$)=>{let Y=$.charCodeAt(0);return W[$]=()=>{return N1[0]=Y,S0.i=5,S0},W},{}),S0=Object.assign(BO,RO,{N:String.fromCharCode(0),i:0,inc(W){return S0.i+=W,S0},str(W){let $=Buffer.byteLength(W);return xX($),S0.i+=N1.write(W,S0.i,$,"utf8"),S0},i16(W){return xX(2),N1.writeUInt16BE(W,S0.i),S0.i+=2,S0},i32(W,$){if($||$===0)return N1.writeUInt32BE(W,$),S0;return xX(4),N1.writeUInt32BE(W,S0.i),S0.i+=4,S0},z(W){return xX(W),N1.fill(0,S0.i,S0.i+W),S0.i+=W,S0},raw(W){return N1=Buffer.concat([N1.subarray(0,S0.i),W]),S0.i=N1.length,S0},end(W=1){N1.writeUInt32BE(S0.i-W,W);let $=N1.subarray(0,S0.i);return S0.i=0,N1=Buffer.allocUnsafe(256),$}}),n=S0;function xX(W){if(N1.length-S0.i<W){let $=N1,Y=$.length;N1=Buffer.allocUnsafe(Y+(Y>>1)+W),$.copy(N1)}}function BO(){return S0.i=0,S0}var K7=Gz,qO=1,g$=n().S().end(),Yz=n().H().end(),CO=n().i32(8).i32(80877103).end(8),kO=Buffer.concat([n().E().str(n.N).i32(0).end(),g$]),jO=n().D().str("S").str(n.N).end(),L8=()=>{},IO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),PO={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 Gz(W,$={},{onopen:Y=L8,onend:X=L8,onclose:G=L8}={}){let{ssl:J,max:H,user:T,host:Q,port:_,database:z,parsers:F,transform:w,onnotice:O,onnotify:V,onparameter:E,max_pipeline:I,keep_alive:j,backoff:N,target_session_attrs:B}=W,P=$W(),g=qO++,x={pid:null,secret:null},p=O7(R9,W.idle_timeout),w0=O7(R9,W.max_lifetime),p0=O7(cU,W.connect_timeout),Z=null,M0,Y0=new B2,U0=Buffer.alloc(0),e0=W.fetch_types,V1={},MW={},b2=Math.random().toString(36).slice(2),k=1,e=0,R0=0,m0=0,W1=0,z0=0,j0=0,r0=0,u0=null,v0=null,O1=!1,I0=null,VW=null,K1=null,K$=null,$1=null,y0=null,OW=null,IW=null,y=null,d8=null,E1={queue:$.closed,idleTimer:p,connect(U){K1=U||!0,_J()},terminate:o8,execute:l8,cancel:gU,end:R9,count:0,id:g};return $.closed&&$.closed.push(E1),E1;async function hU(){let U;try{U=W.socket?await Promise.resolve(W.socket(W)):new Wz.Socket}catch(K){v2(K);return}return U.on("error",v2),U.on("close",zJ),U.on("drain",TJ),U}async function gU({pid:U,secret:K},t,L0){try{M0=n().i32(16).i32(80877102).i32(U).i32(K).end(16),await QJ(),Z.once("error",L0),Z.once("close",t)}catch(l0){L0(l0)}}function l8(U){if(O1)return JY(U,a0.connection("CONNECTION_DESTROYED",W));if(U.cancelled)return;try{return U.state=x,y?P.push(U):(y=U,y.active=!0),uU(U),U1(mU(U))&&!U.describeFirst&&!U.cursorFn&&P.length<I&&(!U.options.onexecute||U.options.onexecute(E1))}catch(K){return P.length===0&&U1(g$),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([GJ(U),Yz]):U.prepare?U.prepared?GY(U):Buffer.concat([GJ(U),GY(U)]):pU(U)}function GJ(U){return Buffer.concat([wJ(U.statement.string,U.parameters,U.statement.types,U.statement.name),qD("S",U.statement.name)])}function GY(U){return Buffer.concat([SD(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?UJ("",U.cursorRows):kO])}function pU(U){return Buffer.concat([wJ(U.statement.string,U.parameters,U.statement.types),jO,GY(U)])}function uU(U){let K=[],t=[],L0=Q7(U,U.strings[0],U.args[0],K,t,W);!U.tagged&&U.args.forEach((l0)=>fX(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 MW[U.signature],U.parameters=U.parameters||K,U.prepared=U.prepare&&U.signature in MW,U.describeFirst=U.onlyDescribe||K.length&&!U.prepared,U.statement=U.prepared?MW[U.signature]:{string:L0,types:t,name:U.prepare?b2+k++:""},typeof W.debug==="function"&&W.debug(g,L0,K,t)}function U1(U,K){if(y0=y0?Buffer.concat([y0,U]):Buffer.from(U),K||y0.length>=1024)return JJ(K);return v0===null&&(v0=setImmediate(JJ)),!0}function JJ(U){let K=Z.write(y0,U);return v0!==null&&clearImmediate(v0),y0=v0=null,K}function cU(){PW(a0.connection("CONNECT_TIMEOUT",W,Z)),Z.destroy()}async function HJ(){if(U1(CO),!await new Promise((K)=>Z.once("data",(t)=>K(t[0]===83)))&&J==="prefer")return x2();Z.removeAllListeners(),Z=SO.connect({socket:Z,servername:Wz.isIP(Z.host)?void 0:Z.host,...J==="require"||J==="allow"||J==="prefer"?{rejectUnauthorized:!1}:J==="verify-full"?{}:typeof J==="object"?J:{}}),Z.on("secureConnect",x2),Z.on("error",v2),Z.on("close",zJ),Z.on("drain",TJ)}function TJ(){!y&&Y(E1)}function N9(U){if(I0){if(I0.push(U),R0-=U.length,R0>=0)return}U0=I0?Buffer.concat(I0,z0-R0):U0.length===0?U:Buffer.concat([U0,U],U0.length+U.length);while(U0.length>4){if(z0=U0.readUInt32BE(1),z0>=U0.length){R0=z0-U0.length,I0=[U0];break}try{dU(U0.subarray(0,z0+1))}catch(K){y&&(y.cursorFn||y.describeFirst)&&U1(g$),PW(K)}U0=U0.subarray(z0+1),R0=0,I0=null}}async function QJ(){if(O1=!1,V1={},Z||(Z=await hU()),!Z)return;if(p0.start(),W.socket)return J?HJ():x2();if(Z.on("connect",J?HJ:x2),W.path)return Z.connect(W.path);Z.ssl=J,Z.connect(_[m0],Q[m0]),Z.host=Q[m0],Z.port=_[m0],m0=(m0+1)%_.length}function _J(){setTimeout(QJ,e?e+j0-$z.now():0)}function x2(){try{MW={},e0=W.fetch_types,b2=Math.random().toString(36).slice(2),k=1,w0.start(),Z.on("data",N9),j&&Z.setKeepAlive&&Z.setKeepAlive(!0,1000*j);let U=kD();U1(U)}catch(U){v2(U)}}function v2(U){if(E1.queue===$.connecting&&W.host[W1+1])return;PW(U);while(P.length)JY(P.shift(),U)}function PW(U){$1&&($1.destroy(U),$1=null),y&&JY(y,U),K1&&(JY(K1,U),K1=null)}function JY(U,K){"query"in K||"parameters"in K||Object.defineProperties(K,{stack:{value:K.stack+U.origin.replace(/.*\n/,`
|
|
57
|
-
`),enumerable
|
|
79
|
+
`);super({baseURL:U.baseURL,timeout:U.timeout??600000,httpAgent:U.httpAgent,maxRetries:U.maxRetries,fetch:U.fetch});this.completions=new _T(this),this.chat=new k1(this),this.embeddings=new FT(this),this.files=new K0(this),this.images=new ET(this),this.audio=new s6(this),this.moderations=new AT(this),this.models=new A0(this),this.fineTuning=new G6(this),this.graders=new M0(this),this.vectorStores=new J6(this),this.beta=new f6(this),this.batches=new z0(this),this.uploads=new L0(this),this.responses=new N0(this),this.evals=new X1(this),this.containers=new W1(this),this._options=U,this.apiKey=T,this.organization=W,this.project=X}defaultQuery(){return this._options.defaultQuery}defaultHeaders($){return{...super.defaultHeaders($),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders($){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery($){return Rz($,{arrayFormat:"brackets"})}}SQ=X$;X$.OpenAI=SQ;X$.DEFAULT_TIMEOUT=600000;X$.OpenAIError=l;X$.APIError=t$;X$.APIConnectionError=Y0;X$.APIConnectionTimeoutError=U0;X$.APIUserAbortError=Y4;X$.NotFoundError=tY;X$.ConflictError=aY;X$.RateLimitError=eY;X$.BadRequestError=rY;X$.AuthenticationError=iY;X$.InternalServerError=$8;X$.PermissionDeniedError=nY;X$.UnprocessableEntityError=sY;X$.toFile=gz;X$.fileFromPath=lY;X$.Completions=_T;X$.Chat=k1;X$.ChatCompletionsPage=w0;X$.Embeddings=FT;X$.Files=K0;X$.FileObjectsPage=DT;X$.Images=ET;X$.Audio=s6;X$.Moderations=AT;X$.Models=A0;X$.ModelsPage=MT;X$.FineTuning=G6;X$.Graders=M0;X$.VectorStores=J6;X$.VectorStoresPage=ST;X$.VectorStoreSearchResponsesPage=BT;X$.Beta=f6;X$.Batches=z0;X$.BatchesPage=TT;X$.Uploads=L0;X$.Responses=N0;X$.Evals=X1;X$.EvalListResponsesPage=ZT;X$.Containers=W1;X$.ContainerListResponsesPage=HT;var BQ=X$;function dI($,...T){let[W,X,Y,U]=T,G=[{role:"user",content:HF(X)},{role:"user",content:W}],J=U.at(-1);if(J)G.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(J.response,null,2),"Here's the error message:",JSON.stringify(J.error.issues,null,2)].join(`
|
|
80
|
+
`)});return{model:$,messages:G}}var a=1e6,RQ={"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 oI($){let W=Object.keys(RQ).filter((X)=>$.startsWith(X)).sort((X,Y)=>Y.length-X.length)[0];if(!W)return;return RQ[W]}function lI($){return async function T(W,X){if(!$)throw new Error("This is a bug in safegen. OpenAI client not available to the json generator.");let Y=await $.chat.completions.create({...W,stream:!1,response_format:{type:"json_object"}},X),U=Y.choices[0].message?.content,{usage:G}=Y;if(U&&G){let J=G.prompt_tokens,z=G.prompt_tokens_details?.cached_tokens??0,w=J-z,H=G.completion_tokens,_=oI(W.model),F=0;if(_)F=J*_.promptPricePerToken+w*(_.promptPricePerTokenCached??0)+H*_.completionPricePerToken;else console.warn(`No pricing facts found for model ${W.model}. Giving a price of 0.`);return{data:JSON.parse(U),usage:G,usdPrice:F}}if(!U&&!G)throw new Error("No content or usage found in completion");if(!U)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var IQ=new Map,kQ=class{usdBudget;usdMinimum;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;client;lastUsage;constructor({model:$,usdBudget:T,usdMinimum:W,apiKey:X,cachingMode:Y,cacheKey:U="openai-safegen",logger:G}){this.usdBudget=T,this.usdMinimum=W,this.squirrel=new RF(Y);let J=IQ.get(X);if(Y!=="read"){if(!J)J=new BQ({apiKey:X,dangerouslyAllowBrowser:!1}),IQ.set(X,J);this.client=J}this.getUnknownJsonFromOpenAi=lI(this.client),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(U,this.getUnknownJsonFromOpenAi),this.from=_F(async(...z)=>{if(this.usdBudget<this.usdMinimum)return G?.warn("SafeGen budget exhausted"),z[2];let w=dI($,...z),H=z[0],_=z[3],{data:F,usage:D,usdPrice:V}=await this.getUnknownJsonFromOpenAiSquirreled.for(`${H.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${_.length}`).get(w);return this.lastUsage=D,this.usdBudget-=V,F},G)}from};import{exec as $j}from"child_process";class B8{supported;constructor($){this.supported=$}refine($){for(let[T,W]of Object.entries(this.supported))try{if(W($)===!0&&W!==Boolean)return{type:T,data:$}}catch(X){try{if($ instanceof W)return{type:T,data:$}}catch(Y){}}return null}}var rI=new B8({number:($)=>typeof $==="number",string:($)=>typeof $==="string",boolean:($)=>typeof $==="boolean",null:($)=>$===null});function iI($){if(!$)return!1;return Object.getPrototypeOf($)===Object.prototype}var nI=new B8({object:iI,array:($)=>Array.isArray($)}),tI=new B8({...rI.supported,...nI.supported}),qQ=($)=>{if($===void 0)return"undefined";let T=tI.refine($);if(T)return T.type;return Object.getPrototypeOf($).constructor.name};var Z=Symbol.for("drizzle:entityKind"),Wd=Symbol.for("drizzle:hasOwnEntityKind");function S($,T){if(!$||typeof $!=="object")return!1;if($ instanceof T)return!0;if(!Object.prototype.hasOwnProperty.call(T,Z))throw new Error(`Class "${T.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 W=Object.getPrototypeOf($).constructor;if(W)while(W){if(Z in W&&W[Z]===T[Z])return!0;W=Object.getPrototypeOf(W)}return!1}class B${constructor($,T){this.table=$,this.config=T,this.name=T.name,this.keyAsName=T.keyAsName,this.notNull=T.notNull,this.default=T.default,this.defaultFn=T.defaultFn,this.onUpdateFn=T.onUpdateFn,this.hasDefault=T.hasDefault,this.primary=T.primaryKey,this.isUnique=T.isUnique,this.uniqueName=T.uniqueName,this.uniqueType=T.uniqueType,this.dataType=T.dataType,this.columnType=T.columnType,this.generated=T.generated,this.generatedIdentity=T.generatedIdentity}static[Z]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class z7{static[Z]="ColumnBuilder";config;constructor($,T,W){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:T,columnType:W,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}var A6=Symbol.for("drizzle:Name");class _7{static[Z]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor($,T){if(this.reference=()=>{let{name:W,columns:X,foreignColumns:Y}=$();return{name:W,columns:X,foreignTable:Y[0].table,foreignColumns:Y}},T)this._onUpdate=T.onUpdate,this._onDelete=T.onDelete}onUpdate($){return this._onUpdate=$===void 0?"no action":$,this}onDelete($){return this._onDelete=$===void 0?"no action":$,this}build($){return new PQ($,this)}}class PQ{constructor($,T){this.table=$,this.reference=T.reference,this.onUpdate=T._onUpdate,this.onDelete=T._onDelete}static[Z]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:T,foreignColumns:W}=this.reference(),X=T.map((G)=>G.name),Y=W.map((G)=>G.name),U=[this.table[A6],...X,W[0].table[A6],...Y];return $??`${U.join("_")}_fk`}}function R8($,...T){return $(...T)}function CQ($,T){return`${$[A6]}_${T.join("_")}_unique`}function vQ($,T,W){for(let X=T;X<$.length;X++){let Y=$[X];if(Y==="\\"){X++;continue}if(Y==='"')return[$.slice(T,X).replace(/\\/g,""),X+1];if(W)continue;if(Y===","||Y==="}")return[$.slice(T,X).replace(/\\/g,""),X]}return[$.slice(T).replace(/\\/g,""),$.length]}function jQ($,T=0){let W=[],X=T,Y=!1;while(X<$.length){let U=$[X];if(U===","){if(Y||X===T)W.push("");Y=!0,X++;continue}if(Y=!1,U==="\\"){X+=2;continue}if(U==='"'){let[z,w]=vQ($,X+1,!0);W.push(z),X=w;continue}if(U==="}")return[W,X+1];if(U==="{"){let[z,w]=jQ($,X+1);W.push(z),X=w;continue}let[G,J]=vQ($,X,!1);W.push(G),X=J}return[W,X]}function xQ($){let[T]=jQ($,1);return T}function H7($){return`{${$.map((T)=>{if(Array.isArray(T))return H7(T);if(typeof T==="string")return`"${T.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${T}`}).join(",")}}`}class d extends z7{foreignKeyConfigs=[];static[Z]="PgColumnBuilder";array($){return new fQ(this.config.name,this,$)}references($,T={}){return this.foreignKeyConfigs.push({ref:$,actions:T}),this}unique($,T){return this.config.isUnique=!0,this.config.uniqueName=$,this.config.uniqueType=T?.nulls,this}generatedAlwaysAs($){return this.config.generated={as:$,type:"always",mode:"stored"},this}buildForeignKeys($,T){return this.foreignKeyConfigs.map(({ref:W,actions:X})=>{return R8((Y,U)=>{let G=new _7(()=>{let J=Y();return{columns:[$],foreignColumns:[J]}});if(U.onUpdate)G.onUpdate(U.onUpdate);if(U.onDelete)G.onDelete(U.onDelete);return G.build(T)},W,X)})}buildExtraConfigColumn($){return new bQ($,this.config)}}class b extends B${constructor($,T){if(!T.uniqueName)T.uniqueName=CQ($,[T.name]);super($,T);this.table=$}static[Z]="PgColumn"}class bQ extends b{static[Z]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}class f2{static[Z]="IndexedColumn";constructor($,T,W,X){this.name=$,this.keyAsName=T,this.type=W,this.indexConfig=X}name;keyAsName;type;indexConfig}class fQ extends d{static[Z]="PgArrayBuilder";constructor($,T,W){super($,"array","PgArray");this.config.baseBuilder=T,this.config.size=W}build($){let T=this.config.baseBuilder.build($);return new F7($,this.config,T)}}class F7 extends b{constructor($,T,W,X){super($,T);this.baseColumn=W,this.range=X,this.size=T.size}size;static[Z]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue($){if(typeof $==="string")$=xQ($);return $.map((T)=>this.baseColumn.mapFromDriverValue(T))}mapToDriverValue($,T=!1){let W=$.map((X)=>X===null?null:S(this.baseColumn,F7)?this.baseColumn.mapToDriverValue(X,!0):this.baseColumn.mapToDriverValue(X));if(T)return W;return H7(W)}}class yQ extends d{static[Z]="PgEnumObjectColumnBuilder";constructor($,T){super($,"string","PgEnumObjectColumn");this.config.enum=T}build($){return new hQ($,this.config)}}class hQ extends b{static[Z]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,T){super($,T);this.enum=T.enum}getSQLType(){return this.enum.enumName}}var I8=Symbol.for("drizzle:isPgEnum");function gQ($){return!!$&&typeof $==="function"&&I8 in $&&$[I8]===!0}class mQ extends d{static[Z]="PgEnumColumnBuilder";constructor($,T){super($,"string","PgEnumColumn");this.config.enum=T}build($){return new cQ($,this.config)}}class cQ extends b{static[Z]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,T){super($,T);this.enum=T.enum}getSQLType(){return this.enum.enumName}}function y2($,T){return Array.isArray(T)?aI($,[...T],void 0):sI($,T,void 0)}function aI($,T,W){let X=Object.assign((Y)=>new mQ(Y??"",X),{enumName:$,enumValues:T,schema:W,[I8]:!0});return X}function sI($,T,W){let X=Object.assign((Y)=>new yQ(Y??"",X),{enumName:$,enumValues:Object.values(T),schema:W,[I8]:!0});return X}class G4{static[Z]="Subquery";constructor($,T,W,X=!1){this._={brand:"Subquery",sql:$,selectedFields:T,alias:W,isWith:X}}}class h2 extends G4{static[Z]="WithSubquery"}var uQ="0.43.1";var Q7,Z7,R$={startActiveSpan($,T){if(!Q7)return T();if(!Z7)Z7=Q7.trace.getTracer("drizzle-orm",uQ);return R8((W,X)=>X.startActiveSpan($,(Y)=>{try{return T(Y)}catch(U){throw Y.setStatus({code:W.SpanStatusCode.ERROR,message:U instanceof Error?U.message:"Unknown error"}),U}finally{Y.end()}}),Q7,Z7)}};var C$=Symbol.for("drizzle:ViewBaseConfig");var k8=Symbol.for("drizzle:Schema"),q8=Symbol.for("drizzle:Columns"),pQ=Symbol.for("drizzle:ExtraConfigColumns"),D7=Symbol.for("drizzle:OriginalName"),O7=Symbol.for("drizzle:BaseName"),g2=Symbol.for("drizzle:IsAlias"),dQ=Symbol.for("drizzle:ExtraConfigBuilder"),eI=Symbol.for("drizzle:IsDrizzleTable");class c{static[Z]="Table";static Symbol={Name:A6,Schema:k8,OriginalName:D7,Columns:q8,ExtraConfigColumns:pQ,BaseName:O7,IsAlias:g2,ExtraConfigBuilder:dQ};[A6];[D7];[k8];[q8];[pQ];[O7];[g2]=!1;[eI]=!0;[dQ]=void 0;constructor($,T,W){this[A6]=this[D7]=$,this[k8]=T,this[O7]=W}}function F4($){return $[A6]}function R0($){return`${$[k8]??"public"}.${$[A6]}`}function V7($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function $k($){let T={sql:"",params:[]};for(let W of $)if(T.sql+=W.sql,T.params.push(...W.params),W.typings?.length){if(!T.typings)T.typings=[];T.typings.push(...W.typings)}return T}class J4{static[Z]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new p([this])}}class p{constructor($){this.queryChunks=$}static[Z]="SQL";decoder=lQ;shouldInlineParams=!1;append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return R$.startActiveSpan("drizzle.buildSQL",(T)=>{let W=this.buildQueryFromSourceParams(this.queryChunks,$);return T?.setAttributes({"drizzle.query.text":W.sql,"drizzle.query.params":JSON.stringify(W.params)}),W})}buildQueryFromSourceParams($,T){let W=Object.assign({},T,{inlineParams:T.inlineParams||this.shouldInlineParams,paramStartIndex:T.paramStartIndex||{value:0}}),{casing:X,escapeName:Y,escapeParam:U,prepareTyping:G,inlineParams:J,paramStartIndex:z}=W;return $k($.map((w)=>{if(S(w,J4))return{sql:w.value.join(""),params:[]};if(S(w,P8))return{sql:Y(w.value),params:[]};if(w===void 0)return{sql:"",params:[]};if(Array.isArray(w)){let H=[new J4("(")];for(let[_,F]of w.entries())if(H.push(F),_<w.length-1)H.push(new J4(", "));return H.push(new J4(")")),this.buildQueryFromSourceParams(H,W)}if(S(w,p))return this.buildQueryFromSourceParams(w.queryChunks,{...W,inlineParams:J||w.shouldInlineParams});if(S(w,c)){let H=w[c.Symbol.Schema],_=w[c.Symbol.Name];return{sql:H===void 0||w[g2]?Y(_):Y(H)+"."+Y(_),params:[]}}if(S(w,B$)){let H=X.getColumnCasing(w);if(T.invokeSource==="indexes")return{sql:Y(H),params:[]};let _=w.table[c.Symbol.Schema];return{sql:w.table[g2]||_===void 0?Y(w.table[c.Symbol.Name])+"."+Y(H):Y(_)+"."+Y(w.table[c.Symbol.Name])+"."+Y(H),params:[]}}if(S(w,g4)){let H=w[C$].schema,_=w[C$].name;return{sql:H===void 0||w[C$].isAlias?Y(_):Y(H)+"."+Y(_),params:[]}}if(S(w,T6)){if(S(w.value,b1))return{sql:U(z.value++,w),params:[w],typings:["none"]};let H=w.value===null?null:w.encoder.mapToDriverValue(w.value);if(S(H,p))return this.buildQueryFromSourceParams([H],W);if(J)return{sql:this.mapInlineParam(H,W),params:[]};let _=["none"];if(G)_=[G(w.encoder)];return{sql:U(z.value++,H),params:[H],typings:_}}if(S(w,b1))return{sql:U(z.value++,w),params:[w],typings:["none"]};if(S(w,p.Aliased)&&w.fieldAlias!==void 0)return{sql:Y(w.fieldAlias),params:[]};if(S(w,G4)){if(w._.isWith)return{sql:Y(w._.alias),params:[]};return this.buildQueryFromSourceParams([new J4("("),w._.sql,new J4(") "),new P8(w._.alias)],W)}if(gQ(w)){if(w.schema)return{sql:Y(w.schema)+"."+Y(w.enumName),params:[]};return{sql:Y(w.enumName),params:[]}}if(V7(w)){if(w.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([w.getSQL()],W);return this.buildQueryFromSourceParams([new J4("("),w.getSQL(),new J4(")")],W)}if(J)return{sql:this.mapInlineParam(w,W),params:[]};return{sql:U(z.value++,w),params:[w],typings:["none"]}}))}mapInlineParam($,{escapeString:T}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return T($);if(typeof $==="object"){let W=$.toString();if(W==="[object Object]")return T(JSON.stringify($));return T(W)}throw new Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new p.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class P8{constructor($){this.value=$}static[Z]="Name";brand;getSQL(){return new p([this])}}function oQ($){return typeof $==="object"&&$!==null&&"mapToDriverValue"in $&&typeof $.mapToDriverValue==="function"}var lQ={mapFromDriverValue:($)=>$},rQ={mapToDriverValue:($)=>$},dd={...lQ,...rQ};class T6{constructor($,T=rQ){this.value=$,this.encoder=T}static[Z]="Param";brand;getSQL(){return new p([this])}}function O($,...T){let W=[];if(T.length>0||$.length>0&&$[0]!=="")W.push(new J4($[0]));for(let[X,Y]of T.entries())W.push(Y,new J4($[X+1]));return new p(W)}(($)=>{function T(){return new p([])}$.empty=T;function W(z){return new p(z)}$.fromList=W;function X(z){return new p([new J4(z)])}$.raw=X;function Y(z,w){let H=[];for(let[_,F]of z.entries()){if(_>0&&w!==void 0)H.push(w);H.push(F)}return new p(H)}$.join=Y;function U(z){return new P8(z)}$.identifier=U;function G(z){return new b1(z)}$.placeholder=G;function J(z,w){return new T6(z,w)}$.param=J})(O||(O={}));(($)=>{class T{constructor(W,X){this.sql=W,this.fieldAlias=X}static[Z]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new T(this.sql,this.fieldAlias)}}$.Aliased=T})(p||(p={}));class b1{constructor($){this.name=$}static[Z]="Placeholder";getSQL(){return new p([this])}}function K7($,T){return $.map((W)=>{if(S(W,b1)){if(!(W.name in T))throw new Error(`No value for placeholder "${W.name}" was provided`);return T[W.name]}if(S(W,T6)&&S(W.value,b1)){if(!(W.value.name in T))throw new Error(`No value for placeholder "${W.value.name}" was provided`);return W.encoder.mapToDriverValue(T[W.value.name])}return W})}var Tk=Symbol.for("drizzle:IsDrizzleView");class g4{static[Z]="View";[C$];[Tk]=!0;constructor({name:$,schema:T,selectedFields:W,query:X}){this[C$]={name:$,originalName:$,schema:T,selectedFields:W,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new p([this])}}B$.prototype.getSQL=function(){return new p([this])};c.prototype.getSQL=function(){return new p([this])};G4.prototype.getSQL=function(){return new p([this])};class RT{constructor($){this.table=$}static[Z]="ColumnAliasProxyHandler";get($,T){if(T==="table")return this.table;return $[T]}}class m2{constructor($,T){this.alias=$,this.replaceOriginalName=T}static[Z]="TableAliasProxyHandler";get($,T){if(T===c.Symbol.IsAlias)return!0;if(T===c.Symbol.Name)return this.alias;if(this.replaceOriginalName&&T===c.Symbol.OriginalName)return this.alias;if(T===C$)return{...$[C$],name:this.alias,isAlias:!0};if(T===c.Symbol.Columns){let X=$[c.Symbol.Columns];if(!X)return X;let Y={};return Object.keys(X).map((U)=>{Y[U]=new Proxy(X[U],new RT(new Proxy($,this)))}),Y}let W=$[T];if(S(W,B$))return new Proxy(W,new RT(new Proxy($,this)));return W}}function C8($,T){return new Proxy($,new m2(T,!1))}function y6($,T){return new Proxy($,new RT(new Proxy($.table,new m2(T,!1))))}function E7($,T){return new p.Aliased(c2($.sql,T),$.fieldAlias)}function c2($,T){return O.join($.queryChunks.map((W)=>{if(S(W,B$))return y6(W,T);if(S(W,p))return c2(W,T);if(S(W,p.Aliased))return E7(W,T);return W}))}class v8 extends Error{static[Z]="DrizzleError";constructor({message:$,cause:T}){super($);this.name="DrizzleError",this.cause=T}}class M7 extends v8{static[Z]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class iQ{static[Z]="ConsoleLogWriter";write($){console.log($)}}class A7{static[Z]="DefaultLogger";writer;constructor($){this.writer=$?.writer??new iQ}logQuery($,T){let W=T.map((Y)=>{try{return JSON.stringify(Y)}catch{return String(Y)}}),X=W.length?` -- params: [${W.join(", ")}]`:"";this.writer.write(`Query: ${$}${X}`)}}class N7{static[Z]="NoopLogger";logQuery(){}}class k4{static[Z]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch($){return this.then(void 0,$)}finally($){return this.then((T)=>{return $?.(),T},(T)=>{throw $?.(),T})}then($,T){return this.execute().then($,T)}}function nQ($,T,W){let X={},Y=$.reduce((U,{path:G,field:J},z)=>{let w;if(S(J,B$))w=J;else if(S(J,p))w=J.decoder;else w=J.sql.decoder;let H=U;for(let[_,F]of G.entries())if(_<G.length-1){if(!(F in H))H[F]={};H=H[F]}else{let D=T[z],V=H[F]=D===null?null:w.mapFromDriverValue(D);if(W&&S(J,B$)&&G.length===2){let E=G[0];if(!(E in X))X[E]=V===null?F4(J.table):!1;else if(typeof X[E]==="string"&&X[E]!==F4(J.table))X[E]=!1}}return U},{});if(W&&Object.keys(X).length>0){for(let[U,G]of Object.entries(X))if(typeof G==="string"&&!W[G])Y[U]=null}return Y}function w6($,T){return Object.entries($).reduce((W,[X,Y])=>{if(typeof X!=="string")return W;let U=T?[...T,X]:[X];if(S(Y,B$)||S(Y,p)||S(Y,p.Aliased))W.push({path:U,field:Y});else if(S(Y,c))W.push(...w6(Y[c.Symbol.Columns],U));else W.push(...w6(Y,U));return W},[])}function u2($,T){let W=Object.keys($),X=Object.keys(T);if(W.length!==X.length)return!1;for(let[Y,U]of W.entries())if(U!==X[Y])return!1;return!0}function j8($,T){let W=Object.entries(T).filter(([,X])=>X!==void 0).map(([X,Y])=>{if(S(Y,p)||S(Y,B$))return[X,Y];else return[X,new T6(Y,$[c.Symbol.Columns][X])]});if(W.length===0)throw new Error("No values to set");return Object.fromEntries(W)}function tQ($,T){for(let W of T)for(let X of Object.getOwnPropertyNames(W.prototype)){if(X==="constructor")continue;Object.defineProperty($.prototype,X,Object.getOwnPropertyDescriptor(W.prototype,X)||Object.create(null))}}function aQ($){return $[c.Symbol.Columns]}function U1($){return S($,G4)?$._.alias:S($,g4)?$[C$].name:S($,p)?void 0:$[c.Symbol.IsAlias]?$[c.Symbol.Name]:$[c.Symbol.BaseName]}function D$($,T){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:T}}function sQ($){if(typeof $!=="object"||$===null)return!1;if($.constructor.name!=="Object")return!1;if("logger"in $){let T=typeof $.logger;if(T!=="boolean"&&(T!=="object"||typeof $.logger.logQuery!=="function")&&T!=="undefined")return!1;return!0}if("schema"in $){let T=typeof $.schema;if(T!=="object"&&T!=="undefined")return!1;return!0}if("casing"in $){let T=typeof $.casing;if(T!=="string"&&T!=="undefined")return!1;return!0}if("mode"in $){if($.mode!=="default"||$.mode!=="planetscale"||$.mode!==void 0)return!1;return!0}if("connection"in $){let T=typeof $.connection;if(T!=="string"&&T!=="object"&&T!=="undefined")return!1;return!0}if("client"in $){let T=typeof $.client;if(T!=="object"&&T!=="function"&&T!=="undefined")return!1;return!0}if(Object.keys($).length===0)return!0;return!1}class f1 extends d{static[Z]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity($){if($){let{name:T,...W}=$;this.config.generatedIdentity={type:"always",sequenceName:T,sequenceOptions:W}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity($){if($){let{name:T,...W}=$;this.config.generatedIdentity={type:"byDefault",sequenceName:T,sequenceOptions:W}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class eQ extends f1{static[Z]="PgBigInt53Builder";constructor($){super($,"number","PgBigInt53")}build($){return new $Z($,this.config)}}class $Z extends b{static[Z]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}}class TZ extends f1{static[Z]="PgBigInt64Builder";constructor($){super($,"bigint","PgBigInt64")}build($){return new WZ($,this.config)}}class WZ extends b{static[Z]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue($){return BigInt($)}}function XZ($,T){let{name:W,config:X}=D$($,T);if(X.mode==="number")return new eQ(W);return new TZ(W)}class YZ extends d{static[Z]="PgBigSerial53Builder";constructor($){super($,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build($){return new UZ($,this.config)}}class UZ extends b{static[Z]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}}class GZ extends d{static[Z]="PgBigSerial64Builder";constructor($){super($,"bigint","PgBigSerial64");this.config.hasDefault=!0}build($){return new JZ($,this.config)}}class JZ extends b{static[Z]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue($){return BigInt($)}}function wZ($,T){let{name:W,config:X}=D$($,T);if(X.mode==="number")return new YZ(W);return new GZ(W)}class zZ extends d{static[Z]="PgBooleanBuilder";constructor($){super($,"boolean","PgBoolean")}build($){return new _Z($,this.config)}}class _Z extends b{static[Z]="PgBoolean";getSQLType(){return"boolean"}}function p2($){return new zZ($??"")}class HZ extends d{static[Z]="PgCharBuilder";constructor($,T){super($,"string","PgChar");this.config.length=T.length,this.config.enumValues=T.enum}build($){return new FZ($,this.config)}}class FZ extends b{static[Z]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function QZ($,T={}){let{name:W,config:X}=D$($,T);return new HZ(W,X)}class ZZ extends d{static[Z]="PgCidrBuilder";constructor($){super($,"string","PgCidr")}build($){return new DZ($,this.config)}}class DZ extends b{static[Z]="PgCidr";getSQLType(){return"cidr"}}function OZ($){return new ZZ($??"")}class VZ extends d{static[Z]="PgCustomColumnBuilder";constructor($,T,W){super($,"custom","PgCustomColumn");this.config.fieldConfig=T,this.config.customTypeParams=W}build($){return new KZ($,this.config)}}class KZ extends b{static[Z]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor($,T){super($,T);this.sqlName=T.customTypeParams.dataType(T.fieldConfig),this.mapTo=T.customTypeParams.toDriver,this.mapFrom=T.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function EZ($){return(T,W)=>{let{name:X,config:Y}=D$(T,W);return new VZ(X,Y,$)}}class G1 extends d{static[Z]="PgDateColumnBaseBuilder";defaultNow(){return this.default(O`now()`)}}class MZ extends G1{static[Z]="PgDateBuilder";constructor($){super($,"date","PgDate")}build($){return new x8($,this.config)}}class x8 extends b{static[Z]="PgDate";getSQLType(){return"date"}mapFromDriverValue($){return new Date($)}mapToDriverValue($){return $.toISOString()}}class AZ extends G1{static[Z]="PgDateStringBuilder";constructor($){super($,"string","PgDateString")}build($){return new b8($,this.config)}}class b8 extends b{static[Z]="PgDateString";getSQLType(){return"date"}}function NZ($,T){let{name:W,config:X}=D$($,T);if(X?.mode==="date")return new MZ(W);return new AZ(W)}class LZ extends d{static[Z]="PgDoublePrecisionBuilder";constructor($){super($,"number","PgDoublePrecision")}build($){return new SZ($,this.config)}}class SZ extends b{static[Z]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue($){if(typeof $==="string")return Number.parseFloat($);return $}}function BZ($){return new LZ($??"")}class RZ extends d{static[Z]="PgInetBuilder";constructor($){super($,"string","PgInet")}build($){return new IZ($,this.config)}}class IZ extends b{static[Z]="PgInet";getSQLType(){return"inet"}}function kZ($){return new RZ($??"")}class qZ extends f1{static[Z]="PgIntegerBuilder";constructor($){super($,"number","PgInteger")}build($){return new PZ($,this.config)}}class PZ extends b{static[Z]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue($){if(typeof $==="string")return Number.parseInt($);return $}}function d2($){return new qZ($??"")}class CZ extends d{static[Z]="PgIntervalBuilder";constructor($,T){super($,"string","PgInterval");this.config.intervalConfig=T}build($){return new vZ($,this.config)}}class vZ extends b{static[Z]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let $=this.fields?` ${this.fields}`:"",T=this.precision?`(${this.precision})`:"";return`interval${$}${T}`}}function jZ($,T={}){let{name:W,config:X}=D$($,T);return new CZ(W,X)}class xZ extends d{static[Z]="PgJsonBuilder";constructor($){super($,"json","PgJson")}build($){return new f8($,this.config)}}class f8 extends b{static[Z]="PgJson";constructor($,T){super($,T)}getSQLType(){return"json"}mapToDriverValue($){return JSON.stringify($)}mapFromDriverValue($){if(typeof $==="string")try{return JSON.parse($)}catch{return $}return $}}function bZ($){return new xZ($??"")}class fZ extends d{static[Z]="PgJsonbBuilder";constructor($){super($,"json","PgJsonb")}build($){return new y8($,this.config)}}class y8 extends b{static[Z]="PgJsonb";constructor($,T){super($,T)}getSQLType(){return"jsonb"}mapToDriverValue($){return JSON.stringify($)}mapFromDriverValue($){if(typeof $==="string")try{return JSON.parse($)}catch{return $}return $}}function yZ($){return new fZ($??"")}class hZ extends d{static[Z]="PgLineBuilder";constructor($){super($,"array","PgLine")}build($){return new gZ($,this.config)}}class gZ extends b{static[Z]="PgLine";getSQLType(){return"line"}mapFromDriverValue($){let[T,W,X]=$.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(W),Number.parseFloat(X)]}mapToDriverValue($){return`{${$[0]},${$[1]},${$[2]}}`}}class mZ extends d{static[Z]="PgLineABCBuilder";constructor($){super($,"json","PgLineABC")}build($){return new cZ($,this.config)}}class cZ extends b{static[Z]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue($){let[T,W,X]=$.slice(1,-1).split(",");return{a:Number.parseFloat(T),b:Number.parseFloat(W),c:Number.parseFloat(X)}}mapToDriverValue($){return`{${$.a},${$.b},${$.c}}`}}function uZ($,T){let{name:W,config:X}=D$($,T);if(!X?.mode||X.mode==="tuple")return new hZ(W);return new mZ(W)}class pZ extends d{static[Z]="PgMacaddrBuilder";constructor($){super($,"string","PgMacaddr")}build($){return new dZ($,this.config)}}class dZ extends b{static[Z]="PgMacaddr";getSQLType(){return"macaddr"}}function oZ($){return new pZ($??"")}class lZ extends d{static[Z]="PgMacaddr8Builder";constructor($){super($,"string","PgMacaddr8")}build($){return new rZ($,this.config)}}class rZ extends b{static[Z]="PgMacaddr8";getSQLType(){return"macaddr8"}}function iZ($){return new lZ($??"")}class nZ extends d{static[Z]="PgNumericBuilder";constructor($,T,W){super($,"string","PgNumeric");this.config.precision=T,this.config.scale=W}build($){return new h8($,this.config)}}class h8 extends b{static[Z]="PgNumeric";precision;scale;constructor($,T){super($,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue($){if(typeof $==="string")return $;return 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 tZ extends d{static[Z]="PgNumericNumberBuilder";constructor($,T,W){super($,"number","PgNumericNumber");this.config.precision=T,this.config.scale=W}build($){return new aZ($,this.config)}}class aZ extends b{static[Z]="PgNumericNumber";precision;scale;constructor($,T){super($,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}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 sZ extends d{static[Z]="PgNumericBigIntBuilder";constructor($,T,W){super($,"bigint","PgNumericBigInt");this.config.precision=T,this.config.scale=W}build($){return new eZ($,this.config)}}class eZ extends b{static[Z]="PgNumericBigInt";precision;scale;constructor($,T){super($,T);this.precision=T.precision,this.scale=T.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 $D($,T){let{name:W,config:X}=D$($,T),Y=X?.mode;return Y==="number"?new tZ(W,X?.precision,X?.scale):Y==="bigint"?new sZ(W,X?.precision,X?.scale):new nZ(W,X?.precision,X?.scale)}class TD extends d{static[Z]="PgPointTupleBuilder";constructor($){super($,"array","PgPointTuple")}build($){return new WD($,this.config)}}class WD extends b{static[Z]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue($){if(typeof $==="string"){let[T,W]=$.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(W)]}return[$.x,$.y]}mapToDriverValue($){return`(${$[0]},${$[1]})`}}class XD extends d{static[Z]="PgPointObjectBuilder";constructor($){super($,"json","PgPointObject")}build($){return new YD($,this.config)}}class YD extends b{static[Z]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue($){if(typeof $==="string"){let[T,W]=$.slice(1,-1).split(",");return{x:Number.parseFloat(T),y:Number.parseFloat(W)}}return $}mapToDriverValue($){return`(${$.x},${$.y})`}}function UD($,T){let{name:W,config:X}=D$($,T);if(!X?.mode||X.mode==="tuple")return new TD(W);return new XD(W)}function Wk($){let T=[];for(let W=0;W<$.length;W+=2)T.push(Number.parseInt($.slice(W,W+2),16));return new Uint8Array(T)}function GD($,T){let W=new ArrayBuffer(8),X=new DataView(W);for(let Y=0;Y<8;Y++)X.setUint8(Y,$[T+Y]);return X.getFloat64(0,!0)}function L7($){let T=Wk($),W=0,X=T[W];W+=1;let Y=new DataView(T.buffer),U=Y.getUint32(W,X===1);W+=4;let G;if(U&536870912)G=Y.getUint32(W,X===1),W+=4;if((U&65535)===1){let J=GD(T,W);W+=8;let z=GD(T,W);return W+=8,[J,z]}throw new Error("Unsupported geometry type")}class JD extends d{static[Z]="PgGeometryBuilder";constructor($){super($,"array","PgGeometry")}build($){return new wD($,this.config)}}class wD extends b{static[Z]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue($){return L7($)}mapToDriverValue($){return`point(${$[0]} ${$[1]})`}}class zD extends d{static[Z]="PgGeometryObjectBuilder";constructor($){super($,"json","PgGeometryObject")}build($){return new _D($,this.config)}}class _D extends b{static[Z]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue($){let T=L7($);return{x:T[0],y:T[1]}}mapToDriverValue($){return`point(${$.x} ${$.y})`}}function HD($,T){let{name:W,config:X}=D$($,T);if(!X?.mode||X.mode==="tuple")return new JD(W);return new zD(W)}class FD extends d{static[Z]="PgRealBuilder";constructor($,T){super($,"number","PgReal");this.config.length=T}build($){return new QD($,this.config)}}class QD extends b{static[Z]="PgReal";constructor($,T){super($,T)}getSQLType(){return"real"}mapFromDriverValue=($)=>{if(typeof $==="string")return Number.parseFloat($);return $}}function ZD($){return new FD($??"")}class DD extends d{static[Z]="PgSerialBuilder";constructor($){super($,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build($){return new OD($,this.config)}}class OD extends b{static[Z]="PgSerial";getSQLType(){return"serial"}}function VD($){return new DD($??"")}class KD extends f1{static[Z]="PgSmallIntBuilder";constructor($){super($,"number","PgSmallInt")}build($){return new ED($,this.config)}}class ED extends b{static[Z]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=($)=>{if(typeof $==="string")return Number($);return $}}function MD($){return new KD($??"")}class AD extends d{static[Z]="PgSmallSerialBuilder";constructor($){super($,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build($){return new ND($,this.config)}}class ND extends b{static[Z]="PgSmallSerial";getSQLType(){return"smallserial"}}function LD($){return new AD($??"")}class SD extends d{static[Z]="PgTextBuilder";constructor($,T){super($,"string","PgText");this.config.enumValues=T.enum}build($){return new BD($,this.config)}}class BD extends b{static[Z]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function RD($,T={}){let{name:W,config:X}=D$($,T);return new SD(W,X)}class ID extends G1{constructor($,T,W){super($,"string","PgTime");this.withTimezone=T,this.precision=W,this.config.withTimezone=T,this.config.precision=W}static[Z]="PgTimeBuilder";build($){return new g8($,this.config)}}class g8 extends b{static[Z]="PgTime";withTimezone;precision;constructor($,T){super($,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function kD($,T={}){let{name:W,config:X}=D$($,T);return new ID(W,X.withTimezone??!1,X.precision)}class qD extends G1{static[Z]="PgTimestampBuilder";constructor($,T,W){super($,"date","PgTimestamp");this.config.withTimezone=T,this.config.precision=W}build($){return new m8($,this.config)}}class m8 extends b{static[Z]="PgTimestamp";withTimezone;precision;constructor($,T){super($,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=($)=>{return new Date(this.withTimezone?$:$+"+0000")};mapToDriverValue=($)=>{return $.toISOString()}}class PD extends G1{static[Z]="PgTimestampStringBuilder";constructor($,T,W){super($,"string","PgTimestampString");this.config.withTimezone=T,this.config.precision=W}build($){return new c8($,this.config)}}class c8 extends b{static[Z]="PgTimestampString";withTimezone;precision;constructor($,T){super($,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function N6($,T={}){let{name:W,config:X}=D$($,T);if(X?.mode==="string")return new PD(W,X.withTimezone??!1,X.precision);return new qD(W,X?.withTimezone??!1,X?.precision)}class CD extends d{static[Z]="PgUUIDBuilder";constructor($){super($,"string","PgUUID")}defaultRandom(){return this.default(O`gen_random_uuid()`)}build($){return new u8($,this.config)}}class u8 extends b{static[Z]="PgUUID";getSQLType(){return"uuid"}}function z6($){return new CD($??"")}class vD extends d{static[Z]="PgVarcharBuilder";constructor($,T){super($,"string","PgVarchar");this.config.length=T.length,this.config.enumValues=T.enum}build($){return new jD($,this.config)}}class jD extends b{static[Z]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function q4($,T={}){let{name:W,config:X}=D$($,T);return new vD(W,X)}class xD extends d{static[Z]="PgBinaryVectorBuilder";constructor($,T){super($,"string","PgBinaryVector");this.config.dimensions=T.dimensions}build($){return new bD($,this.config)}}class bD extends b{static[Z]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function fD($,T){let{name:W,config:X}=D$($,T);return new xD(W,X)}class yD extends d{static[Z]="PgHalfVectorBuilder";constructor($,T){super($,"array","PgHalfVector");this.config.dimensions=T.dimensions}build($){return new hD($,this.config)}}class hD extends b{static[Z]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue($){return JSON.stringify($)}mapFromDriverValue($){return $.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function gD($,T){let{name:W,config:X}=D$($,T);return new yD(W,X)}class mD extends d{static[Z]="PgSparseVectorBuilder";constructor($,T){super($,"string","PgSparseVector");this.config.dimensions=T.dimensions}build($){return new cD($,this.config)}}class cD extends b{static[Z]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function uD($,T){let{name:W,config:X}=D$($,T);return new mD(W,X)}class pD extends d{static[Z]="PgVectorBuilder";constructor($,T){super($,"array","PgVector");this.config.dimensions=T.dimensions}build($){return new dD($,this.config)}}class dD extends b{static[Z]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue($){return JSON.stringify($)}mapFromDriverValue($){return $.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function oD($,T){let{name:W,config:X}=D$($,T);return new pD(W,X)}function lD(){return{bigint:XZ,bigserial:wZ,boolean:p2,char:QZ,cidr:OZ,customType:EZ,date:NZ,doublePrecision:BZ,inet:kZ,integer:d2,interval:jZ,json:bZ,jsonb:yZ,line:uZ,macaddr:oZ,macaddr8:iZ,numeric:$D,point:UD,geometry:HD,real:ZD,serial:VD,smallint:MD,smallserial:LD,text:RD,time:kD,timestamp:N6,uuid:z6,varchar:q4,bit:fD,halfvec:gD,sparsevec:uD,vector:oD}}var S7=Symbol.for("drizzle:PgInlineForeignKeys"),rD=Symbol.for("drizzle:EnableRLS");class O4 extends c{static[Z]="PgTable";static Symbol=Object.assign({},c.Symbol,{InlineForeignKeys:S7,EnableRLS:rD});[S7]=[];[rD]=!1;[c.Symbol.ExtraConfigBuilder]=void 0;[c.Symbol.ExtraConfigColumns]={}}function Xk($,T,W,X,Y=$){let U=new O4($,X,Y),G=typeof T==="function"?T(lD()):T,J=Object.fromEntries(Object.entries(G).map(([H,_])=>{let F=_;F.setName(H);let D=F.build(U);return U[S7].push(...F.buildForeignKeys(D,U)),[H,D]})),z=Object.fromEntries(Object.entries(G).map(([H,_])=>{let F=_;F.setName(H);let D=F.buildExtraConfigColumn(U);return[H,D]})),w=Object.assign(U,J);if(w[c.Symbol.Columns]=J,w[c.Symbol.ExtraConfigColumns]=z,W)w[O4.Symbol.ExtraConfigBuilder]=W;return Object.assign(w,{enableRLS:()=>{return w[O4.Symbol.EnableRLS]=!0,w}})}var y1=($,T,W)=>{return Xk($,T,W,void 0)};function iD(...$){if($[0].columns)return new o2($[0].columns,$[0].name);return new o2($)}class o2{static[Z]="PgPrimaryKeyBuilder";columns;name;constructor($,T){this.columns=$,this.name=T}build($){return new nD($,this.columns,this.name)}}class nD{constructor($,T,W){this.table=$,this.columns=T,this.name=W}static[Z]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[O4.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}function m4($,T){if(oQ(T)&&!V7($)&&!S($,T6)&&!S($,b1)&&!S($,B$)&&!S($,c)&&!S($,g4))return new T6($,T);return $}var p8=($,T)=>{return O`${$} = ${m4(T,$)}`},tD=($,T)=>{return O`${$} <> ${m4(T,$)}`};function l2(...$){let T=$.filter((W)=>W!==void 0);if(T.length===0)return;if(T.length===1)return new p(T);return new p([new J4("("),O.join(T,new J4(" and ")),new J4(")")])}function aD(...$){let T=$.filter((W)=>W!==void 0);if(T.length===0)return;if(T.length===1)return new p(T);return new p([new J4("("),O.join(T,new J4(" or ")),new J4(")")])}function sD($){return O`not ${$}`}var d8=($,T)=>{return O`${$} > ${m4(T,$)}`},eD=($,T)=>{return O`${$} >= ${m4(T,$)}`},$O=($,T)=>{return O`${$} < ${m4(T,$)}`},TO=($,T)=>{return O`${$} <= ${m4(T,$)}`};function WO($,T){if(Array.isArray(T)){if(T.length===0)return O`false`;return O`${$} in ${T.map((W)=>m4(W,$))}`}return O`${$} in ${m4(T,$)}`}function XO($,T){if(Array.isArray(T)){if(T.length===0)return O`true`;return O`${$} not in ${T.map((W)=>m4(W,$))}`}return O`${$} not in ${m4(T,$)}`}function YO($){return O`${$} is null`}function UO($){return O`${$} is not null`}function GO($){return O`exists ${$}`}function JO($){return O`not exists ${$}`}function wO($,T,W){return O`${$} between ${m4(T,$)} and ${m4(W,$)}`}function zO($,T,W){return O`${$} not between ${m4(T,$)} and ${m4(W,$)}`}function _O($,T){return O`${$} like ${T}`}function HO($,T){return O`${$} not like ${T}`}function FO($,T){return O`${$} ilike ${T}`}function QO($,T){return O`${$} not ilike ${T}`}function ZO($){return O`${$} asc`}function DO($){return O`${$} desc`}class B7{constructor($,T,W){this.sourceTable=$,this.referencedTable=T,this.relationName=W,this.referencedTableName=T[c.Symbol.Name]}static[Z]="Relation";referencedTableName;fieldName}class OO{constructor($,T){this.table=$,this.config=T}static[Z]="Relations"}class h1 extends B7{constructor($,T,W,X){super($,T,W?.relationName);this.config=W,this.isNullable=X}static[Z]="One";withFieldName($){let T=new h1(this.sourceTable,this.referencedTable,this.config,this.isNullable);return T.fieldName=$,T}}class r2 extends B7{constructor($,T,W){super($,T,W?.relationName);this.config=W}static[Z]="Many";withFieldName($){let T=new r2(this.sourceTable,this.referencedTable,this.config);return T.fieldName=$,T}}function VO(){return{and:l2,between:wO,eq:p8,exists:GO,gt:d8,gte:eD,ilike:FO,inArray:WO,isNull:YO,isNotNull:UO,like:_O,lt:$O,lte:TO,ne:tD,not:sD,notBetween:zO,notExists:JO,notLike:HO,notIlike:QO,notInArray:XO,or:aD,sql:O}}function KO(){return{sql:O,asc:ZO,desc:DO}}function EO($,T){if(Object.keys($).length===1&&"default"in $&&!S($.default,c))$=$.default;let W={},X={},Y={};for(let[U,G]of Object.entries($))if(S(G,c)){let J=R0(G),z=X[J];W[J]=U,Y[U]={tsName:U,dbName:G[c.Symbol.Name],schema:G[c.Symbol.Schema],columns:G[c.Symbol.Columns],relations:z?.relations??{},primaryKey:z?.primaryKey??[]};for(let H of Object.values(G[c.Symbol.Columns]))if(H.primary)Y[U].primaryKey.push(H);let w=G[c.Symbol.ExtraConfigBuilder]?.(G[c.Symbol.ExtraConfigColumns]);if(w){for(let H of Object.values(w))if(S(H,o2))Y[U].primaryKey.push(...H.columns)}}else if(S(G,OO)){let J=R0(G.table),z=W[J],w=G.config(T(G.table)),H;for(let[_,F]of Object.entries(w))if(z){let D=Y[z];if(D.relations[_]=F,H)D.primaryKey.push(...H)}else{if(!(J in X))X[J]={relations:{},primaryKey:H};X[J].relations[_]=F}}return{tables:Y,tableNamesMap:W}}function Yk($){return function T(W,X){return new h1($,W,X,X?.fields.reduce((Y,U)=>Y&&U.notNull,!0)??!1)}}function Uk($){return function T(W,X){return new r2($,W,X)}}function MO($,T,W){if(S(W,h1)&&W.config)return{fields:W.config.fields,references:W.config.references};let X=T[R0(W.referencedTable)];if(!X)throw new Error(`Table "${W.referencedTable[c.Symbol.Name]}" not found in schema`);let Y=$[X];if(!Y)throw new Error(`Table "${X}" not found in schema`);let U=W.sourceTable,G=T[R0(U)];if(!G)throw new Error(`Table "${U[c.Symbol.Name]}" not found in schema`);let J=[];for(let z of Object.values(Y.relations))if(W.relationName&&W!==z&&z.relationName===W.relationName||!W.relationName&&z.referencedTable===W.sourceTable)J.push(z);if(J.length>1)throw W.relationName?new Error(`There are multiple relations with name "${W.relationName}" in table "${X}"`):new Error(`There are multiple relations between "${X}" and "${W.sourceTable[c.Symbol.Name]}". Please specify relation name`);if(J[0]&&S(J[0],h1)&&J[0].config)return{fields:J[0].config.references,references:J[0].config.fields};throw new Error(`There is not enough information to infer relation "${G}.${W.fieldName}"`)}function AO($){return{one:Yk($),many:Uk($)}}function o8($,T,W,X,Y=(U)=>U){let U={};for(let[G,J]of X.entries())if(J.isJson){let z=T.relations[J.tsKey],w=W[G],H=typeof w==="string"?JSON.parse(w):w;U[J.tsKey]=S(z,h1)?H&&o8($,$[J.relationTableTsKey],H,J.selection,Y):H.map((_)=>o8($,$[J.relationTableTsKey],_,J.selection,Y))}else{let z=Y(W[G]),w=J.field,H;if(S(w,B$))H=w;else if(S(w,p))H=w.decoder;else H=w.sql.decoder;U[J.tsKey]=z===null?null:H.mapFromDriverValue(z)}return U}import iv from"path";import qk from"os";import Pk from"fs";var l8=new Map,R7=new Map,I7=Symbol("OriginError"),IT={};class _6 extends Promise{constructor($,T,W,X,Y={}){let U,G;super((J,z)=>{U=J,G=z});this.tagged=Array.isArray($.raw),this.strings=$,this.args=T,this.handler=W,this.canceller=X,this.options=Y,this.state=null,this.statement=null,this.resolve=(J)=>(this.active=!1,U(J)),this.reject=(J)=>(this.active=!1,G(J)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[I7]=this.handler.debug?new Error:this.tagged&&Gk(this.strings)}get origin(){return(this.handler.debug?this[I7].stack:this.tagged&&R7.has(this.strings)?R7.get(this.strings):R7.set(this.strings,this[I7].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($=1,T){if(this.options.simple=!1,typeof $==="function")T=$,$=1;if(this.cursorRows=$,typeof T==="function")return this.cursorFn=T,this;let W;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};W&&W();let X=new Promise((Y,U)=>{this.cursorFn=(G)=>{return Y({value:G,done:!1}),new Promise((J)=>W=J)},this.resolve=()=>(this.active=!1,Y({done:!0})),this.reject=(G)=>(this.active=!1,U(G))});return this.execute(),X},return(){return W&&W(IT),{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($){return this.forEachFn=$,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 Gk($){if(l8.has($))return l8.get($);let T=Error.stackTraceLimit;return Error.stackTraceLimit=4,l8.set($,new Error),Error.stackTraceLimit=T,l8.get($)}class kT extends Error{constructor($){super($.message);this.name=this.constructor.name,Object.assign(this,$)}}var a$={connection:NO,postgres:LO,generic:SO,notSupported:BO};function NO($,T,W){let{host:X,port:Y}=W||T,U=Object.assign(new Error("write "+$+" "+(T.path||X+":"+Y)),{code:$,errno:$,address:T.path||X},T.path?{}:{port:Y});return Error.captureStackTrace(U,NO),U}function LO($){let T=new kT($);return Error.captureStackTrace(T,LO),T}function SO($,T){let W=Object.assign(new Error($+": "+T),{code:$});return Error.captureStackTrace(W,SO),W}function BO($){let T=Object.assign(new Error($+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:$});return Error.captureStackTrace(T,BO),T}var Jk={string:{to:25,from:null,serialize:($)=>""+$},number:{to:0,from:[21,23,26,700,701],serialize:($)=>""+$,parse:($)=>+$},json:{to:114,from:[114,3802],serialize:($)=>JSON.stringify($),parse:($)=>JSON.parse($)},boolean:{to:16,from:16,serialize:($)=>$===!0?"t":"f",parse:($)=>$==="t"},date:{to:1184,from:[1082,1114,1184],serialize:($)=>($ instanceof Date?$:new Date($)).toISOString(),parse:($)=>new Date($)},bytea:{to:17,from:17,serialize:($)=>"\\x"+Buffer.from($).toString("hex"),parse:($)=>Buffer.from($.slice(2),"hex")}};class n8{then(){k7()}catch(){k7()}finally(){k7()}}class a2 extends n8{constructor($){super();this.value=s8($)}}class h6 extends n8{constructor($,T,W){super();this.value=$,this.type=T,this.array=W}}class t8 extends n8{constructor($,T){super();this.first=$,this.rest=T}build($,T,W,X){let Y=wk.map(([U,G])=>({fn:G,i:$.search(U)})).sort((U,G)=>U.i-G.i).pop();return Y.i===-1?j7(this.first,X):Y.fn(this.first,this.rest,T,W,X)}}function a8($,T,W,X){let Y=$ instanceof h6?$.value:$;if(Y===void 0){if($ instanceof h6?$.value=X.transform.undefined:Y=$=X.transform.undefined,Y===void 0)throw a$.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+W.push($ instanceof h6?(T.push($.value),$.array?$.array[$.type||i8($.value)]||$.type||qO($.value):$.type):(T.push($),i8($)))}var IO=CO(Jk);function C7($,T,W,X,Y,U){for(let G=1;G<$.strings.length;G++)T+=v7(T,W,X,Y,U)+$.strings[G],W=$.args[G];return T}function v7($,T,W,X,Y){return T instanceof t8?T.build($,W,X,Y):T instanceof _6?P7(T,W,X,Y):T instanceof a2?T.value:T&&T[0]instanceof _6?T.reduce((U,G)=>U+" "+P7(G,W,X,Y),""):a8(T,W,X,Y)}function P7($,T,W,X){return $.fragment=!0,C7($,$.strings[0],$.args[0],T,W,X)}function kO($,T,W,X,Y){return $.map((U)=>"("+X.map((G)=>v7("values",U[G],T,W,Y)).join(",")+")").join(",")}function RO($,T,W,X,Y){let U=Array.isArray($[0]),G=T.length?T.flat():Object.keys(U?$[0]:$);return kO(U?$:[$],W,X,G,Y)}function r8($,T,W,X,Y){if(typeof $==="string"&&($=[$].concat(T)),Array.isArray($))return j7($,Y);let U;return(T.length?T.flat():Object.keys($)).map((J)=>{return U=$[J],(U instanceof _6?P7(U,W,X,Y):U instanceof a2?U.value:a8(U,W,X,Y))+" as "+s8(Y.transform.column.to?Y.transform.column.to(J):J)}).join(",")}var wk=Object.entries({values:RO,in:(...$)=>{let T=RO(...$);return T==="()"?"(null)":T},select:r8,as:r8,returning:r8,"\\(":r8,update($,T,W,X,Y){return(T.length?T.flat():Object.keys($)).map((U)=>s8(Y.transform.column.to?Y.transform.column.to(U):U)+"="+v7("values",$[U],W,X,Y))},insert($,T,W,X,Y){let U=T.length?T.flat():Object.keys(Array.isArray($)?$[0]:$);return"("+j7(U,Y)+")values"+kO(Array.isArray($)?$:[$],W,X,U,Y)}}).map(([$,T])=>[new RegExp("((?:^|[\\s(])"+$+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),T]);function k7(){throw a$.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:zk,parsers:_k}=IO;function qO($){if(Array.isArray($))return qO($[0]);return typeof $==="string"?1009:0}var PO=function($){let T=CO($||{});return{serializers:Object.assign({},zk,T.serializers),parsers:Object.assign({},_k,T.parsers)}};function CO($){return Object.keys($).reduce((T,W)=>{if($[W].from&&[].concat($[W].from).forEach((X)=>T.parsers[X]=$[W].parse),$[W].serialize)T.serializers[$[W].to]=$[W].serialize,$[W].from&&[].concat($[W].from).forEach((X)=>T.serializers[X]=$[W].serialize);return T},{parsers:{},serializers:{}})}function j7($,{transform:{column:T}}){return $.map((W)=>s8(T.to?T.to(W):W)).join(",")}var s8=function $(T){return'"'+T.replace(/"/g,'""').replace(/\./g,'"."')+'"'},i8=function $(T){return T instanceof h6?T.type:T instanceof Date?1184:T instanceof Uint8Array?17:T===!0||T===!1?16:typeof T==="bigint"?20:Array.isArray(T)?$(T[0]):0},Hk=/\\/g,Fk=/"/g;function Qk($){return $.replace(Hk,"\\\\").replace(Fk,"\\\"")}var vO=function $(T,W,X,Y){if(Array.isArray(T)===!1)return T;if(!T.length)return"{}";let U=T[0],G=Y===1020?";":",";if(Array.isArray(U)&&!U.type)return"{"+T.map((J)=>$(J,W,X,Y)).join(G)+"}";return"{"+T.map((J)=>{if(J===void 0){if(J=X.transform.undefined,J===void 0)throw a$.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return J===null?"null":'"'+Qk(W?W(J.type?J.value:J):""+J)+'"'}).join(G)+"}"},q7={i:0,char:null,str:"",quoted:!1,last:0},jO=function $(T,W,X){return q7.i=q7.last=0,xO(q7,T,W,X)};function xO($,T,W,X){let Y=[],U=X===1020?";":",";for(;$.i<T.length;$.i++){if($.char=T[$.i],$.quoted)if($.char==="\\")$.str+=T[++$.i];else if($.char==='"')Y.push(W?W($.str):$.str),$.str="",$.quoted=T[$.i+1]==='"',$.last=$.i+2;else $.str+=$.char;else if($.char==='"')$.quoted=!0;else if($.char==="{")$.last=++$.i,Y.push(xO($,T,W,X));else if($.char==="}"){$.quoted=!1,$.last<$.i&&Y.push(W?W(T.slice($.last,$.i)):T.slice($.last,$.i)),$.last=$.i+1;break}else if($.char===U&&$.p!=="}"&&$.p!=='"')Y.push(W?W(T.slice($.last,$.i)):T.slice($.last,$.i)),$.last=$.i+1;$.p=$.char}return $.last<$.i&&Y.push(W?W(T.slice($.last,$.i+1)):T.slice($.last,$.i+1)),Y}var I0=($)=>{let T=$[0];for(let W=1;W<$.length;W++)T+=$[W]==="_"?$[++W].toUpperCase():$[W];return T},k0=($)=>{let T=$[0].toUpperCase();for(let W=1;W<$.length;W++)T+=$[W]==="_"?$[++W].toUpperCase():$[W];return T},q0=($)=>$.replace(/_/g,"-"),i2=($)=>$.replace(/([A-Z])/g,"_$1").toLowerCase(),n2=($)=>($.slice(0,1)+$.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),t2=($)=>$.replace(/-/g,"_");function x7($){return function T(W,X){return typeof W==="object"&&W!==null&&(X.type===114||X.type===3802)?Array.isArray(W)?W.map((Y)=>T(Y,X)):Object.entries(W).reduce((Y,[U,G])=>Object.assign(Y,{[$(U)]:T(G,X)}),{}):W}}I0.column={from:I0};I0.value={from:x7(I0)};i2.column={to:i2};var b7={...I0};b7.column.to=i2;k0.column={from:k0};k0.value={from:x7(k0)};n2.column={to:n2};var f7={...k0};f7.column.to=n2;q0.column={from:q0};q0.value={from:x7(q0)};t2.column={to:t2};var y7={...q0};y7.column.to=t2;import bO from"net";import Vk from"tls";import s2 from"crypto";import h7 from"stream";import{performance as fO}from"perf_hooks";class P0 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 W6=Zk;function Zk($=[]){let T=$.slice(),W=0;return{get length(){return T.length-W},remove:(X)=>{let Y=T.indexOf(X);return Y===-1?null:(T.splice(Y,1),X)},push:(X)=>(T.push(X),X),shift:()=>{let X=T[W++];if(W===T.length)W=0,T=[];else T[W-1]=void 0;return X}}}var N4=Buffer.allocUnsafe(256),Dk="BCcDdEFfHPpQSX".split("").reduce(($,T)=>{let W=T.charCodeAt(0);return $[T]=()=>{return N4[0]=W,S$.i=5,S$},$},{}),S$=Object.assign(Ok,Dk,{N:String.fromCharCode(0),i:0,inc($){return S$.i+=$,S$},str($){let T=Buffer.byteLength($);return e8(T),S$.i+=N4.write($,S$.i,T,"utf8"),S$},i16($){return e8(2),N4.writeUInt16BE($,S$.i),S$.i+=2,S$},i32($,T){if(T||T===0)return N4.writeUInt32BE($,T),S$;return e8(4),N4.writeUInt32BE($,S$.i),S$.i+=4,S$},z($){return e8($),N4.fill(0,S$.i,S$.i+$),S$.i+=$,S$},raw($){return N4=Buffer.concat([N4.subarray(0,S$.i),$]),S$.i=N4.length,S$},end($=1){N4.writeUInt32BE(S$.i-$,$);let T=N4.subarray(0,S$.i);return S$.i=0,N4=Buffer.allocUnsafe(256),T}}),i=S$;function e8($){if(N4.length-S$.i<$){let T=N4,W=T.length;N4=Buffer.allocUnsafe(W+(W>>1)+$),T.copy(N4)}}function Ok(){return S$.i=0,S$}var c7=gO,Kk=1,g1=i().S().end(),yO=i().H().end(),Ek=i().i32(8).i32(80877103).end(8),Mk=Buffer.concat([i().E().str(i.N).i32(0).end(),g1]),Ak=i().D().str("S").str(i.N).end(),qT=()=>{},Nk=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Lk={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 gO($,T={},{onopen:W=qT,onend:X=qT,onclose:Y=qT}={}){let{ssl:U,max:G,user:J,host:z,port:w,database:H,parsers:_,transform:F,onnotice:D,onnotify:V,onparameter:E,max_pipeline:R,keep_alive:P,backoff:A,target_session_attrs:N}=$,k=W6(),y=Kk++,x={pid:null,secret:null},m=m7(uU,$.idle_timeout),J$=m7(uU,$.max_lifetime),m$=m7(SM,$.connect_timeout),B=null,Z$,$$=new P0,H$=Buffer.alloc(0),e$=$.fetch_types,V4={},D6={},g0=Math.random().toString(36).slice(2),v=1,e=0,M$=0,g$=0,$4=0,w$=0,A$=0,i$=0,c$=null,x$=null,K4=!1,k$=null,O6=null,Q4=null,K1=null,T4=null,b$=null,V6=null,k6=null,h=null,sT=null,E4={queue:T.closed,idleTimer:m,connect(Q){Q4=Q,v5()},terminate:$W,execute:eT,cancel:MM,end:uU,count:0,id:y};return T.closed&&T.closed.push(E4),E4;async function EM(){let Q;try{Q=$.socket?await Promise.resolve($.socket($)):new bO.Socket}catch(M){c0(M);return}return Q.on("error",c0),Q.on("close",j5),Q.on("drain",P5),Q}async function MM({pid:Q,secret:M},t,V$){try{Z$=i().i32(16).i32(80877102).i32(Q).i32(M).end(16),await C5(),B.once("error",V$),B.once("close",t)}catch(o$){V$(o$)}}function eT(Q){if(K4)return xX(Q,a$.connection("CONNECTION_DESTROYED",$));if(Q.cancelled)return;try{return Q.state=x,h?k.push(Q):(h=Q,h.active=!0),LM(Q),Z4(AM(Q))&&!Q.describeFirst&&!Q.cursorFn&&k.length<R&&(!Q.options.onexecute||Q.options.onexecute(E4))}catch(M){return k.length===0&&Z4(g1),q6(M),!0}}function AM(Q){if(Q.parameters.length>=65534)throw a$.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return Q.options.simple?i().Q().str(Q.statement.string+i.N).end():Q.describeFirst?Buffer.concat([I5(Q),yO]):Q.prepare?Q.prepared?jX(Q):Buffer.concat([I5(Q),jX(Q)]):NM(Q)}function I5(Q){return Buffer.concat([b5(Q.statement.string,Q.parameters,Q.statement.types,Q.statement.name),wA("S",Q.statement.name)])}function jX(Q){return Buffer.concat([JA(Q.parameters,Q.statement.types,Q.statement.name,Q.cursorName),Q.cursorFn?f5("",Q.cursorRows):Mk])}function NM(Q){return Buffer.concat([b5(Q.statement.string,Q.parameters,Q.statement.types),Ak,jX(Q)])}function LM(Q){let M=[],t=[],V$=C7(Q,Q.strings[0],Q.args[0],M,t,$);!Q.tagged&&Q.args.forEach((o$)=>a8(o$,M,t,$)),Q.prepare=$.prepare&&("prepare"in Q.options?Q.options.prepare:!0),Q.string=V$,Q.signature=Q.prepare&&t+V$,Q.onlyDescribe&&delete D6[Q.signature],Q.parameters=Q.parameters||M,Q.prepared=Q.prepare&&Q.signature in D6,Q.describeFirst=Q.onlyDescribe||M.length&&!Q.prepared,Q.statement=Q.prepared?D6[Q.signature]:{string:V$,types:t,name:Q.prepare?g0+v++:""},typeof $.debug==="function"&&$.debug(y,V$,M,t)}function Z4(Q,M){if(b$=b$?Buffer.concat([b$,Q]):Buffer.from(Q),M||b$.length>=1024)return k5(M);return x$===null&&(x$=setImmediate(k5)),!0}function k5(Q){let M=B.write(b$,Q);return x$!==null&&clearImmediate(x$),b$=x$=null,M}function SM(){q6(a$.connection("CONNECT_TIMEOUT",$,B)),B.destroy()}async function q5(){if(Z4(Ek),!await new Promise((M)=>B.once("data",(t)=>M(t[0]===83)))&&U==="prefer")return m0();B.removeAllListeners(),B=Vk.connect({socket:B,servername:bO.isIP(B.host)?void 0:B.host,...U==="require"||U==="allow"||U==="prefer"?{rejectUnauthorized:!1}:U==="verify-full"?{}:typeof U==="object"?U:{}}),B.on("secureConnect",m0),B.on("error",c0),B.on("close",j5),B.on("drain",P5)}function P5(){!h&&W(E4)}function cU(Q){if(k$){if(k$.push(Q),M$-=Q.length,M$>0)return}H$=k$?Buffer.concat(k$,w$-M$):H$.length===0?Q:Buffer.concat([H$,Q],H$.length+Q.length);while(H$.length>4){if(w$=H$.readUInt32BE(1),w$>=H$.length){M$=w$-H$.length,k$=[H$];break}try{BM(H$.subarray(0,w$+1))}catch(M){h&&(h.cursorFn||h.describeFirst)&&Z4(g1),q6(M)}H$=H$.subarray(w$+1),M$=0,k$=null}}async function C5(){if(K4=!1,V4={},B||(B=await EM()),!B)return;if(m$.start(),$.socket)return U?q5():m0();if(B.on("connect",U?q5:m0),$.path)return B.connect($.path);B.ssl=U,B.connect(w[g$],z[g$]),B.host=z[g$],B.port=w[g$],g$=(g$+1)%w.length}function v5(){setTimeout(C5,e?e+A$-fO.now():0)}function m0(){try{D6={},e$=$.fetch_types,g0=Math.random().toString(36).slice(2),v=1,J$.start(),B.on("data",cU),P&&B.setKeepAlive&&B.setKeepAlive(!0,1000*P);let Q=_A();Z4(Q)}catch(Q){c0(Q)}}function c0(Q){if(E4.queue===T.connecting&&$.host[$4+1])return;q6(Q);while(k.length)xX(k.shift(),Q)}function q6(Q){T4&&(T4.destroy(Q),T4=null),h&&xX(h,Q),Q4&&(xX(Q4,Q),Q4=null)}function xX(Q,M){if(Q.reserve)return Q.reject(M);if(!M||typeof M!=="object")M=new Error(M);"query"in M||"parameters"in M||Object.defineProperties(M,{stack:{value:M.stack+Q.origin.replace(/.*\n/,`
|
|
81
|
+
`),enumerable:$.debug},query:{value:Q.string,enumerable:$.debug},parameters:{value:Q.parameters,enumerable:$.debug},args:{value:Q.args,enumerable:$.debug},types:{value:Q.statement&&Q.statement.types,enumerable:$.debug}}),Q.reject(M)}function uU(){return K1||(!E4.reserved&&X(E4),!E4.reserved&&!Q4&&!h&&k.length===0?($W(),new Promise((Q)=>B&&B.readyState!=="closed"?B.once("close",Q):Q())):K1=new Promise((Q)=>V6=Q))}function $W(){if(K4=!0,T4||h||Q4||k.length)c0(a$.connection("CONNECTION_DESTROYED",$));if(clearImmediate(x$),B)B.removeListener("data",cU),B.removeListener("connect",m0),B.readyState==="open"&&B.end(i().X().end());V6&&(V6(),K1=V6=null)}async function j5(Q){if(H$=Buffer.alloc(0),M$=0,k$=null,clearImmediate(x$),B.removeListener("data",cU),B.removeListener("connect",m0),m.cancel(),J$.cancel(),m$.cancel(),B.removeAllListeners(),B=null,Q4)return v5();!Q&&(h||k.length)&&c0(a$.connection("CONNECTION_CLOSED",$,B)),e=fO.now(),Q&&$.shared.retries++,A$=(typeof A==="function"?A($.shared.retries):A)*1000,Y(E4,a$.connection("CONNECTION_CLOSED",$,B))}function BM(Q,M=Q[0]){(M===68?RM:M===100?eM:M===65?rM:M===83?IM:M===90?kM:M===67?qM:M===50?x5:M===49?PM:M===116?CM:M===84?vM:M===82?jM:M===110?gM:M===75?mM:M===69?oM:M===115?iM:M===51?nM:M===71?tM:M===78?TA:M===72?aM:M===99?$A:M===73?WA:M===86?XA:M===118?YA:M===87?sM:UA)(Q)}function RM(Q){let M=7,t,V$,o$,M4=h.isRaw?new Array(h.statement.columns.length):{};for(let B4=0;B4<h.statement.columns.length;B4++)V$=h.statement.columns[B4],t=Q.readInt32BE(M),M+=4,o$=t===-1?null:h.isRaw===!0?Q.subarray(M,M+=t):V$.parser===void 0?Q.toString("utf8",M,M+=t):V$.parser.array===!0?V$.parser(Q.toString("utf8",M+1,M+=t)):V$.parser(Q.toString("utf8",M,M+=t)),h.isRaw?M4[B4]=h.isRaw===!0?o$:F.value.from?F.value.from(o$,V$):o$:M4[V$.name]=F.value.from?F.value.from(o$,V$):o$;h.forEachFn?h.forEachFn(F.row.from?F.row.from(M4):M4,$$):$$[i$++]=F.row.from?F.row.from(M4):M4}function IM(Q){let[M,t]=Q.toString("utf8",5,Q.length-1).split(i.N);if(V4[M]=t,$.parameters[M]!==t)$.parameters[M]=t,E&&E(M,t)}function kM(Q){if(h&&h.options.simple&&h.resolve(O6||$$),h=O6=null,$$=new P0,m$.cancel(),Q4){if(N){if(!V4.in_hot_standby||!V4.default_transaction_read_only)return dM();else if(pM(N,V4))return $W()}if(e$)return Q4.reserve&&(Q4=null),cM();Q4&&!Q4.reserve&&eT(Q4),$.shared.retries=$4=0,Q4=null;return}while(k.length&&(h=k.shift())&&(h.active=!0,h.cancelled))gO($).cancel(h.state,h.cancelled.resolve,h.cancelled.reject);if(h)return;E4.reserved?!E4.reserved.release&&Q[5]===73?K1?$W():(E4.reserved=null,W(E4)):E4.reserved():K1?$W():W(E4)}function qM(Q){i$=0;for(let M=Q.length-1;M>0;M--){if(Q[M]===32&&Q[M+1]<58&&$$.count===null)$$.count=+Q.toString("utf8",M+1,Q.length-1);if(Q[M-1]>=65){$$.command=Q.toString("utf8",5,M),$$.state=x;break}}if(sT&&(sT(),sT=null),$$.command==="BEGIN"&&G!==1&&!E4.reserved)return q6(a$.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(h.options.simple)return x5();if(h.cursorFn)$$.count&&h.cursorFn($$),Z4(g1);h.resolve($$)}function PM(){h.parsing=!1}function x5(){!$$.statement&&($$.statement=h.statement),$$.columns=h.statement.columns}function CM(Q){let M=Q.readUInt16BE(5);for(let t=0;t<M;++t)!h.statement.types[t]&&(h.statement.types[t]=Q.readUInt32BE(7+t*4));h.prepare&&(D6[h.signature]=h.statement),h.describeFirst&&!h.onlyDescribe&&(Z4(jX(h)),h.describeFirst=!1)}function vM(Q){if($$.command)O6=O6||[$$],O6.push($$=new P0),$$.count=null,h.statement.columns=null;let M=Q.readUInt16BE(5),t=7,V$;h.statement.columns=Array(M);for(let o$=0;o$<M;++o$){V$=t;while(Q[t++]!==0);let M4=Q.readUInt32BE(t),B4=Q.readUInt16BE(t+4),E1=Q.readUInt32BE(t+6);h.statement.columns[o$]={name:F.column.from?F.column.from(Q.toString("utf8",V$,t-1)):Q.toString("utf8",V$,t-1),parser:_[E1],table:M4,number:B4,type:E1},t+=18}if($$.statement=h.statement,h.onlyDescribe)return h.resolve(h.statement),Z4(g1)}async function jM(Q,M=Q.readUInt32BE(5)){(M===3?xM:M===5?bM:M===10?fM:M===11?yM:M===12?hM:M!==0?GA:qT)(Q,M)}async function xM(){let Q=await pU();Z4(i().p().str(Q).z(1).end())}async function bM(Q){let M="md5"+await hO(Buffer.concat([Buffer.from(await hO(await pU()+J)),Q.subarray(9)]));Z4(i().p().str(M).z(1).end())}async function fM(){k6=(await s2.randomBytes(18)).toString("base64"),i().p().str("SCRAM-SHA-256"+i.N);let Q=i.i;Z4(i.inc(4).str("n,,n=*,r="+k6).i32(i.i-Q-4,Q).end())}async function yM(Q){let M=Q.toString("utf8",9).split(",").reduce((B4,E1)=>(B4[E1[0]]=E1.slice(2),B4),{}),t=await s2.pbkdf2Sync(await pU(),Buffer.from(M.s,"base64"),parseInt(M.i),32,"sha256"),V$=await $U(t,"Client Key"),o$="n=*,r="+k6+",r="+M.r+",s="+M.s+",i="+M.i+",c=biws,r="+M.r;c$=(await $U(await $U(t,"Server Key"),o$)).toString("base64");let M4="c=biws,r="+M.r+",p="+Bk(V$,Buffer.from(await $U(await Sk(V$),o$))).toString("base64");Z4(i().p().str(M4).end())}function hM(Q){if(Q.toString("utf8",9).split(i.N,1)[0].slice(2)===c$)return;q6(a$.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),B.destroy()}function pU(){return Promise.resolve(typeof $.pass==="function"?$.pass():$.pass)}function gM(){if($$.statement=h.statement,$$.statement.columns=[],h.onlyDescribe)return h.resolve(h.statement),Z4(g1)}function mM(Q){x.pid=Q.readUInt32BE(5),x.secret=Q.readUInt32BE(9)}async function cM(){e$=!1,(await new _6([`
|
|
58
82
|
select b.oid, b.typarray
|
|
59
83
|
from pg_catalog.pg_type a
|
|
60
84
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
61
85
|
where a.typcategory = 'A'
|
|
62
86
|
group by b.oid, b.typarray
|
|
63
87
|
order by b.oid
|
|
64
|
-
`],[],
|
|
88
|
+
`],[],eT)).forEach(({oid:M,typarray:t})=>uM(M,t))}function uM(Q,M){if(!!$.parsers[M]&&!!$.serializers[M])return;let t=$.parsers[Q];$.shared.typeArrayMap[Q]=M,$.parsers[M]=(V$)=>jO(V$,t,M),$.parsers[M].array=!0,$.serializers[M]=(V$)=>vO(V$,$.serializers[Q],$,M)}function pM(Q,M){return Q==="read-write"&&M.default_transaction_read_only==="on"||Q==="read-only"&&M.default_transaction_read_only==="off"||Q==="primary"&&M.in_hot_standby==="on"||Q==="standby"&&M.in_hot_standby==="off"||Q==="prefer-standby"&&M.in_hot_standby==="off"&&$.host[$4]}function dM(){let Q=new _6([`
|
|
65
89
|
show transaction_read_only;
|
|
66
90
|
select pg_catalog.pg_is_in_recovery()
|
|
67
|
-
`],[],
|
|
91
|
+
`],[],eT,null,{simple:!0});Q.resolve=([[M],[t]])=>{V4.default_transaction_read_only=M.transaction_read_only,V4.in_hot_standby=t.pg_is_in_recovery?"on":"off"},Q.execute()}function oM(Q){h&&(h.cursorFn||h.describeFirst)&&Z4(g1);let M=a$.postgres(g7(Q));h&&h.retried?q6(h.retried):h&&h.prepared&&Nk.has(M.routine)?lM(h,M):q6(M)}function lM(Q,M){delete D6[Q.signature],Q.retried=M,eT(Q)}function rM(Q){if(!V)return;let M=9;while(Q[M++]!==0);V(Q.toString("utf8",9,M-1),Q.toString("utf8",M,Q.length-1))}async function iM(){try{let Q=await Promise.resolve(h.cursorFn($$));i$=0,Q===IT?Z4(zA(h.portal)):($$=new P0,Z4(f5("",h.cursorRows)))}catch(Q){Z4(g1),h.reject(Q)}}function nM(){$$.count&&h.cursorFn($$),h.resolve($$)}function tM(){T4=new h7.Writable({autoDestroy:!0,write(Q,M,t){B.write(i().d().raw(Q).end(),t)},destroy(Q,M){M(Q),B.write(i().f().str(Q+i.N).end()),T4=null},final(Q){B.write(i().c().end()),sT=Q}}),h.resolve(T4)}function aM(){T4=new h7.Readable({read(){B.resume()}}),h.resolve(T4)}function sM(){T4=new h7.Duplex({autoDestroy:!0,read(){B.resume()},write(Q,M,t){B.write(i().d().raw(Q).end(),t)},destroy(Q,M){M(Q),B.write(i().f().str(Q+i.N).end()),T4=null},final(Q){B.write(i().c().end()),sT=Q}}),h.resolve(T4)}function eM(Q){T4&&(T4.push(Q.subarray(5))||B.pause())}function $A(){T4&&T4.push(null),T4=null}function TA(Q){D?D(g7(Q)):console.log(g7(Q))}function WA(){}function XA(){q6(a$.notSupported("FunctionCallResponse"))}function YA(){q6(a$.notSupported("NegotiateProtocolVersion"))}function UA(Q){console.error("Postgres.js : Unknown Message:",Q[0])}function GA(Q,M){console.error("Postgres.js : Unknown Auth:",M)}function JA(Q,M,t="",V$=""){let o$,M4;return i().B().str(V$+i.N).str(t+i.N).i16(0).i16(Q.length),Q.forEach((B4,E1)=>{if(B4===null)return i.i32(4294967295);M4=M[E1],Q[E1]=B4=M4 in $.serializers?$.serializers[M4](B4):""+B4,o$=i.i,i.inc(4).str(B4).i32(i.i-o$-4,o$)}),i.i16(0),i.end()}function b5(Q,M,t,V$=""){return i().P().str(V$+i.N).str(Q+i.N).i16(M.length),M.forEach((o$,M4)=>i.i32(t[M4]||0)),i.end()}function wA(Q,M=""){return i().D().str(Q).str(M+i.N).end()}function f5(Q="",M=0){return Buffer.concat([i().E().str(Q+i.N).i32(M).end(),yO])}function zA(Q=""){return Buffer.concat([i().C().str("P").str(Q+i.N).end(),i().S().end()])}function _A(){return Z$||i().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:J,database:H,client_encoding:"UTF8"},$.connection)).filter(([,Q])=>Q).map(([Q,M])=>Q+i.N+M).join(i.N)).z(2).end(0)}}function g7($){let T={},W=5;for(let X=5;X<$.length-1;X++)if($[X]===0)T[Lk[$[W]]]=$.toString("utf8",W+1,X),W=X+1;return T}function hO($){return s2.createHash("md5").update($).digest("hex")}function $U($,T){return s2.createHmac("sha256",$).update(T).digest()}function Sk($){return s2.createHash("sha256").update($).digest()}function Bk($,T){let W=Math.max($.length,T.length),X=Buffer.allocUnsafe(W);for(let Y=0;Y<W;Y++)X[Y]=$[Y]^T[Y];return X}function m7($,T){if(T=typeof T==="function"?T():T,!T)return{cancel:qT,start:qT};let W;return{cancel(){W&&(clearTimeout(W),W=null)},start(){W&&clearTimeout(W),W=setTimeout(X,T*1000,arguments)}};function X(Y){$.apply(null,Y),W=null}}var mO=()=>{};function u7($,T){let W=new Map,X="postgresjs_"+Math.random().toString(36).slice(2),Y={},U,G,J=!1,z=_.sql=$({...T,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...T.connection,replication:"database"},onclose:async function(){if(J)return;G=null,Y.pid=Y.secret=void 0,F(await D(z,X,T.publications)),W.forEach((E)=>E.forEach(({onsubscribe:R})=>R()))},no_subscribe:!0}),w=z.end,H=z.close;return z.end=async()=>{return J=!0,G&&await new Promise((E)=>(G.once("close",E),G.end())),w()},z.close=async()=>{return G&&await new Promise((E)=>(G.once("close",E),G.end())),H()},_;async function _(E,R,P=mO,A=mO){if(E=kk(E),!U)U=D(z,X,T.publications);let N={fn:R,onsubscribe:P},k=W.has(E)?W.get(E).add(N):W.set(E,new Set([N])).get(E),y=()=>{k.delete(N),k.size===0&&W.delete(E)};return U.then((x)=>{return F(x),P(),G&&G.on("error",A),{unsubscribe:y,state:Y,sql:z}})}function F(E){G=E.stream,Y.pid=E.state.pid,Y.secret=E.state.secret}async function D(E,R,P){if(!P)throw new Error("Missing publication names");let A=await E.unsafe(`CREATE_REPLICATION_SLOT ${R} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[N]=A,k=await E.unsafe(`START_REPLICATION SLOT ${R} LOGICAL ${N.consistent_point} (proto_version '1', publication_names '${P}')`).writable(),y={lsn:Buffer.concat(N.consistent_point.split("/").map((B)=>Buffer.from(("00000000"+B).slice(-8),"hex")))};return k.on("data",m),k.on("error",x),k.on("close",E.close),{stream:k,state:A.state};function x(B){console.error("Unexpected error during logical streaming - reconnecting",B)}function m(B){if(B[0]===119)Ik(B.subarray(25),y,E.options.parsers,J$,T.transform);else if(B[0]===107&&B[17])y.lsn=B.subarray(1,9),m$()}function J$(B,Z$){let $$=Z$.relation.schema+"."+Z$.relation.table;V("*",B,Z$),V("*:"+$$,B,Z$),Z$.relation.keys.length&&V("*:"+$$+"="+Z$.relation.keys.map((H$)=>B[H$.name]),B,Z$),V(Z$.command,B,Z$),V(Z$.command+":"+$$,B,Z$),Z$.relation.keys.length&&V(Z$.command+":"+$$+"="+Z$.relation.keys.map((H$)=>B[H$.name]),B,Z$)}function m$(){let B=Buffer.alloc(34);B[0]=114,B.fill(y.lsn,1),B.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),k.write(B)}}function V(E,R,P){W.has(E)&&W.get(E).forEach(({fn:A})=>A(R,P,E))}}function Rk($){return new Date(Date.UTC(2000,0,1)+Number($/BigInt(1000)))}function Ik($,T,W,X,Y){let U=(G,[J,z])=>(G[J.charCodeAt(0)]=z,G);Object.entries({R:(G)=>{let J=1,z=T[G.readUInt32BE(J)]={schema:G.toString("utf8",J+=4,J=G.indexOf(0,J))||"pg_catalog",table:G.toString("utf8",J+1,J=G.indexOf(0,J+1)),columns:Array(G.readUInt16BE(J+=2)),keys:[]};J+=2;let w=0,H;while(J<G.length)H=z.columns[w++]={key:G[J++],name:Y.column.from?Y.column.from(G.toString("utf8",J,J=G.indexOf(0,J))):G.toString("utf8",J,J=G.indexOf(0,J)),type:G.readUInt32BE(J+=1),parser:W[G.readUInt32BE(J)],atttypmod:G.readUInt32BE(J+=4)},H.key&&z.keys.push(H),J+=4},Y:()=>{},O:()=>{},B:(G)=>{T.date=Rk(G.readBigInt64BE(9)),T.lsn=G.subarray(1,9)},I:(G)=>{let J=1,z=T[G.readUInt32BE(J)],{row:w}=TU(G,z.columns,J+=7,Y);X(w,{command:"insert",relation:z})},D:(G)=>{let J=1,z=T[G.readUInt32BE(J)];J+=4;let w=G[J]===75;X(w||G[J]===79?TU(G,z.columns,J+=3,Y).row:null,{command:"delete",relation:z,key:w})},U:(G)=>{let J=1,z=T[G.readUInt32BE(J)];J+=4;let w=G[J]===75,H=w||G[J]===79?TU(G,z.columns,J+=3,Y):null;H&&(J=H.i);let{row:_}=TU(G,z.columns,J+3,Y);X(_,{command:"update",relation:z,key:w,old:H&&H.row})},T:()=>{},C:()=>{}}).reduce(U,{})[$[0]]($)}function TU($,T,W,X){let Y,U,G,J=X.raw?new Array(T.length):{};for(let z=0;z<T.length;z++)Y=$[W++],U=T[z],G=Y===110?null:Y===117?void 0:U.parser===void 0?$.toString("utf8",W+4,W+=4+$.readUInt32BE(W)):U.parser.array===!0?U.parser($.toString("utf8",W+5,W+=4+$.readUInt32BE(W))):U.parser($.toString("utf8",W+4,W+=4+$.readUInt32BE(W))),X.raw?J[z]=X.raw===!0?G:X.value.from?X.value.from(G,U):G:J[U.name]=X.value.from?X.value.from(G,U):G;return{i:W,row:X.row.from?X.row.from(J):J}}function kk($){let T=$.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!T)throw new Error("Malformed subscribe pattern: "+$);let[,W,X,Y]=T;return(W||"*")+(X?":"+(X.indexOf(".")===-1?"public."+X:X):"")+(Y?"="+Y:"")}import cO from"stream";function p7($,T,W=393216){return new Promise(async(X,Y)=>{await $.begin(async(U)=>{let G;!T&&([{oid:T}]=await U`select lo_creat(-1) as oid`);let[{fd:J}]=await U`select lo_open(${T}, ${W}) as fd`,z={writable:H,readable:w,close:()=>U`select lo_close(${J})`.then(G),tell:()=>U`select lo_tell64(${J})`,read:(_)=>U`select loread(${J}, ${_}) as data`,write:(_)=>U`select lowrite(${J}, ${_})`,truncate:(_)=>U`select lo_truncate64(${J}, ${_})`,seek:(_,F=0)=>U`select lo_lseek64(${J}, ${_}, ${F})`,size:()=>U`
|
|
68
92
|
select
|
|
69
|
-
lo_lseek64(${
|
|
93
|
+
lo_lseek64(${J}, location, 0) as position,
|
|
70
94
|
seek.size
|
|
71
95
|
from (
|
|
72
96
|
select
|
|
@@ -74,62 +98,62 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
74
98
|
tell.location
|
|
75
99
|
from (select lo_tell64($1) as location) tell
|
|
76
100
|
) seek
|
|
77
|
-
`};return X(Q),new Promise(async(F)=>H=F);async function _({highWaterMark:F=16384,start:w=0,end:O=1/0}={}){let V=O-w;return w&&await Q.seek(w),new Hz.Readable({highWaterMark:F,async read(E){let I=E>V?E-V:E;V-=E;let[{data:j}]=await Q.read(I);if(this.push(j),j.length<E)this.push(null)}})}async function z({highWaterMark:F=16384,start:w=0}={}){return w&&await Q.seek(w),new Hz.Writable({highWaterMark:F,write(O,V,E){Q.write(O).then(()=>E(),E)}})}}).catch(G)})}Object.assign(hX,{PostgresError:A8,toPascal:N2,pascal:U7,toCamel:Z2,camel:w7,toKebab:R2,kebab:D7,fromPascal:A6,fromCamel:E6,fromKebab:L6,BigInt:{to:20,from:[20],parse:(W)=>BigInt(W),serialize:(W)=>W.toString()}});var Z8=hX;function hX(W,$){let Y=mO(W,$),X=Y.no_subscribe||E7(hX,{...Y}),G=!1,J=$W(),H=$W(),T=$W(),Q=$W(),_=$W(),z=$W(),F=$W(),w=$W(),O={connecting:H,reserved:T,closed:Q,ended:_,open:z,busy:F,full:w},V=[...Array(Y.max)].map(()=>K7(Y,O,{onopen:MW,onend:V1,onclose:b2})),E=I(w0);return Object.assign(E,{get parameters(){return Y.parameters},largeObject:A7.bind(null,E),subscribe:X,CLOSE:E8,END:E8,PostgresError:A8,options:Y,reserve:B,listen:j,begin:P,close:Y0,end:M0}),E;function I(k){return k.debug=Y.debug,Object.entries(Y.types).reduce((z0,[j0,r0])=>{return z0[j0]=(u0)=>new pW(u0,r0.to),z0},e),Object.assign(R0,{types:e,typed:e,unsafe:m0,notify:N,array:p,json:x,file:W1}),R0;function e(z0,j0){return new pW(z0,j0)}function R0(z0,...j0){return z0&&Array.isArray(z0.raw)?new zW(z0,j0,k,Z):typeof z0==="string"&&!j0.length?new Z6(Y.transform.column.to?Y.transform.column.to(z0):z0):new PX(z0,j0)}function m0(z0,j0=[],r0={}){return arguments.length===2&&!Array.isArray(j0)&&(r0=j0,j0=[]),new zW([z0],j0,k,Z,{prepare:!1,...r0,simple:"simple"in r0?r0.simple:j0.length===0})}function W1(z0,j0=[],r0={}){return arguments.length===2&&!Array.isArray(j0)&&(r0=j0,j0=[]),new zW([],j0,(v0)=>{gO.readFile(z0,"utf8",(O1,I0)=>{if(O1)return v0.reject(O1);v0.strings=[I0],k(v0)})},Z,{...r0,simple:"simple"in r0?r0.simple:j0.length===0})}}async function j(k,e,R0){let m0={fn:e,onlisten:R0},W1=j.sql||(j.sql=hX({...Y,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))}})),z0=j.channels||(j.channels={});if(k in z0){z0[k].listeners.push(m0);let v0=await z0[k].result;return m0.onlisten&&m0.onlisten(),{state:v0.state,unlisten:u0}}z0[k]={result:W1`listen ${W1.unsafe('"'+k.replace(/"/g,'""')+'"')}`,listeners:[m0]};let r0=await z0[k].result;return m0.onlisten&&m0.onlisten(),{state:r0.state,unlisten:u0};async function u0(){if(k in z0===!1)return;if(z0[k].listeners=z0[k].listeners.filter((v0)=>v0!==m0),z0[k].listeners.length)return;return delete z0[k],W1`unlisten ${W1.unsafe('"'+k.replace(/"/g,'""')+'"')}`}}async function N(k,e){return await E`select pg_notify(${k}, ${""+e})`}async function B(){let k=$W(),e=z.length?z.shift():await new Promise((W1)=>{J.push({reserve:W1}),Q.length&&e0(Q.shift())});g(e,T),e.reserved=()=>k.length?e.execute(k.shift()):g(e,T),e.reserved.release=!0;let R0=I(m0);return R0.release=()=>{e.reserved=null,MW(e)},R0;function m0(W1){e.queue===w?k.push(W1):e.execute(W1)||g(e,w)}}async function P(k,e){!e&&(e=k,k="");let R0=$W(),m0=0,W1,z0=null;try{return await E.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=K$,I0.prepare=(y0)=>z0=y0.replace(/[^a-z0-9$-_. ]/gi);let VW,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)}),VW)throw VW}catch(y0){throw await(O1?I0`rollback to ${I0(O1)}`:I0`rollback`),y0 instanceof A8&&y0.code==="25P02"&&VW||y0}if(!O1)z0?await I0`prepare transaction '${I0.unsafe(z0)}'`:await I0`commit`;return K1;function K$(y0,OW){if(y0&&Array.isArray(y0.raw))return K$((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)=>VW||(VW=OW)),u0.queue===w?R0.push(y0):u0.execute(y0)||g(u0,w)}}function r0(u0){W1=u0,g(u0,T),u0.reserved=()=>R0.length?u0.execute(R0.shift()):g(u0,T)}}function g(k,e){return k.queue.remove(k),e.push(k),k.queue=e,e===z?k.idleTimer.start():k.idleTimer.cancel(),k}function x(k){return new pW(k,3802)}function p(k,e){if(!Array.isArray(k))return p(Array.from(arguments));return new pW(k,e||(k.length?jX(k)||25:0),Y.shared.typeArrayMap)}function w0(k){if(G)return k.reject(a0.connection("CONNECTION_ENDED",Y,Y));if(z.length)return p0(z.shift(),k);if(Q.length)return e0(Q.shift(),k);F.length?p0(F.shift(),k):J.push(k)}function p0(k,e){return k.execute(e)?g(k,F):g(k,w)}function Z(k){return new Promise((e,R0)=>{k.state?k.active?K7(Y).cancel(k.state,e,R0):k.cancelled={resolve:e,reject:R0}:(J.remove(k),k.cancelled=!0,k.reject(a0.generic("57014","canceling statement due to user request")),e())})}async function M0({timeout:k=null}={}){if(G)return G;await 1;let e;return G=Promise.race([new Promise((R0)=>k!==null&&(e=setTimeout(U0,k*1000,R0))),Promise.all(V.map((R0)=>R0.end()).concat(j.sql?j.sql.end({timeout:0}):[],X.sql?X.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(e))}async function Y0(){await Promise.all(V.map((k)=>k.end()))}async function U0(k){await Promise.all(V.map((e)=>e.terminate()));while(J.length)J.shift().reject(a0.connection("CONNECTION_DESTROYED",Y));k()}function e0(k,e){return g(k,H),k.connect(e),k}function V1(k){g(k,_)}function MW(k){if(J.length===0)return g(k,z);let e=Math.ceil(J.length/(H.length+1)),R0=!0;while(R0&&J.length&&e-- >0){let m0=J.shift();if(m0.reserve)return m0.reserve(k);R0=k.execute(m0)}R0?g(k,F):g(k,w)}function b2(k,e){g(k,Q),k.reserved=null,k.onclose&&(k.onclose(e),k.onclose=null),Y.onclose&&Y.onclose(k.id),J.length&&e0(k,J.shift())}}function mO(W,$){if(W&&W.shared)return W;let Y=process.env,X=(!W||typeof W==="string"?$:W)||{},{url:G,multihost:J}=lO(W),H=[...G.searchParams].reduce((w,[O,V])=>(w[O]=V,w),{}),T=X.hostname||X.host||J||G.hostname||Y.PGHOST||"localhost",Q=X.port||G.port||Y.PGPORT||5432,_=X.user||X.username||G.username||Y.PGUSERNAME||Y.PGUSER||oO();X.no_prepare&&(X.prepare=!1),H.sslmode&&(H.ssl=H.sslmode,delete H.sslmode),"timeout"in X&&(console.log("The timeout option is deprecated, use idle_timeout instead"),X.idle_timeout=X.timeout),H.sslrootcert==="system"&&(H.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],F={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:cO,max_pipeline:100,backoff:uO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(T)?T:T.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(Q)?Q:T.split(",").map((w)=>parseInt(w.split(":")[1]||Q)),path:X.path||T.indexOf("/")>-1&&T+"/.s.PGSQL."+Q,database:X.database||X.db||(G.pathname||"").slice(1)||Y.PGDATABASE||_,user:_,pass:X.pass||X.password||G.password||Y.PGPASSWORD||"",...Object.entries(F).reduce((w,[O,V])=>{let E=O in X?X[O]:(O in H)?H[O]==="disable"||H[O]==="false"?!1:H[O]:Y["PG"+O.toUpperCase()]||V;return w[O]=typeof E==="string"&&z.includes(O)?+E:E,w},{}),connection:{application_name:"postgres.js",...X.connection,...Object.entries(H).reduce((w,[O,V])=>((O in F)||(w[O]=V),w),{})},types:X.types||{},target_session_attrs:pO(X,G,Y),onnotice:X.onnotice,onnotify:X.onnotify,onclose:X.onclose,onparameter:X.onparameter,socket:X.socket,transform:dO(X.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...r_(X.types)}}function pO(W,$,Y){let X=W.target_session_attrs||$.searchParams.get("target_session_attrs")||Y.PGTARGETSESSIONATTRS;if(!X||["read-write","read-only","primary","standby","prefer-standby"].includes(X))return X;throw new Error("target_session_attrs "+X+" is not supported")}function uO(W){return(0.5+Math.random()/2)*Math.min(3**W/100,20)}function cO(){return 60*(30+Math.random()*30)}function dO(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 lO(W){if(!W||typeof W!=="string")return{url:{searchParams:new Map}};let $=W;$=$.slice($.indexOf("://")+3).split(/[?/]/)[0],$=decodeURIComponent($.slice($.indexOf("@")+1));let Y=new URL(W.replace($,$.split(",")[0]));return{url:{username:decodeURIComponent(Y.username),password:decodeURIComponent(Y.password),host:Y.host,hostname:Y.hostname,port:Y.port,pathname:Y.pathname,searchParams:Y.searchParams},multihost:$.indexOf(",")>-1&&$}}function oO(){try{return hO.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 X=(L(W,H1)?W._.selectedFields:L(W,g1)?W[f0].selectedFields:W)[$];if(L(X,u.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!X.isSelectionField)return X.sql;let G=X.clone();return G.isSelectionField=!0,G}if(L(X,u)){if(this.config.sqlBehavior==="sql")return X;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(X,q0)){if(this.config.alias)return new Proxy(X,new K8(new Proxy(X.table,new F6(this.config.alias,this.config.replaceOriginalName??!1))));return X}if(typeof X!=="object"||X===null)return X;return new Proxy(X,new n0(this.config))}}class gX extends I1{constructor(W,$,Y,X){super();this.session=$,this.dialect=Y,this.config={table:W,withList:X}}static[D]="PgDelete";config;where(W){return this.config.where=W,this}returning(W=this.config.table[m.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 iO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Y)=>Y.toLowerCase()).join("_")}function nO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((Y,X,G)=>{let J=G===0?X.toLowerCase():`${X[0].toUpperCase()}${X.slice(1)}`;return Y+J},"")}function rO(W){return W}class L7{static[D]="CasingCache";cache={};cachedTables={};convert;constructor(W){this.convert=W==="snake_case"?iO:W==="camelCase"?nO:rO}getColumnCasing(W){if(!W.keyAsName)return W.name;let $=W.table[m.Symbol.Schema]??"public",Y=W.table[m.Symbol.OriginalName],X=`${$}.${Y}.${W.name}`;if(!this.cache[X])this.cacheTable(W.table);return this.cache[X]}cacheTable(W){let $=W[m.Symbol.Schema]??"public",Y=W[m.Symbol.OriginalName],X=`${$}.${Y}`;if(!this.cachedTables[X]){for(let G of Object.values(W[m.Symbol.Columns])){let J=`${X}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[X]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class R6 extends g1{static[D]="PgViewBase"}class S2{static[D]="PgDialect";casing;constructor(W){this.casing=new L7(W?.casing)}async migrate(W,$,Y){let X=typeof Y==="string"?"__drizzle_migrations":Y.migrationsTable??"__drizzle_migrations",G=typeof Y==="string"?"drizzle":Y.migrationsSchema??"drizzle",J=M`
|
|
78
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
101
|
+
`};return X(z),new Promise(async(_)=>G=_);async function w({highWaterMark:_=16384,start:F=0,end:D=1/0}={}){let V=D-F;return F&&await z.seek(F),new cO.Readable({highWaterMark:_,async read(E){let R=E>V?E-V:E;V-=E;let[{data:P}]=await z.read(R);if(this.push(P),P.length<E)this.push(null)}})}async function H({highWaterMark:_=16384,start:F=0}={}){return F&&await z.seek(F),new cO.Writable({highWaterMark:_,write(D,V,E){z.write(D).then(()=>E(),E)}})}}).catch(Y)})}Object.assign(WU,{PostgresError:kT,toPascal:k0,pascal:f7,toCamel:I0,camel:b7,toKebab:q0,kebab:y7,fromPascal:n2,fromCamel:i2,fromKebab:t2,BigInt:{to:20,from:[20],parse:($)=>BigInt($),serialize:($)=>$.toString()}});var PT=WU;function WU($,T){let W=Ck($,T),X=W.no_subscribe||u7(WU,{...W}),Y=!1,U=W6(),G=W6(),J=W6(),z=W6(),w=W6(),H=W6(),_=W6(),F=W6(),D={connecting:G,reserved:J,closed:z,ended:w,open:H,busy:_,full:F},V=[...Array(W.max)].map(()=>c7(W,D,{onopen:D6,onend:V4,onclose:g0})),E=R(J$);return Object.assign(E,{get parameters(){return W.parameters},largeObject:p7.bind(null,E),subscribe:X,CLOSE:IT,END:IT,PostgresError:kT,options:W,reserve:N,listen:P,begin:k,close:$$,end:Z$}),E;function R(v){return v.debug=W.debug,Object.entries(W.types).reduce((w$,[A$,i$])=>{return w$[A$]=(c$)=>new h6(c$,i$.to),w$},e),Object.assign(M$,{types:e,typed:e,unsafe:g$,notify:A,array:m,json:x,file:$4}),M$;function e(w$,A$){return new h6(w$,A$)}function M$(w$,...A$){return w$&&Array.isArray(w$.raw)?new _6(w$,A$,v,B):typeof w$==="string"&&!A$.length?new a2(W.transform.column.to?W.transform.column.to(w$):w$):new t8(w$,A$)}function g$(w$,A$=[],i$={}){return arguments.length===2&&!Array.isArray(A$)&&(i$=A$,A$=[]),new _6([w$],A$,v,B,{prepare:!1,...i$,simple:"simple"in i$?i$.simple:A$.length===0})}function $4(w$,A$=[],i$={}){return arguments.length===2&&!Array.isArray(A$)&&(i$=A$,A$=[]),new _6([],A$,(x$)=>{Pk.readFile(w$,"utf8",(K4,k$)=>{if(K4)return x$.reject(K4);x$.strings=[k$],v(x$)})},B,{...i$,simple:"simple"in i$?i$.simple:A$.length===0})}}async function P(v,e,M$){let g$={fn:e,onlisten:M$},$4=P.sql||(P.sql=WU({...W,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(P.channels).forEach(([x$,{listeners:K4}])=>{delete P.channels[x$],Promise.all(K4.map((k$)=>P(x$,k$.fn,k$.onlisten).catch(()=>{})))})},onnotify(x$,K4){x$ in P.channels&&P.channels[x$].listeners.forEach((k$)=>k$.fn(K4))}})),w$=P.channels||(P.channels={});if(v in w$){w$[v].listeners.push(g$);let x$=await w$[v].result;return g$.onlisten&&g$.onlisten(),{state:x$.state,unlisten:c$}}w$[v]={result:$4`listen ${$4.unsafe('"'+v.replace(/"/g,'""')+'"')}`,listeners:[g$]};let i$=await w$[v].result;return g$.onlisten&&g$.onlisten(),{state:i$.state,unlisten:c$};async function c$(){if(v in w$===!1)return;if(w$[v].listeners=w$[v].listeners.filter((x$)=>x$!==g$),w$[v].listeners.length)return;return delete w$[v],$4`unlisten ${$4.unsafe('"'+v.replace(/"/g,'""')+'"')}`}}async function A(v,e){return await E`select pg_notify(${v}, ${""+e})`}async function N(){let v=W6(),e=H.length?H.shift():await new Promise(($4,w$)=>{let A$={reserve:$4,reject:w$};U.push(A$),z.length&&e$(z.shift(),A$)});y(e,J),e.reserved=()=>v.length?e.execute(v.shift()):y(e,J),e.reserved.release=!0;let M$=R(g$);return M$.release=()=>{e.reserved=null,D6(e)},M$;function g$($4){e.queue===F?v.push($4):e.execute($4)||y(e,F)}}async function k(v,e){!e&&(e=v,v="");let M$=W6(),g$=0,$4,w$=null;try{return await E.unsafe("begin "+v.replace(/[^a-z ]/ig,""),[],{onexecute:i$}).execute(),await Promise.race([A$($4,e),new Promise((c$,x$)=>$4.onclose=x$)])}catch(c$){throw c$}async function A$(c$,x$,K4){let k$=R(T4);k$.savepoint=K1,k$.prepare=(b$)=>w$=b$.replace(/[^a-z0-9$-_. ]/gi);let O6,Q4;K4&&await k$`savepoint ${k$(K4)}`;try{if(Q4=await new Promise((b$,V6)=>{let k6=x$(k$);Promise.resolve(Array.isArray(k6)?Promise.all(k6):k6).then(b$,V6)}),O6)throw O6}catch(b$){throw await(K4?k$`rollback to ${k$(K4)}`:k$`rollback`),b$ instanceof kT&&b$.code==="25P02"&&O6||b$}if(!K4)w$?await k$`prepare transaction '${k$.unsafe(w$)}'`:await k$`commit`;return Q4;function K1(b$,V6){if(b$&&Array.isArray(b$.raw))return K1((k6)=>k6.apply(k6,arguments));return arguments.length===1&&(V6=b$,b$=null),A$(c$,V6,"s"+g$+++(b$?"_"+b$:""))}function T4(b$){b$.catch((V6)=>O6||(O6=V6)),c$.queue===F?M$.push(b$):c$.execute(b$)||y(c$,F)}}function i$(c$){$4=c$,y(c$,J),c$.reserved=()=>M$.length?c$.execute(M$.shift()):y(c$,J)}}function y(v,e){return v.queue.remove(v),e.push(v),v.queue=e,e===H?v.idleTimer.start():v.idleTimer.cancel(),v}function x(v){return new h6(v,3802)}function m(v,e){if(!Array.isArray(v))return m(Array.from(arguments));return new h6(v,e||(v.length?i8(v)||25:0),W.shared.typeArrayMap)}function J$(v){if(Y)return v.reject(a$.connection("CONNECTION_ENDED",W,W));if(H.length)return m$(H.shift(),v);if(z.length)return e$(z.shift(),v);_.length?m$(_.shift(),v):U.push(v)}function m$(v,e){return v.execute(e)?y(v,_):y(v,F)}function B(v){return new Promise((e,M$)=>{v.state?v.active?c7(W).cancel(v.state,e,M$):v.cancelled={resolve:e,reject:M$}:(U.remove(v),v.cancelled=!0,v.reject(a$.generic("57014","canceling statement due to user request")),e())})}async function Z$({timeout:v=null}={}){if(Y)return Y;await 1;let e;return Y=Promise.race([new Promise((M$)=>v!==null&&(e=setTimeout(H$,v*1000,M$))),Promise.all(V.map((M$)=>M$.end()).concat(P.sql?P.sql.end({timeout:0}):[],X.sql?X.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(e))}async function $$(){await Promise.all(V.map((v)=>v.end()))}async function H$(v){await Promise.all(V.map((e)=>e.terminate()));while(U.length)U.shift().reject(a$.connection("CONNECTION_DESTROYED",W));v()}function e$(v,e){return y(v,G),v.connect(e),v}function V4(v){y(v,w)}function D6(v){if(U.length===0)return y(v,H);let e=Math.ceil(U.length/(G.length+1)),M$=!0;while(M$&&U.length&&e-- >0){let g$=U.shift();if(g$.reserve)return g$.reserve(v);M$=v.execute(g$)}M$?y(v,_):y(v,F)}function g0(v,e){y(v,z),v.reserved=null,v.onclose&&(v.onclose(e),v.onclose=null),W.onclose&&W.onclose(v.id),U.length&&e$(v,U.shift())}}function Ck($,T){if($&&$.shared)return $;let W=process.env,X=(!$||typeof $==="string"?T:$)||{},{url:Y,multihost:U}=fk($),G=[...Y.searchParams].reduce((F,[D,V])=>(F[D]=V,F),{}),J=X.hostname||X.host||U||Y.hostname||W.PGHOST||"localhost",z=X.port||Y.port||W.PGPORT||5432,w=X.user||X.username||Y.username||W.PGUSERNAME||W.PGUSER||yk();X.no_prepare&&(X.prepare=!1),G.sslmode&&(G.ssl=G.sslmode,delete G.sslmode),"timeout"in X&&(console.log("The timeout option is deprecated, use idle_timeout instead"),X.idle_timeout=X.timeout),G.sslrootcert==="system"&&(G.ssl="verify-full");let H=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],_={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:xk,max_pipeline:100,backoff:jk,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(J)?J:J.split(",").map((F)=>F.split(":")[0]),port:Array.isArray(z)?z:J.split(",").map((F)=>parseInt(F.split(":")[1]||z)),path:X.path||J.indexOf("/")>-1&&J+"/.s.PGSQL."+z,database:X.database||X.db||(Y.pathname||"").slice(1)||W.PGDATABASE||w,user:w,pass:X.pass||X.password||Y.password||W.PGPASSWORD||"",...Object.entries(_).reduce((F,[D,V])=>{let E=D in X?X[D]:(D in G)?G[D]==="disable"||G[D]==="false"?!1:G[D]:W["PG"+D.toUpperCase()]||V;return F[D]=typeof E==="string"&&H.includes(D)?+E:E,F},{}),connection:{application_name:W.PGAPPNAME||"postgres.js",...X.connection,...Object.entries(G).reduce((F,[D,V])=>((D in _)||(F[D]=V),F),{})},types:X.types||{},target_session_attrs:vk(X,Y,W),onnotice:X.onnotice,onnotify:X.onnotify,onclose:X.onclose,onparameter:X.onparameter,socket:X.socket,transform:bk(X.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...PO(X.types)}}function vk($,T,W){let X=$.target_session_attrs||T.searchParams.get("target_session_attrs")||W.PGTARGETSESSIONATTRS;if(!X||["read-write","read-only","primary","standby","prefer-standby"].includes(X))return X;throw new Error("target_session_attrs "+X+" is not supported")}function jk($){return(0.5+Math.random()/2)*Math.min(3**$/100,20)}function xk(){return 60*(30+Math.random()*30)}function bk($){return{undefined:$.undefined,column:{from:typeof $.column==="function"?$.column:$.column&&$.column.from,to:$.column&&$.column.to},value:{from:typeof $.value==="function"?$.value:$.value&&$.value.from,to:$.value&&$.value.to},row:{from:typeof $.row==="function"?$.row:$.row&&$.row.from,to:$.row&&$.row.to}}}function fk($){if(!$||typeof $!=="string")return{url:{searchParams:new Map}};let T=$;T=T.slice(T.indexOf("://")+3).split(/[?/]/)[0],T=decodeURIComponent(T.slice(T.indexOf("@")+1));let W=new URL($.replace(T,T.split(",")[0]));return{url:{username:decodeURIComponent(W.username),password:decodeURIComponent(W.password),host:W.host,hostname:W.hostname,port:W.port,pathname:W.pathname,searchParams:W.searchParams},multihost:T.indexOf(",")>-1&&T}}function yk(){try{return qk.userInfo().username}catch($){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class r${static[Z]="SelectionProxyHandler";config;constructor($){this.config={...$}}get($,T){if(T==="_")return{...$._,selectedFields:new Proxy($._.selectedFields,this)};if(T===C$)return{...$[C$],selectedFields:new Proxy($[C$].selectedFields,this)};if(typeof T==="symbol")return $[T];let X=(S($,G4)?$._.selectedFields:S($,g4)?$[C$].selectedFields:$)[T];if(S(X,p.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!X.isSelectionField)return X.sql;let Y=X.clone();return Y.isSelectionField=!0,Y}if(S(X,p)){if(this.config.sqlBehavior==="sql")return X;throw new Error(`You tried to reference "${T}" 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(S(X,B$)){if(this.config.alias)return new Proxy(X,new RT(new Proxy(X.table,new m2(this.config.alias,this.config.replaceOriginalName??!1))));return X}if(typeof X!=="object"||X===null)return X;return new Proxy(X,new r$(this.config))}}class XU extends k4{constructor($,T,W,X){super();this.session=T,this.dialect=W,this.config={table:$,withList:X}}static[Z]="PgDelete";config;where($){return this.config.where=$,this}returning($=this.config.table[c.Symbol.Columns]){return this.config.returningFields=$,this.config.returning=w6($),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:$,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare($){return R$.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,$,!0)})}prepare($){return this._prepare($)}authToken;setToken($){return this.authToken=$,this}execute=($)=>{return R$.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute($,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new r$({alias:F4(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function hk($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((W)=>W.toLowerCase()).join("_")}function gk($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((W,X,Y)=>{let U=Y===0?X.toLowerCase():`${X[0].toUpperCase()}${X.slice(1)}`;return W+U},"")}function mk($){return $}class d7{static[Z]="CasingCache";cache={};cachedTables={};convert;constructor($){this.convert=$==="snake_case"?hk:$==="camelCase"?gk:mk}getColumnCasing($){if(!$.keyAsName)return $.name;let T=$.table[c.Symbol.Schema]??"public",W=$.table[c.Symbol.OriginalName],X=`${T}.${W}.${$.name}`;if(!this.cache[X])this.cacheTable($.table);return this.cache[X]}cacheTable($){let T=$[c.Symbol.Schema]??"public",W=$[c.Symbol.OriginalName],X=`${T}.${W}`;if(!this.cachedTables[X]){for(let Y of Object.values($[c.Symbol.Columns])){let U=`${X}.${Y.name}`;this.cache[U]=this.convert(Y.name)}this.cachedTables[X]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class e2 extends g4{static[Z]="PgViewBase"}class C0{static[Z]="PgDialect";casing;constructor($){this.casing=new d7($?.casing)}async migrate($,T,W){let X=typeof W==="string"?"__drizzle_migrations":W.migrationsTable??"__drizzle_migrations",Y=typeof W==="string"?"drizzle":W.migrationsSchema??"drizzle",U=O`
|
|
102
|
+
CREATE TABLE IF NOT EXISTS ${O.identifier(Y)}.${O.identifier(X)} (
|
|
79
103
|
id SERIAL PRIMARY KEY,
|
|
80
104
|
hash text NOT NULL,
|
|
81
105
|
created_at bigint
|
|
82
106
|
)
|
|
83
|
-
`;await $.execute(M`CREATE SCHEMA IF NOT EXISTS ${M.identifier(G)}`),await $.execute(J);let T=(await $.all(M`select id, hash, created_at from ${M.identifier(G)}.${M.identifier(X)} order by created_at desc limit 1`))[0];await $.transaction(async(Q)=>{for await(let _ of W)if(!T||Number(T.created_at)<_.folderMillis){for(let z of _.sql)await Q.execute(M.raw(z));await Q.execute(M`insert into ${M.identifier(G)}.${M.identifier(X)} ("hash", "created_at") values(${_.hash}, ${_.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[Y,X]of W.entries())if($.push(M`${M.identifier(X._.alias)} as (${X._.sql})`),Y<W.length-1)$.push(M`, `);return $.push(M` `),M.join($)}buildDeleteQuery({table:W,where:$,returning:Y,withList:X}){let G=this.buildWithCTE(X),J=Y?M` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,H=$?M` where ${$}`:void 0;return M`${G}delete from ${W}${H}${J}`}buildUpdateSet(W,$){let Y=W[m.Symbol.Columns],X=Object.keys(Y).filter((J)=>$[J]!==void 0||Y[J]?.onUpdateFn!==void 0),G=X.length;return M.join(X.flatMap((J,H)=>{let T=Y[J],Q=$[J]??M.param(T.onUpdateFn(),T),_=M`${M.identifier(this.casing.getColumnCasing(T))} = ${Q}`;if(H<G-1)return[_,M.raw(", ")];return[_]}))}buildUpdateQuery({table:W,set:$,where:Y,returning:X,withList:G,from:J,joins:H}){let T=this.buildWithCTE(G),Q=W[M1.Symbol.Name],_=W[M1.Symbol.Schema],z=W[M1.Symbol.OriginalName],F=Q===z?void 0:Q,w=M`${_?M`${M.identifier(_)}.`:void 0}${M.identifier(z)}${F&&M` ${M.identifier(F)}`}`,O=this.buildUpdateSet(W,$),V=J&&M.join([M.raw(" from "),this.buildFromTable(J)]),E=this.buildJoins(H),I=X?M` returning ${this.buildSelection(X,{isSingleTable:!J})}`:void 0,j=Y?M` where ${Y}`:void 0;return M`${T}update ${w} set ${O}${V}${E}${j}${I}`}buildSelection(W,{isSingleTable:$=!1}={}){let Y=W.length,X=W.flatMap(({field:G},J)=>{let H=[];if(L(G,u.Aliased)&&G.isSelectionField)H.push(M.identifier(G.fieldAlias));else if(L(G,u.Aliased)||L(G,u)){let T=L(G,u.Aliased)?G.sql:G;if($)H.push(new u(T.queryChunks.map((Q)=>{if(L(Q,b))return M.identifier(this.casing.getColumnCasing(Q));return Q})));else H.push(T);if(L(G,u.Aliased))H.push(M` as ${M.identifier(G.fieldAlias)}`)}else if(L(G,q0))if($)H.push(M.identifier(this.casing.getColumnCasing(G)));else H.push(G);if(J<Y-1)H.push(M`, `);return H});return M.join(X)}buildJoins(W){if(!W||W.length===0)return;let $=[];for(let[Y,X]of W.entries()){if(Y===0)$.push(M` `);let G=X.table,J=X.lateral?M` lateral`:void 0,H=X.on?M` on ${X.on}`:void 0;if(L(G,M1)){let T=G[M1.Symbol.Name],Q=G[M1.Symbol.Schema],_=G[M1.Symbol.OriginalName],z=T===_?void 0:X.alias;$.push(M`${M.raw(X.joinType)} join${J} ${Q?M`${M.identifier(Q)}.`:void 0}${M.identifier(_)}${z&&M` ${M.identifier(z)}`}${H}`)}else if(L(G,g1)){let T=G[f0].name,Q=G[f0].schema,_=G[f0].originalName,z=T===_?void 0:X.alias;$.push(M`${M.raw(X.joinType)} join${J} ${Q?M`${M.identifier(Q)}.`:void 0}${M.identifier(_)}${z&&M` ${M.identifier(z)}`}${H}`)}else $.push(M`${M.raw(X.joinType)} join${J} ${G}${H}`);if(Y<W.length-1)$.push(M` `)}return M.join($)}buildFromTable(W){if(L(W,m)&&W[m.Symbol.IsAlias]){let $=M`${M.identifier(W[m.Symbol.OriginalName])}`;if(W[m.Symbol.Schema])$=M`${M.identifier(W[m.Symbol.Schema])}.${$}`;return M`${$} ${M.identifier(W[m.Symbol.Name])}`}return W}buildSelectQuery({withList:W,fields:$,fieldsFlat:Y,where:X,having:G,table:J,joins:H,orderBy:T,groupBy:Q,limit:_,offset:z,lockingClause:F,distinct:w,setOperators:O}){let V=Y??QW($);for(let U0 of V)if(L(U0.field,q0)&&w1(U0.field.table)!==(L(J,H1)?J._.alias:L(J,R6)?J[f0].name:L(J,u)?void 0:w1(J))&&!((e0)=>H?.some(({alias:V1})=>V1===(e0[m.Symbol.IsAlias]?w1(e0):e0[m.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 E=!H||H.length===0,I=this.buildWithCTE(W),j;if(w)j=w===!0?M` distinct`:M` distinct on (${M.join(w.on,M`, `)})`;let N=this.buildSelection(V,{isSingleTable:E}),B=this.buildFromTable(J),P=this.buildJoins(H),g=X?M` where ${X}`:void 0,x=G?M` having ${G}`:void 0,p;if(T&&T.length>0)p=M` order by ${M.join(T,M`, `)}`;let w0;if(Q&&Q.length>0)w0=M` group by ${M.join(Q,M`, `)}`;let p0=typeof _==="object"||typeof _==="number"&&_>=0?M` limit ${_}`:void 0,Z=z?M` offset ${z}`:void 0,M0=M.empty();if(F){let U0=M` for ${M.raw(F.strength)}`;if(F.config.of)U0.append(M` of ${M.join(Array.isArray(F.config.of)?F.config.of:[F.config.of],M`, `)}`);if(F.config.noWait)U0.append(M` nowait`);else if(F.config.skipLocked)U0.append(M` skip locked`);M0.append(U0)}let Y0=M`${I}select${j} ${N} from ${B}${P}${g}${w0}${x}${p}${p0}${Z}${M0}`;if(O.length>0)return this.buildSetOperations(Y0,O);return Y0}buildSetOperations(W,$){let[Y,...X]=$;if(!Y)throw new Error("Cannot pass undefined values to any set operator");if(X.length===0)return this.buildSetOperationQuery({leftSelect:W,setOperator:Y});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:W,setOperator:Y}),X)}buildSetOperationQuery({leftSelect:W,setOperator:{type:$,isAll:Y,rightSelect:X,limit:G,orderBy:J,offset:H}}){let T=M`(${W.getSQL()}) `,Q=M`(${X.getSQL()})`,_;if(J&&J.length>0){let O=[];for(let V of J)if(L(V,b))O.push(M.identifier(V.name));else if(L(V,u)){for(let E=0;E<V.queryChunks.length;E++){let I=V.queryChunks[E];if(L(I,b))V.queryChunks[E]=M.identifier(I.name)}O.push(M`${V}`)}else O.push(M`${V}`);_=M` order by ${M.join(O,M`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?M` limit ${G}`:void 0,F=M.raw(`${$} ${Y?"all ":""}`),w=H?M` offset ${H}`:void 0;return M`${T}${F}${Q}${_}${z}${w}`}buildInsertQuery({table:W,values:$,onConflict:Y,returning:X,withList:G,select:J,overridingSystemValue_:H}){let T=[],Q=W[m.Symbol.Columns],_=Object.entries(Q).filter(([I,j])=>!j.shouldDisableInsert()),z=_.map(([,I])=>M.identifier(this.casing.getColumnCasing(I)));if(J){let I=$;if(L(I,u))T.push(I);else T.push(I.getSQL())}else{let I=$;T.push(M.raw("values "));for(let[j,N]of I.entries()){let B=[];for(let[P,g]of _){let x=N[P];if(x===void 0||L(x,WW)&&x.value===void 0)if(g.defaultFn!==void 0){let p=g.defaultFn(),w0=L(p,u)?p:M.param(p,g);B.push(w0)}else if(!g.default&&g.onUpdateFn!==void 0){let p=g.onUpdateFn(),w0=L(p,u)?p:M.param(p,g);B.push(w0)}else B.push(M`default`);else B.push(x)}if(T.push(B),j<I.length-1)T.push(M`, `)}}let F=this.buildWithCTE(G),w=M.join(T),O=X?M` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,V=Y?M` on conflict ${Y}`:void 0,E=H===!0?M`overriding system value `:void 0;return M`${F}insert into ${W} ${z} ${E}${w}${V}${O}`}buildRefreshMaterializedViewQuery({view:W,concurrently:$,withNoData:Y}){let X=$?M` concurrently`:void 0,G=Y?M` with no data`:void 0;return M`refresh materialized view${X} ${W}${G}`}prepareTyping(W){if(L(W,EX)||L(W,KX))return"json";else if(L(W,AX))return"decimal";else if(L(W,LX))return"time";else if(L(W,ZX)||L(W,NX))return"timestamp";else if(L(W,VX)||L(W,OX))return"date";else if(L(W,RX))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:Y,table:X,tableConfig:G,queryConfig:J,tableAlias:H,nestedQueryRelation:T,joinOn:Q}){let _=[],z,F,w=[],O,V=[];if(J===!0)_=Object.entries(G.columns).map(([j,N])=>({dbKey:N.name,tsKey:j,field:mW(N,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(G.columns).map(([x,p])=>[x,mW(p,H)]));if(J.where){let x=typeof J.where==="function"?J.where(I,v_()):J.where;O=x&&w6(x,H)}let j=[],N=[];if(J.columns){let x=!1;for(let[p,w0]of Object.entries(J.columns)){if(w0===void 0)continue;if(p in G.columns){if(!x&&w0===!0)x=!0;N.push(p)}}if(N.length>0)N=x?N.filter((p)=>J.columns?.[p]===!0):Object.keys(G.columns).filter((p)=>!N.includes(p))}else N=Object.keys(G.columns);for(let x of N){let p=G.columns[x];j.push({tsKey:x,value:p})}let B=[];if(J.with)B=Object.entries(J.with).filter((x)=>!!x[1]).map(([x,p])=>({tsKey:x,queryConfig:p,relation:G.relations[x]}));let P;if(J.extras){P=typeof J.extras==="function"?J.extras(I,{sql:M}):J.extras;for(let[x,p]of Object.entries(P))j.push({tsKey:x,value:t5(p,H)})}for(let{tsKey:x,value:p}of j)_.push({dbKey:L(p,u.Aliased)?p.fieldAlias:G.columns[x].name,tsKey:x,field:L(p,q0)?mW(p,H):p,relationTableTsKey:void 0,isJson:!1,selection:[]});let g=typeof J.orderBy==="function"?J.orderBy(I,y_()):J.orderBy??[];if(!Array.isArray(g))g=[g];w=g.map((x)=>{if(L(x,q0))return mW(x,H);return w6(x,H)}),z=J.limit,F=J.offset;for(let{tsKey:x,queryConfig:p,relation:w0}of B){let p0=g_($,Y,w0),Z=L2(w0.referencedTable),M0=Y[Z],Y0=`${H}_${x}`,U0=O6(...p0.fields.map((MW,b2)=>BX(mW(p0.references[b2],Y0),mW(MW,H)))),e0=this.buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:Y,table:W[M0],tableConfig:$[M0],queryConfig:L(w0,h$)?p===!0?{limit:1}:{...p,limit:1}:p,tableAlias:Y0,joinOn:U0,nestedQueryRelation:w0}),V1=M`${M.identifier(Y0)}.${M.identifier("data")}`.as(x);V.push({on:M`true`,table:new H1(e0.sql,{},Y0),alias:Y0,joinType:"left",lateral:!0}),_.push({dbKey:x,tsKey:x,field:V1,relationTableTsKey:M0,isJson:!0,selection:e0.selection})}}if(_.length===0)throw new DX({message:`No fields selected for table "${G.tsName}" ("${H}")`});let E;if(O=O6(Q,O),T){let I=M`json_build_array(${M.join(_.map(({field:B,tsKey:P,isJson:g})=>g?M`${M.identifier(`${H}_${P}`)}.${M.identifier("data")}`:L(B,u.Aliased)?B.sql:B),M`, `)})`;if(L(T,K6))I=M`coalesce(json_agg(${I}${w.length>0?M` order by ${M.join(w,M`, `)}`:void 0}), '[]'::json)`;let j=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:_}];if(z!==void 0||F!==void 0||w.length>0)E=this.buildSelectQuery({table:UX(X,H),fields:{},fieldsFlat:[{path:[],field:M.raw("*")}],where:O,limit:z,offset:F,orderBy:w,setOperators:[]}),O=void 0,z=void 0,F=void 0,w=[];else E=UX(X,H);E=this.buildSelectQuery({table:L(E,M1)?E:new H1(E,{},H),fields:{},fieldsFlat:j.map(({field:B})=>({path:[],field:L(B,q0)?mW(B,H):B})),joins:V,where:O,limit:z,offset:F,orderBy:w,setOperators:[]})}else E=this.buildSelectQuery({table:UX(X,H),fields:{},fieldsFlat:_.map(({field:I})=>({path:[],field:L(I,q0)?mW(I,H):I})),joins:V,where:O,limit:z,offset:F,orderBy:w,setOperators:[]});return{tableTsKey:G.tsName,sql:E,selection:_}}}class Z7{static[D]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class f1{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,Y=W,X;if(this.fields)X=this.fields;else if(L(Y,H1))X=Object.fromEntries(Object.keys(Y._.selectedFields).map((G)=>[G,Y[G]]));else if(L(Y,R6))X=Y[f0].selectedFields;else if(L(Y,u))X={};else X=VT(Y);return new N7({table:Y,fields:X,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class Tz extends Z7{static[D]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:W,fields:$,isPartialSelect:Y,session:X,dialect:G,withList:J,distinct:H}){super();this.config={withList:J,table:W,fields:{...$},distinct:H,setOperators:[]},this.isPartialSelect=Y,this.session=X,this.dialect=G,this._={selectedFields:$},this.tableName=J$(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(W,$){return(Y,X)=>{let G=this.tableName,J=J$(Y);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(Y,u)){let H=L(Y,H1)?Y._.selectedFields:L(Y,g1)?Y[f0].selectedFields:Y[m.Symbol.Columns];this.config.fields[J]=H}}if(typeof X==="function")X=X(new Proxy(this.config.fields,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:X,table:Y,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(Y)=>{let X=typeof Y==="function"?Y(tO()):Y;if(!U6(this.getSelectedFields(),X.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:X}),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"}))),Y=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Y;else this.config.orderBy=Y}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 N7 extends Tz{static[D]="PgSelect";_prepare(W){let{session:$,config:Y,dialect:X,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=QW(Y.fields),T=$.prepareQuery(X.sqlToQuery(this.getSQL()),H,W,!0);return T.joinsNotNullableMap=G,T.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)})}}MT(N7,[I1]);function N8(W,$){return(Y,X,...G)=>{let J=[X,...G].map((H)=>({type:W,isAll:$,rightSelect:H}));for(let H of J)if(!U6(Y.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 Y.addSetOperators(J)}}var tO=()=>({union:aO,unionAll:sO,intersect:eO,intersectAll:WK,except:$K,exceptAll:YK}),aO=N8("union",!1),sO=N8("union",!0),eO=N8("intersect",!1),WK=N8("intersect",!0),$K=N8("except",!1),YK=N8("except",!0);class B6{static[D]="PgQueryBuilder";dialect;dialectConfig;constructor(W){this.dialect=L(W,S2)?W:void 0,this.dialectConfig=L(W,S2)?void 0:W}$with=(W,$)=>{let Y=this;return{as:(G)=>{if(typeof G==="function")G=G(Y);return new Proxy(new _6(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),W,!0),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...W){let $=this;function Y(J){return new f1({fields:J??void 0,session:void 0,dialect:$.getDialect(),withList:W})}function X(J){return new f1({fields:J??void 0,session:void 0,dialect:$.getDialect(),distinct:!0})}function G(J,H){return new f1({fields:H??void 0,session:void 0,dialect:$.getDialect(),distinct:{on:J}})}return{select:Y,selectDistinct:X,selectDistinctOn:G}}select(W){return new f1({fields:W??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(W){return new f1({fields:W??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(W,$){return new f1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:W}})}getDialect(){if(!this.dialect)this.dialect=new S2(this.dialectConfig);return this.dialect}}class mX{constructor(W,$,Y,X,G){this.table=W,this.session=$,this.dialect=Y,this.withList=X,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((Y)=>{let X={},G=this.table[m.Symbol.Columns];for(let J of Object.keys(Y)){let H=Y[J];X[J]=L(H,u)?H:new WW(H,G[J])}return X});return new R7(this.table,$,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(W){let $=typeof W==="function"?W(new B6):W;if(!L($,u)&&!U6(this.table[FX],$._.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 R7(this.table,$,this.session,this.dialect,this.withList,!0)}}class R7 extends I1{constructor(W,$,Y,X,G,J,H){super();this.session=Y,this.dialect=X,this.config={table:W,values:$,withList:G,select:J,overridingSystemValue_:H}}static[D]="PgInsert";config;returning(W=this.config.table[m.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((X)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(X))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target));let Y=W.where?M` where ${W.where}`:void 0;this.config.onConflict=M`(${M.raw($)})${Y} 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,Y=W.targetWhere?M` where ${W.targetWhere}`:void 0,X=W.setWhere?M` where ${W.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,MX(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=M`(${M.raw(J)})${Y} do update set ${G}${$}${X}`,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 B7 extends I1{constructor(W,$,Y){super();this.session=$,this.dialect=Y,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 pX{constructor(W,$,Y,X){this.table=W,this.session=$,this.dialect=Y,this.withList=X}static[D]="PgUpdateBuilder";authToken;setToken(W){return this.authToken=W,this}set(W){return new Qz(this.table,MX(this.table,W),this.session,this.dialect,this.withList).setToken(this.authToken)}}class Qz extends I1{constructor(W,$,Y,X,G){super();this.session=Y,this.dialect=X,this.config={set:$,table:W,withList:G,joins:[]},this.tableName=J$(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[D]="PgUpdate";config;tableName;joinsNotNullableMap;from(W){let $=W,Y=J$($);if(typeof Y==="string")this.joinsNotNullableMap[Y]=!0;return this.config.from=$,this}getTableLikeFields(W){if(L(W,M1))return W[m.Symbol.Columns];else if(L(W,H1))return W._.selectedFields;return W[f0].selectedFields}createJoin(W){return($,Y)=>{let X=J$($);if(typeof X==="string"&&this.config.joins.some((G)=>G.alias===X))throw new Error(`Alias "${X}" is already used in this query`);if(typeof Y==="function"){let G=this.config.from&&!L(this.config.from,u)?this.getTableLikeFields(this.config.from):void 0;Y=Y(new Proxy(this.config.table[m.Symbol.Columns],new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new n0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:Y,table:$,joinType:W,alias:X}),typeof X==="string")switch(W){case"left":{this.joinsNotNullableMap[X]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[X]=!0;break}case"inner":{this.joinsNotNullableMap[X]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[X]=!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[m.Symbol.Columns]),this.config.from){let $=J$(this.config.from);if(typeof $==="string"&&this.config.from&&!L(this.config.from,u)){let Y=this.getTableLikeFields(this.config.from);W[$]=Y}for(let Y of this.config.joins){let X=J$(Y.table);if(typeof X==="string"&&!L(Y.table,u)){let G=this.getTableLikeFields(Y.table);W[X]=G}}}}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 S6 extends u{constructor(W){super(S6.buildEmbeddedCount(W.source,W.filters).queryChunks);this.params=W,this.mapWith(Number),this.session=W.session,this.sql=S6.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 q7{constructor(W,$,Y,X,G,J,H){this.fullSchema=W,this.schema=$,this.tableNamesMap=Y,this.table=X,this.tableConfig=G,this.dialect=J,this.session=H}static[D]="PgRelationalQueryBuilder";findMany(W){return new S7(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?W:{},"many")}findFirst(W){return new S7(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?{...W,limit:1}:{limit:1},"first")}}class S7 extends I1{constructor(W,$,Y,X,G,J,H,T,Q){super();this.fullSchema=W,this.schema=$,this.tableNamesMap=Y,this.table=X,this.tableConfig=G,this.dialect=J,this.session=H,this.config=T,this.mode=Q}static[D]="PgRelationalQuery";_prepare(W){return C0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:$,builtQuery:Y}=this._toSQL();return this.session.prepareQuery(Y,void 0,W,!0,(X,G)=>{let J=X.map((H)=>qX(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 C7 extends I1{constructor(W,$,Y,X){super();this.execute=W,this.sql=$,this.query=Y,this.mapBatchResult=X}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 q6{constructor(W,$,Y){if(this.dialect=W,this.session=$,this._=Y?{schema:Y.schema,fullSchema:Y.fullSchema,tableNamesMap:Y.tableNamesMap,session:$}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:$},this.query={},this._.schema)for(let[X,G]of Object.entries(this._.schema))this.query[X]=new q7(Y.fullSchema,this._.schema,this._.tableNamesMap,Y.fullSchema[X],G,W,$)}static[D]="PgDatabase";query;$with=(W,$)=>{let Y=this;return{as:(G)=>{if(typeof G==="function")G=G(new B6(Y.dialect));return new Proxy(new _6(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),W,!0),new n0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(W,$){return new S6({source:W,filters:$,session:this.session})}with(...W){let $=this;function Y(Q){return new f1({fields:Q??void 0,session:$.session,dialect:$.dialect,withList:W})}function X(Q){return new f1({fields:Q??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:!0})}function G(Q,_){return new f1({fields:_??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:{on:Q}})}function J(Q){return new pX(Q,$.session,$.dialect,W)}function H(Q){return new mX(Q,$.session,$.dialect,W)}function T(Q){return new gX(Q,$.session,$.dialect,W)}return{select:Y,selectDistinct:X,selectDistinctOn:G,update:J,insert:H,delete:T}}select(W){return new f1({fields:W??void 0,session:this.session,dialect:this.dialect})}selectDistinct(W){return new f1({fields:W??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(W,$){return new f1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:{on:W}})}update(W){return new pX(W,this.session,this.dialect)}insert(W){return new mX(W,this.session,this.dialect)}delete(W){return new gX(W,this.session,this.dialect)}refreshMaterializedView(W){return new B7(W,this.session,this.dialect)}authToken;execute(W){let $=typeof W==="string"?M.raw(W):W.getSQL(),Y=this.dialect.sqlToQuery($),X=this.session.prepareQuery(Y,void 0,void 0,!1);return new C7(()=>X.execute(void 0,this.authToken),$,Y,(G)=>X.mapResult(G,!0))}transaction(W,$){return this.session.transaction(W,$)}}class _z{constructor(W,$){this.unique=W,this.name=$}static[D]="PgIndexBuilderOn";on(...W){return new uX(W.map(($)=>{if(L($,u))return $;$=$;let Y=new T6($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),Y}),this.unique,!1,this.name)}onOnly(...W){return new uX(W.map(($)=>{if(L($,u))return $;$=$;let Y=new T6($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=$.defaultConfig,Y}),this.unique,!0,this.name)}using(W,...$){return new uX($.map((Y)=>{if(L(Y,u))return Y;Y=Y;let X=new T6(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=JSON.parse(JSON.stringify(Y.defaultConfig)),X}),this.unique,!0,this.name,W)}}class uX{static[D]="PgIndexBuilder";config;constructor(W,$,Y,X,G="btree"){this.config={name:X,columns:W,unique:$,only:Y,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 zz(this.config,W)}}class zz{static[D]="PgIndex";config;constructor(W,$){this.config={...W,table:$}}}function k7(W){return new _z(!0,W)}class j7{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 I7{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 Y=await this.execute(W,$);return Number(Y[0].count)}}class P7 extends q6{constructor(W,$,Y,X=0){super(W,$,Y);this.schema=Y,this.nestedIndex=X}static[D]="PgTransaction";rollback(){throw new a5}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 Fz extends j7{constructor(W,$,Y,X,G,J,H){super({sql:$,params:Y});this.client=W,this.queryString=$,this.params=Y,this.logger=X,this.fields=G,this._isResponseInArrayMode=J,this.customResultMapper=H}static[D]="PostgresJsPreparedQuery";async execute(W={}){return C0.startActiveSpan("drizzle.execute",async($)=>{let Y=r5(this.params,W);$?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Y)}),this.logger.logQuery(this.queryString,Y);let{fields:X,queryString:G,client:J,joinsNotNullableMap:H,customResultMapper:T}=this;if(!X&&!T)return C0.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(G,Y)});let Q=await C0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(Y)}),J.unsafe(G,Y).values()});return C0.startActiveSpan("drizzle.mapResponse",()=>{return T?T(Q):Q.map((_)=>DT(X,_,H))})})}all(W={}){return C0.startActiveSpan("drizzle.execute",async($)=>{let Y=r5(this.params,W);return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Y)}),this.logger.logQuery(this.queryString,Y),C0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(Y)}),this.client.unsafe(this.queryString,Y)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class C6 extends I7{constructor(W,$,Y,X={}){super($);this.client=W,this.schema=Y,this.options=X,this.logger=X.logger??new e5}static[D]="PostgresJsSession";logger;prepareQuery(W,$,Y,X,G){return new Fz(this.client,W.sql,W.params,this.logger,$,X,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(Y)=>{let X=new C6(Y,this.dialect,this.schema,this.options),G=new f7(this.dialect,X,this.schema);if($)await G.setTransaction($);return W(G)})}}class f7 extends P7{constructor(W,$,Y,X=0){super(W,$,Y,X);this.session=$}static[D]="PostgresJsTransaction";transaction(W){return this.session.client.savepoint(($)=>{let Y=new C6($,this.dialect,this.schema,this.session.options),X=new f7(this.dialect,Y,this.schema);return W(X)})}}class wz extends q6{static[D]="PostgresJsDatabase"}function R8(W,$={}){let Y=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])W.options.parsers[Q]=Y,W.options.serializers[Q]=Y;W.options.serializers["114"]=Y,W.options.serializers["3802"]=Y;let X=new S2({casing:$.casing}),G;if($.logger===!0)G=new s5;else if($.logger!==!1)G=$.logger;let J;if($.schema){let Q=h_($.schema,m_);J={fullSchema:$.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let H=new C6(W,X,J,{logger:G}),T=new wz(X,H,J);return T.$client=W,T}function cX(...W){if(typeof W[0]==="string"){let $=Z8(W[0]);return R8($,W[1])}if(OT(W[0])){let{connection:$,client:Y,...X}=W[0];if(Y)return R8(Y,X);if(typeof $==="object"&&$.url!==void 0){let{url:J,...H}=$,T=Z8(J,H);return R8(T,X)}let G=Z8($);return R8(G,X)}return R8(W[0],W[1])}((W)=>{function $(Y){return R8({options:{parsers:{},serializers:{}}},Y)}W.mock=$})(cX||(cX={}));function Uz(W,$){if(W instanceof Promise)throw new Error($)}function XK(W,$){let Y={},X=[];for(let G in W){let J=W[G]["~standard"].validate($[G]);if(Uz(J,`Validation must be synchronous, but ${G} returned a Promise.`),J.issues){X.push(...J.issues.map((H)=>({...H,path:[G,...H.path??[]]})));continue}Y[G]=J.value}if(X.length)return{issues:X};return{value:Y}}function b7(W){let $=W.runtimeEnvStrict??W.runtimeEnv??process.env;if(W.emptyStringAsUndefined??!1){for(let[N,B]of Object.entries($))if(B==="")delete $[N]}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:{},T=W.isServer??(typeof window==="undefined"||("Deno"in window)),Q=T?{...J,...H,...G}:{...G,...H},_=W.createFinalSchema?.(Q,T)["~standard"].validate($)??XK(Q,$);Uz(_,"Validation must be synchronous");let z=W.onValidationError??((N)=>{throw console.error("\u274C Invalid environment variables:",N),new Error("Invalid environment variables")}),F=W.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(_.issues)return z(_.issues);let w=(N)=>{if(!W.clientPrefix)return!0;return!N.startsWith(W.clientPrefix)&&!(N in H)},O=(N)=>{return T||!w(N)},V=(N)=>{return N==="__esModule"||N==="$$typeof"},E=(W.extends??[]).reduce((N,B)=>{return Object.assign(N,B)},{}),I=Object.assign(E,_.value);return new Proxy(I,{get(N,B){if(typeof B!=="string")return;if(V(B))return;if(!O(B))return F(B);return Reflect.get(N,B)}})}var m$=(W)=>Array.isArray(W)?W:[W],Dz=(W,$)=>{let Y=[[],[]];for(let X of W)if($(X))Y[0].push(X);else Y[1].push(X);return Y},dX=Array,T$=(W,$)=>W.includes($),Mz=(W,$=0)=>[...new Array(W)].map((Y,X)=>X+$),D0=(W,$,Y)=>{if(W===void 0)return $===void 0?[]:Array.isArray($)?$:[$];if(Y?.prepend)if(Array.isArray($))W.unshift(...$);else W.unshift($);else if(Array.isArray($))W.push(...$);else W.push($);return W},Q$=(W,$)=>{if($===void 0||$===null)return W??[];if(W===void 0||W===null)return m$($);return W.concat($)},Vz=(...W)=>W.reduce(Q$,[]),uW=(W,$,Y)=>{if(W===void 0)return Array.isArray($)?$:[$];let X=Y?.isEqual??((G,J)=>G===J);for(let G of m$($))if(!W.some((J)=>X(J,G)))W.push(G);return W},Oz=(W,$)=>W.reduce((Y,X)=>{let G=X[$];return Y[G]=D0(Y[G],X),Y},{}),_$=(W,$,Y)=>W.length===$.length&&W.every(Y?.isEqual?(X,G)=>Y.isEqual(X,$[G]):(X,G)=>X===$[G]);var p1=(W,$)=>Q1(W)===$,Q1=(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"},Kz={...u1,function:"a function"};class Ez extends Error{}var E0=(W)=>q2(W,Ez),q2=(W,$=Error)=>{throw new $(W)};class k6 extends Error{name="ParseError"}var A=(W)=>q2(W,k6),SW=(W)=>` ${W}`;var X0=(W,$)=>{let Y={},X=Array.isArray(W),G=!1;for(let[J,H]of Object.entries(W).entries()){let T=X?$(J,H[1]):$(...H,J);G||=typeof T[0]==="number";let Q=Array.isArray(T[0])||T.length===0?T:[T];for(let[_,z]of Q)if(typeof _==="object")Y[_.group]=D0(Y[_.group],z);else Y[_]=z}return G?Object.values(Y):Y};var x7=Object.entries;var _1=(W,$)=>(W in $),B8=(W,$)=>($ in W);class v7{constructor(W){Object.assign(this,W)}}var Az=class{};class j6 extends Az{}var GK=(W,$)=>{let Y={},X={},G;for(G in W)if(G in $)Y[G]=W[G];else X[G]=W[G];return[Y,X]};var Lz=(W,$)=>GK(W,$)[1],cW=(W)=>Object.keys(W).length===0,C2=(W)=>[...Object.entries(W),...Object.getOwnPropertySymbols(W).map(($)=>[$,W[$]])],Zz=(W,$)=>Object.defineProperties(W,Object.getOwnPropertyDescriptors($)),Nz=(W)=>{let $=Object.keys(W).sort(),Y={};for(let X=0;X<$.length;X++)Y[$[X]]=W[$[X]];return Y};var YW=SW("represents an uninitialized value"),Rz=(W)=>Object.values(W).filter(($)=>{if(typeof $==="number")return!0;return typeof W[$]!=="number"});var y7={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},h7=globalThis.File??Blob,g7={ArrayBuffer,Blob,File:h7,FormData,Headers,Request,Response,URL},JK={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},k2={...y7,...g7,...JK,String,Number,Boolean},I6=(W)=>{let $=Object.getPrototypeOf(W);while($?.constructor&&(!_1($.constructor.name,k2)||!(W instanceof k2[$.constructor.name])))$=Object.getPrototypeOf($);let Y=$?.constructor?.name;if(Y===void 0||Y==="Object")return;return Y},P6=(W)=>typeof W==="object"&&W!==null?I6(W)??"object":Q1(W);var k0=Array.isArray,HK={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"},TK={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"},Bz={...HK,...TK,...QK},f6=(W)=>{let $=Object(W).name??null;return $&&_1($,k2)&&k2[$]===W?$:null};var m7=(W,$)=>{let Y=W.prototype;while(Y!==null){if(Y===$.prototype)return!0;Y=Object.getPrototypeOf(Y)}return!1};var Sz=(W)=>qz(W,new Map),qz=(W,$)=>{if(typeof W!=="object"||W===null)return W;if($?.has(W))return $.get(W);let Y=f6(W.constructor);if(Y==="Date")return new Date(W.getTime());if(Y&&Y!=="Array")return W;let X=Array.isArray(W)?W.slice():Object.create(Object.getPrototypeOf(W)),G=Object.getOwnPropertyDescriptors(W);if($){$.set(W,X);for(let J in G){let H=G[J];if("get"in H||"set"in H)continue;H.value=qz(H.value,$)}}return Object.defineProperties(X,G),X};var _K=(W)=>{let $=YW;return()=>$===YW?$=W():$},p$=(W)=>typeof W==="function"&&W.length===0;var Cz=class extends Function{constructor(...W){let $=W.slice(0,-1),Y=W.at(-1);try{super(...$,Y)}catch(X){return E0(`Encountered an unexpected error while compiling your definition:
|
|
107
|
+
`;await T.execute(O`CREATE SCHEMA IF NOT EXISTS ${O.identifier(Y)}`),await T.execute(U);let J=(await T.all(O`select id, hash, created_at from ${O.identifier(Y)}.${O.identifier(X)} order by created_at desc limit 1`))[0];await T.transaction(async(z)=>{for await(let w of $)if(!J||Number(J.created_at)<w.folderMillis){for(let H of w.sql)await z.execute(O.raw(H));await z.execute(O`insert into ${O.identifier(Y)}.${O.identifier(X)} ("hash", "created_at") values(${w.hash}, ${w.folderMillis})`)}})}escapeName($){return`"${$}"`}escapeParam($){return`$${$+1}`}escapeString($){return`'${$.replace(/'/g,"''")}'`}buildWithCTE($){if(!$?.length)return;let T=[O`with `];for(let[W,X]of $.entries())if(T.push(O`${O.identifier(X._.alias)} as (${X._.sql})`),W<$.length-1)T.push(O`, `);return T.push(O` `),O.join(T)}buildDeleteQuery({table:$,where:T,returning:W,withList:X}){let Y=this.buildWithCTE(X),U=W?O` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,G=T?O` where ${T}`:void 0;return O`${Y}delete from ${$}${G}${U}`}buildUpdateSet($,T){let W=$[c.Symbol.Columns],X=Object.keys(W).filter((U)=>T[U]!==void 0||W[U]?.onUpdateFn!==void 0),Y=X.length;return O.join(X.flatMap((U,G)=>{let J=W[U],z=T[U]??O.param(J.onUpdateFn(),J),w=O`${O.identifier(this.casing.getColumnCasing(J))} = ${z}`;if(G<Y-1)return[w,O.raw(", ")];return[w]}))}buildUpdateQuery({table:$,set:T,where:W,returning:X,withList:Y,from:U,joins:G}){let J=this.buildWithCTE(Y),z=$[O4.Symbol.Name],w=$[O4.Symbol.Schema],H=$[O4.Symbol.OriginalName],_=z===H?void 0:z,F=O`${w?O`${O.identifier(w)}.`:void 0}${O.identifier(H)}${_&&O` ${O.identifier(_)}`}`,D=this.buildUpdateSet($,T),V=U&&O.join([O.raw(" from "),this.buildFromTable(U)]),E=this.buildJoins(G),R=X?O` returning ${this.buildSelection(X,{isSingleTable:!U})}`:void 0,P=W?O` where ${W}`:void 0;return O`${J}update ${F} set ${D}${V}${E}${P}${R}`}buildSelection($,{isSingleTable:T=!1}={}){let W=$.length,X=$.flatMap(({field:Y},U)=>{let G=[];if(S(Y,p.Aliased)&&Y.isSelectionField)G.push(O.identifier(Y.fieldAlias));else if(S(Y,p.Aliased)||S(Y,p)){let J=S(Y,p.Aliased)?Y.sql:Y;if(T)G.push(new p(J.queryChunks.map((z)=>{if(S(z,b))return O.identifier(this.casing.getColumnCasing(z));return z})));else G.push(J);if(S(Y,p.Aliased))G.push(O` as ${O.identifier(Y.fieldAlias)}`)}else if(S(Y,B$))if(T)G.push(O.identifier(this.casing.getColumnCasing(Y)));else G.push(Y);if(U<W-1)G.push(O`, `);return G});return O.join(X)}buildJoins($){if(!$||$.length===0)return;let T=[];for(let[W,X]of $.entries()){if(W===0)T.push(O` `);let Y=X.table,U=X.lateral?O` lateral`:void 0,G=X.on?O` on ${X.on}`:void 0;if(S(Y,O4)){let J=Y[O4.Symbol.Name],z=Y[O4.Symbol.Schema],w=Y[O4.Symbol.OriginalName],H=J===w?void 0:X.alias;T.push(O`${O.raw(X.joinType)} join${U} ${z?O`${O.identifier(z)}.`:void 0}${O.identifier(w)}${H&&O` ${O.identifier(H)}`}${G}`)}else if(S(Y,g4)){let J=Y[C$].name,z=Y[C$].schema,w=Y[C$].originalName,H=J===w?void 0:X.alias;T.push(O`${O.raw(X.joinType)} join${U} ${z?O`${O.identifier(z)}.`:void 0}${O.identifier(w)}${H&&O` ${O.identifier(H)}`}${G}`)}else T.push(O`${O.raw(X.joinType)} join${U} ${Y}${G}`);if(W<$.length-1)T.push(O` `)}return O.join(T)}buildFromTable($){if(S($,c)&&$[c.Symbol.IsAlias]){let T=O`${O.identifier($[c.Symbol.OriginalName])}`;if($[c.Symbol.Schema])T=O`${O.identifier($[c.Symbol.Schema])}.${T}`;return O`${T} ${O.identifier($[c.Symbol.Name])}`}return $}buildSelectQuery({withList:$,fields:T,fieldsFlat:W,where:X,having:Y,table:U,joins:G,orderBy:J,groupBy:z,limit:w,offset:H,lockingClause:_,distinct:F,setOperators:D}){let V=W??w6(T);for(let H$ of V)if(S(H$.field,B$)&&F4(H$.field.table)!==(S(U,G4)?U._.alias:S(U,e2)?U[C$].name:S(U,p)?void 0:F4(U))&&!((e$)=>G?.some(({alias:V4})=>V4===(e$[c.Symbol.IsAlias]?F4(e$):e$[c.Symbol.BaseName])))(H$.field.table)){let e$=F4(H$.field.table);throw new Error(`Your "${H$.path.join("->")}" field references a column "${e$}"."${H$.field.name}", but the table "${e$}" is not part of the query! Did you forget to join it?`)}let E=!G||G.length===0,R=this.buildWithCTE($),P;if(F)P=F===!0?O` distinct`:O` distinct on (${O.join(F.on,O`, `)})`;let A=this.buildSelection(V,{isSingleTable:E}),N=this.buildFromTable(U),k=this.buildJoins(G),y=X?O` where ${X}`:void 0,x=Y?O` having ${Y}`:void 0,m;if(J&&J.length>0)m=O` order by ${O.join(J,O`, `)}`;let J$;if(z&&z.length>0)J$=O` group by ${O.join(z,O`, `)}`;let m$=typeof w==="object"||typeof w==="number"&&w>=0?O` limit ${w}`:void 0,B=H?O` offset ${H}`:void 0,Z$=O.empty();if(_){let H$=O` for ${O.raw(_.strength)}`;if(_.config.of)H$.append(O` of ${O.join(Array.isArray(_.config.of)?_.config.of:[_.config.of],O`, `)}`);if(_.config.noWait)H$.append(O` nowait`);else if(_.config.skipLocked)H$.append(O` skip locked`);Z$.append(H$)}let $$=O`${R}select${P} ${A} from ${N}${k}${y}${J$}${x}${m}${m$}${B}${Z$}`;if(D.length>0)return this.buildSetOperations($$,D);return $$}buildSetOperations($,T){let[W,...X]=T;if(!W)throw new Error("Cannot pass undefined values to any set operator");if(X.length===0)return this.buildSetOperationQuery({leftSelect:$,setOperator:W});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:$,setOperator:W}),X)}buildSetOperationQuery({leftSelect:$,setOperator:{type:T,isAll:W,rightSelect:X,limit:Y,orderBy:U,offset:G}}){let J=O`(${$.getSQL()}) `,z=O`(${X.getSQL()})`,w;if(U&&U.length>0){let D=[];for(let V of U)if(S(V,b))D.push(O.identifier(V.name));else if(S(V,p)){for(let E=0;E<V.queryChunks.length;E++){let R=V.queryChunks[E];if(S(R,b))V.queryChunks[E]=O.identifier(R.name)}D.push(O`${V}`)}else D.push(O`${V}`);w=O` order by ${O.join(D,O`, `)} `}let H=typeof Y==="object"||typeof Y==="number"&&Y>=0?O` limit ${Y}`:void 0,_=O.raw(`${T} ${W?"all ":""}`),F=G?O` offset ${G}`:void 0;return O`${J}${_}${z}${w}${H}${F}`}buildInsertQuery({table:$,values:T,onConflict:W,returning:X,withList:Y,select:U,overridingSystemValue_:G}){let J=[],z=$[c.Symbol.Columns],w=Object.entries(z).filter(([R,P])=>!P.shouldDisableInsert()),H=w.map(([,R])=>O.identifier(this.casing.getColumnCasing(R)));if(U){let R=T;if(S(R,p))J.push(R);else J.push(R.getSQL())}else{let R=T;J.push(O.raw("values "));for(let[P,A]of R.entries()){let N=[];for(let[k,y]of w){let x=A[k];if(x===void 0||S(x,T6)&&x.value===void 0)if(y.defaultFn!==void 0){let m=y.defaultFn(),J$=S(m,p)?m:O.param(m,y);N.push(J$)}else if(!y.default&&y.onUpdateFn!==void 0){let m=y.onUpdateFn(),J$=S(m,p)?m:O.param(m,y);N.push(J$)}else N.push(O`default`);else N.push(x)}if(J.push(N),P<R.length-1)J.push(O`, `)}}let _=this.buildWithCTE(Y),F=O.join(J),D=X?O` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,V=W?O` on conflict ${W}`:void 0,E=G===!0?O`overriding system value `:void 0;return O`${_}insert into ${$} ${H} ${E}${F}${V}${D}`}buildRefreshMaterializedViewQuery({view:$,concurrently:T,withNoData:W}){let X=T?O` concurrently`:void 0,Y=W?O` with no data`:void 0;return O`refresh materialized view${X} ${$}${Y}`}prepareTyping($){if(S($,y8)||S($,f8))return"json";else if(S($,h8))return"decimal";else if(S($,g8))return"time";else if(S($,m8)||S($,c8))return"timestamp";else if(S($,x8)||S($,b8))return"date";else if(S($,u8))return"uuid";else return"none"}sqlToQuery($,T){return $.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:T})}buildRelationalQueryWithoutPK({fullSchema:$,schema:T,tableNamesMap:W,table:X,tableConfig:Y,queryConfig:U,tableAlias:G,nestedQueryRelation:J,joinOn:z}){let w=[],H,_,F=[],D,V=[];if(U===!0)w=Object.entries(Y.columns).map(([P,A])=>({dbKey:A.name,tsKey:P,field:y6(A,G),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let R=Object.fromEntries(Object.entries(Y.columns).map(([x,m])=>[x,y6(m,G)]));if(U.where){let x=typeof U.where==="function"?U.where(R,VO()):U.where;D=x&&c2(x,G)}let P=[],A=[];if(U.columns){let x=!1;for(let[m,J$]of Object.entries(U.columns)){if(J$===void 0)continue;if(m in Y.columns){if(!x&&J$===!0)x=!0;A.push(m)}}if(A.length>0)A=x?A.filter((m)=>U.columns?.[m]===!0):Object.keys(Y.columns).filter((m)=>!A.includes(m))}else A=Object.keys(Y.columns);for(let x of A){let m=Y.columns[x];P.push({tsKey:x,value:m})}let N=[];if(U.with)N=Object.entries(U.with).filter((x)=>!!x[1]).map(([x,m])=>({tsKey:x,queryConfig:m,relation:Y.relations[x]}));let k;if(U.extras){k=typeof U.extras==="function"?U.extras(R,{sql:O}):U.extras;for(let[x,m]of Object.entries(k))P.push({tsKey:x,value:E7(m,G)})}for(let{tsKey:x,value:m}of P)w.push({dbKey:S(m,p.Aliased)?m.fieldAlias:Y.columns[x].name,tsKey:x,field:S(m,B$)?y6(m,G):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let y=typeof U.orderBy==="function"?U.orderBy(R,KO()):U.orderBy??[];if(!Array.isArray(y))y=[y];F=y.map((x)=>{if(S(x,B$))return y6(x,G);return c2(x,G)}),H=U.limit,_=U.offset;for(let{tsKey:x,queryConfig:m,relation:J$}of N){let m$=MO(T,W,J$),B=R0(J$.referencedTable),Z$=W[B],$$=`${G}_${x}`,H$=l2(...m$.fields.map((D6,g0)=>p8(y6(m$.references[g0],$$),y6(D6,G)))),e$=this.buildRelationalQueryWithoutPK({fullSchema:$,schema:T,tableNamesMap:W,table:$[Z$],tableConfig:T[Z$],queryConfig:S(J$,h1)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:$$,joinOn:H$,nestedQueryRelation:J$}),V4=O`${O.identifier($$)}.${O.identifier("data")}`.as(x);V.push({on:O`true`,table:new G4(e$.sql,{},$$),alias:$$,joinType:"left",lateral:!0}),w.push({dbKey:x,tsKey:x,field:V4,relationTableTsKey:Z$,isJson:!0,selection:e$.selection})}}if(w.length===0)throw new v8({message:`No fields selected for table "${Y.tsName}" ("${G}")`});let E;if(D=l2(z,D),J){let R=O`json_build_array(${O.join(w.map(({field:N,tsKey:k,isJson:y})=>y?O`${O.identifier(`${G}_${k}`)}.${O.identifier("data")}`:S(N,p.Aliased)?N.sql:N),O`, `)})`;if(S(J,r2))R=O`coalesce(json_agg(${R}${F.length>0?O` order by ${O.join(F,O`, `)}`:void 0}), '[]'::json)`;let P=[{dbKey:"data",tsKey:"data",field:R.as("data"),isJson:!0,relationTableTsKey:Y.tsName,selection:w}];if(H!==void 0||_!==void 0||F.length>0)E=this.buildSelectQuery({table:C8(X,G),fields:{},fieldsFlat:[{path:[],field:O.raw("*")}],where:D,limit:H,offset:_,orderBy:F,setOperators:[]}),D=void 0,H=void 0,_=void 0,F=[];else E=C8(X,G);E=this.buildSelectQuery({table:S(E,O4)?E:new G4(E,{},G),fields:{},fieldsFlat:P.map(({field:N})=>({path:[],field:S(N,B$)?y6(N,G):N})),joins:V,where:D,limit:H,offset:_,orderBy:F,setOperators:[]})}else E=this.buildSelectQuery({table:C8(X,G),fields:{},fieldsFlat:w.map(({field:R})=>({path:[],field:S(R,B$)?y6(R,G):R})),joins:V,where:D,limit:H,offset:_,orderBy:F,setOperators:[]});return{tableTsKey:Y.tsName,sql:E,selection:w}}}class o7{static[Z]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class P4{static[Z]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor($){if(this.fields=$.fields,this.session=$.session,this.dialect=$.dialect,$.withList)this.withList=$.withList;this.distinct=$.distinct}authToken;setToken($){return this.authToken=$,this}from($){let T=!!this.fields,W=$,X;if(this.fields)X=this.fields;else if(S(W,G4))X=Object.fromEntries(Object.keys(W._.selectedFields).map((Y)=>[Y,W[Y]]));else if(S(W,e2))X=W[C$].selectedFields;else if(S(W,p))X={};else X=aQ(W);return new l7({table:W,fields:X,isPartialSelect:T,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class uO extends o7{static[Z]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:$,fields:T,isPartialSelect:W,session:X,dialect:Y,withList:U,distinct:G}){super();this.config={withList:U,table:$,fields:{...T},distinct:G,setOperators:[]},this.isPartialSelect=W,this.session=X,this.dialect=Y,this._={selectedFields:T},this.tableName=U1($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin($,T){return(W,X)=>{let Y=this.tableName,U=U1(W);if(typeof U==="string"&&this.config.joins?.some((G)=>G.alias===U))throw new Error(`Alias "${U}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof Y==="string")this.config.fields={[Y]:this.config.fields};if(typeof U==="string"&&!S(W,p)){let G=S(W,G4)?W._.selectedFields:S(W,g4)?W[C$].selectedFields:W[c.Symbol.Columns];this.config.fields[U]=G}}if(typeof X==="function")X=X(new Proxy(this.config.fields,new r$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:X,table:W,joinType:$,alias:U,lateral:T}),typeof U==="string")switch($){case"left":{this.joinsNotNullableMap[U]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[U]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[U]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[U]=!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($,T){return(W)=>{let X=typeof W==="function"?W(ck()):W;if(!u2(this.getSelectedFields(),X.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:$,isAll:T,rightSelect:X}),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($){return this.config.setOperators.push(...$),this}where($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new r$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=$,this}having($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new r$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=$,this}groupBy(...$){if(typeof $[0]==="function"){let T=$[0](new Proxy(this.config.fields,new r$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(T)?T:[T]}else this.config.groupBy=$;return this}orderBy(...$){if(typeof $[0]==="function"){let T=$[0](new Proxy(this.config.fields,new r$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),W=Array.isArray(T)?T:[T];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=W;else this.config.orderBy=W}else{let T=$;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=T;else this.config.orderBy=T}return this}limit($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=$;else this.config.limit=$;return this}offset($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=$;else this.config.offset=$;return this}for($,T={}){return this.config.lockingClause={strength:$,config:T},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:$,...T}=this.dialect.sqlToQuery(this.getSQL());return T}as($){return new Proxy(new G4(this.getSQL(),this.config.fields,$),new r$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new r$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class l7 extends uO{static[Z]="PgSelect";_prepare($){let{session:T,config:W,dialect:X,joinsNotNullableMap:Y,authToken:U}=this;if(!T)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return R$.startActiveSpan("drizzle.prepareQuery",()=>{let G=w6(W.fields),J=T.prepareQuery(X.sqlToQuery(this.getSQL()),G,$,!0);return J.joinsNotNullableMap=Y,J.setToken(U)})}prepare($){return this._prepare($)}authToken;setToken($){return this.authToken=$,this}execute=($)=>{return R$.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute($,this.authToken)})}}tQ(l7,[k4]);function CT($,T){return(W,X,...Y)=>{let U=[X,...Y].map((G)=>({type:$,isAll:T,rightSelect:G}));for(let G of U)if(!u2(W.getSelectedFields(),G.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return W.addSetOperators(U)}}var ck=()=>({union:uk,unionAll:pk,intersect:dk,intersectAll:ok,except:lk,exceptAll:rk}),uk=CT("union",!1),pk=CT("union",!0),dk=CT("intersect",!1),ok=CT("intersect",!0),lk=CT("except",!1),rk=CT("except",!0);class $X{static[Z]="PgQueryBuilder";dialect;dialectConfig;constructor($){this.dialect=S($,C0)?$:void 0,this.dialectConfig=S($,C0)?void 0:$}$with=($,T)=>{let W=this;return{as:(Y)=>{if(typeof Y==="function")Y=Y(W);return new Proxy(new h2(Y.getSQL(),T??("getSelectedFields"in Y?Y.getSelectedFields()??{}:{}),$,!0),new r$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...$){let T=this;function W(U){return new P4({fields:U??void 0,session:void 0,dialect:T.getDialect(),withList:$})}function X(U){return new P4({fields:U??void 0,session:void 0,dialect:T.getDialect(),distinct:!0})}function Y(U,G){return new P4({fields:G??void 0,session:void 0,dialect:T.getDialect(),distinct:{on:U}})}return{select:W,selectDistinct:X,selectDistinctOn:Y}}select($){return new P4({fields:$??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct($){return new P4({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn($,T){return new P4({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:$}})}getDialect(){if(!this.dialect)this.dialect=new C0(this.dialectConfig);return this.dialect}}class YU{constructor($,T,W,X,Y){this.table=$,this.session=T,this.dialect=W,this.withList=X,this.overridingSystemValue_=Y}static[Z]="PgInsertBuilder";authToken;setToken($){return this.authToken=$,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values($){if($=Array.isArray($)?$:[$],$.length===0)throw new Error("values() must be called with at least one value");let T=$.map((W)=>{let X={},Y=this.table[c.Symbol.Columns];for(let U of Object.keys(W)){let G=W[U];X[U]=S(G,p)?G:new T6(G,Y[U])}return X});return new r7(this.table,T,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select($){let T=typeof $==="function"?$(new $X):$;if(!S(T,p)&&!u2(this.table[q8],T._.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 r7(this.table,T,this.session,this.dialect,this.withList,!0)}}class r7 extends k4{constructor($,T,W,X,Y,U,G){super();this.session=W,this.dialect=X,this.config={table:$,values:T,withList:Y,select:U,overridingSystemValue_:G}}static[Z]="PgInsert";config;returning($=this.config.table[c.Symbol.Columns]){return this.config.returningFields=$,this.config.returning=w6($),this}onConflictDoNothing($={}){if($.target===void 0)this.config.onConflict=O`do nothing`;else{let T="";T=Array.isArray($.target)?$.target.map((X)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(X))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing($.target));let W=$.where?O` where ${$.where}`:void 0;this.config.onConflict=O`(${O.raw(T)})${W} do nothing`}return this}onConflictDoUpdate($){if($.where&&($.targetWhere||$.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 T=$.where?O` where ${$.where}`:void 0,W=$.targetWhere?O` where ${$.targetWhere}`:void 0,X=$.setWhere?O` where ${$.setWhere}`:void 0,Y=this.dialect.buildUpdateSet(this.config.table,j8(this.config.table,$.set)),U="";return U=Array.isArray($.target)?$.target.map((G)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(G))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing($.target)),this.config.onConflict=O`(${O.raw(U)})${W} do update set ${Y}${T}${X}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:$,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare($){return R$.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,$,!0)})}prepare($){return this._prepare($)}authToken;setToken($){return this.authToken=$,this}execute=($)=>{return R$.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute($,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new r$({alias:F4(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class i7 extends k4{constructor($,T,W){super();this.session=T,this.dialect=W,this.config={view:$}}static[Z]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:$,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare($){return R$.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,$,!0)})}prepare($){return this._prepare($)}authToken;setToken($){return this.authToken=$,this}execute=($)=>{return R$.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute($,this.authToken)})}}class UU{constructor($,T,W,X){this.table=$,this.session=T,this.dialect=W,this.withList=X}static[Z]="PgUpdateBuilder";authToken;setToken($){return this.authToken=$,this}set($){return new pO(this.table,j8(this.table,$),this.session,this.dialect,this.withList).setToken(this.authToken)}}class pO extends k4{constructor($,T,W,X,Y){super();this.session=W,this.dialect=X,this.config={set:T,table:$,withList:Y,joins:[]},this.tableName=U1($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[Z]="PgUpdate";config;tableName;joinsNotNullableMap;from($){let T=$,W=U1(T);if(typeof W==="string")this.joinsNotNullableMap[W]=!0;return this.config.from=T,this}getTableLikeFields($){if(S($,O4))return $[c.Symbol.Columns];else if(S($,G4))return $._.selectedFields;return $[C$].selectedFields}createJoin($){return(T,W)=>{let X=U1(T);if(typeof X==="string"&&this.config.joins.some((Y)=>Y.alias===X))throw new Error(`Alias "${X}" is already used in this query`);if(typeof W==="function"){let Y=this.config.from&&!S(this.config.from,p)?this.getTableLikeFields(this.config.from):void 0;W=W(new Proxy(this.config.table[c.Symbol.Columns],new r$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),Y&&new Proxy(Y,new r$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:W,table:T,joinType:$,alias:X}),typeof X==="string")switch($){case"left":{this.joinsNotNullableMap[X]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([Y])=>[Y,!1])),this.joinsNotNullableMap[X]=!0;break}case"inner":{this.joinsNotNullableMap[X]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([Y])=>[Y,!1])),this.joinsNotNullableMap[X]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where($){return this.config.where=$,this}returning($){if(!$){if($=Object.assign({},this.config.table[c.Symbol.Columns]),this.config.from){let T=U1(this.config.from);if(typeof T==="string"&&this.config.from&&!S(this.config.from,p)){let W=this.getTableLikeFields(this.config.from);$[T]=W}for(let W of this.config.joins){let X=U1(W.table);if(typeof X==="string"&&!S(W.table,p)){let Y=this.getTableLikeFields(W.table);$[X]=Y}}}}return this.config.returningFields=$,this.config.returning=w6($),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:$,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare($){let T=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,$,!0);return T.joinsNotNullableMap=this.joinsNotNullableMap,T}prepare($){return this._prepare($)}authToken;setToken($){return this.authToken=$,this}execute=($)=>{return this._prepare().execute($,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new r$({alias:F4(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class TX extends p{constructor($){super(TX.buildEmbeddedCount($.source,$.filters).queryChunks);this.params=$,this.mapWith(Number),this.session=$.session,this.sql=TX.buildCount($.source,$.filters)}sql;token;static[Z]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount($,T){return O`(select count(*) from ${$}${O.raw(" where ").if(T)}${T})`}static buildCount($,T){return O`select count(*) as count from ${$}${O.raw(" where ").if(T)}${T};`}setToken($){return this.token=$,this}then($,T){return Promise.resolve(this.session.count(this.sql,this.token)).then($,T)}catch($){return this.then(void 0,$)}finally($){return this.then((T)=>{return $?.(),T},(T)=>{throw $?.(),T})}}class t7{constructor($,T,W,X,Y,U,G){this.fullSchema=$,this.schema=T,this.tableNamesMap=W,this.table=X,this.tableConfig=Y,this.dialect=U,this.session=G}static[Z]="PgRelationalQueryBuilder";findMany($){return new n7(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many")}findFirst($){return new n7(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first")}}class n7 extends k4{constructor($,T,W,X,Y,U,G,J,z){super();this.fullSchema=$,this.schema=T,this.tableNamesMap=W,this.table=X,this.tableConfig=Y,this.dialect=U,this.session=G,this.config=J,this.mode=z}static[Z]="PgRelationalQuery";_prepare($){return R$.startActiveSpan("drizzle.prepareQuery",()=>{let{query:T,builtQuery:W}=this._toSQL();return this.session.prepareQuery(W,void 0,$,!0,(X,Y)=>{let U=X.map((G)=>o8(this.schema,this.tableConfig,G,T.selection,Y));if(this.mode==="first")return U[0];return U})})}prepare($){return this._prepare($)}_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 $=this._getQuery(),T=this.dialect.sqlToQuery($.sql);return{query:$,builtQuery:T}}toSQL(){return this._toSQL().builtQuery}authToken;setToken($){return this.authToken=$,this}execute(){return R$.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class a7 extends k4{constructor($,T,W,X){super();this.execute=$,this.sql=T,this.query=W,this.mapBatchResult=X}static[Z]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult($,T){return T?this.mapBatchResult($):$}_prepare(){return this}isResponseInArrayMode(){return!1}}class WX{constructor($,T,W){if(this.dialect=$,this.session=T,this._=W?{schema:W.schema,fullSchema:W.fullSchema,tableNamesMap:W.tableNamesMap,session:T}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:T},this.query={},this._.schema)for(let[X,Y]of Object.entries(this._.schema))this.query[X]=new t7(W.fullSchema,this._.schema,this._.tableNamesMap,W.fullSchema[X],Y,$,T)}static[Z]="PgDatabase";query;$with=($,T)=>{let W=this;return{as:(Y)=>{if(typeof Y==="function")Y=Y(new $X(W.dialect));return new Proxy(new h2(Y.getSQL(),T??("getSelectedFields"in Y?Y.getSelectedFields()??{}:{}),$,!0),new r$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count($,T){return new TX({source:$,filters:T,session:this.session})}with(...$){let T=this;function W(z){return new P4({fields:z??void 0,session:T.session,dialect:T.dialect,withList:$})}function X(z){return new P4({fields:z??void 0,session:T.session,dialect:T.dialect,withList:$,distinct:!0})}function Y(z,w){return new P4({fields:w??void 0,session:T.session,dialect:T.dialect,withList:$,distinct:{on:z}})}function U(z){return new UU(z,T.session,T.dialect,$)}function G(z){return new YU(z,T.session,T.dialect,$)}function J(z){return new XU(z,T.session,T.dialect,$)}return{select:W,selectDistinct:X,selectDistinctOn:Y,update:U,insert:G,delete:J}}select($){return new P4({fields:$??void 0,session:this.session,dialect:this.dialect})}selectDistinct($){return new P4({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn($,T){return new P4({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:{on:$}})}update($){return new UU($,this.session,this.dialect)}insert($){return new YU($,this.session,this.dialect)}delete($){return new XU($,this.session,this.dialect)}refreshMaterializedView($){return new i7($,this.session,this.dialect)}authToken;execute($){let T=typeof $==="string"?O.raw($):$.getSQL(),W=this.dialect.sqlToQuery(T),X=this.session.prepareQuery(W,void 0,void 0,!1);return new a7(()=>X.execute(void 0,this.authToken),T,W,(Y)=>X.mapResult(Y,!0))}transaction($,T){return this.session.transaction($,T)}}class dO{constructor($,T){this.unique=$,this.name=T}static[Z]="PgIndexBuilderOn";on(...$){return new GU($.map((T)=>{if(S(T,p))return T;T=T;let W=new f2(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),W}),this.unique,!1,this.name)}onOnly(...$){return new GU($.map((T)=>{if(S(T,p))return T;T=T;let W=new f2(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=T.defaultConfig,W}),this.unique,!0,this.name)}using($,...T){return new GU(T.map((W)=>{if(S(W,p))return W;W=W;let X=new f2(W.name,!!W.keyAsName,W.columnType,W.indexConfig);return W.indexConfig=JSON.parse(JSON.stringify(W.defaultConfig)),X}),this.unique,!0,this.name,$)}}class GU{static[Z]="PgIndexBuilder";config;constructor($,T,W,X,Y="btree"){this.config={name:X,columns:$,unique:T,only:W,method:Y}}concurrently(){return this.config.concurrently=!0,this}with($){return this.config.with=$,this}where($){return this.config.where=$,this}build($){return new oO(this.config,$)}}class oO{static[Z]="PgIndex";config;constructor($,T){this.config={...$,table:T}}}function s7($){return new dO(!0,$)}class e7{constructor($){this.query=$}authToken;getQuery(){return this.query}mapResult($,T){return $}setToken($){return this.authToken=$,this}static[Z]="PgPreparedQuery";joinsNotNullableMap}class $_{constructor($){this.dialect=$}static[Z]="PgSession";execute($,T){return R$.startActiveSpan("drizzle.operation",()=>{return R$.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery($),void 0,void 0,!1)}).setToken(T).execute(void 0,T)})}all($){return this.prepareQuery(this.dialect.sqlToQuery($),void 0,void 0,!1).all()}async count($,T){let W=await this.execute($,T);return Number(W[0].count)}}class T_ extends WX{constructor($,T,W,X=0){super($,T,W);this.schema=W,this.nestedIndex=X}static[Z]="PgTransaction";rollback(){throw new M7}getTransactionConfigSQL($){let T=[];if($.isolationLevel)T.push(`isolation level ${$.isolationLevel}`);if($.accessMode)T.push($.accessMode);if(typeof $.deferrable==="boolean")T.push($.deferrable?"deferrable":"not deferrable");return O.raw(T.join(" "))}setTransaction($){return this.session.execute(O`set transaction ${this.getTransactionConfigSQL($)}`)}}class lO extends e7{constructor($,T,W,X,Y,U,G){super({sql:T,params:W});this.client=$,this.queryString=T,this.params=W,this.logger=X,this.fields=Y,this._isResponseInArrayMode=U,this.customResultMapper=G}static[Z]="PostgresJsPreparedQuery";async execute($={}){return R$.startActiveSpan("drizzle.execute",async(T)=>{let W=K7(this.params,$);T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(W)}),this.logger.logQuery(this.queryString,W);let{fields:X,queryString:Y,client:U,joinsNotNullableMap:G,customResultMapper:J}=this;if(!X&&!J)return R$.startActiveSpan("drizzle.driver.execute",()=>{return U.unsafe(Y,W)});let z=await R$.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":Y,"drizzle.query.params":JSON.stringify(W)}),U.unsafe(Y,W).values()});return R$.startActiveSpan("drizzle.mapResponse",()=>{return J?J(z):z.map((w)=>nQ(X,w,G))})})}all($={}){return R$.startActiveSpan("drizzle.execute",async(T)=>{let W=K7(this.params,$);return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(W)}),this.logger.logQuery(this.queryString,W),R$.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(W)}),this.client.unsafe(this.queryString,W)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class XX extends $_{constructor($,T,W,X={}){super(T);this.client=$,this.schema=W,this.options=X,this.logger=X.logger??new N7}static[Z]="PostgresJsSession";logger;prepareQuery($,T,W,X,Y){return new lO(this.client,$.sql,$.params,this.logger,T,X,Y)}query($,T){return this.logger.logQuery($,T),this.client.unsafe($,T).values()}queryObjects($,T){return this.client.unsafe($,T)}transaction($,T){return this.client.begin(async(W)=>{let X=new XX(W,this.dialect,this.schema,this.options),Y=new W_(this.dialect,X,this.schema);if(T)await Y.setTransaction(T);return $(Y)})}}class W_ extends T_{constructor($,T,W,X=0){super($,T,W,X);this.session=T}static[Z]="PostgresJsTransaction";transaction($){return this.session.client.savepoint((T)=>{let W=new XX(T,this.dialect,this.schema,this.session.options),X=new W_(this.dialect,W,this.schema);return $(X)})}}class rO extends WX{static[Z]="PostgresJsDatabase"}function vT($,T={}){let W=(z)=>z;for(let z of["1184","1082","1083","1114","1182","1185","1115","1231"])$.options.parsers[z]=W,$.options.serializers[z]=W;$.options.serializers["114"]=W,$.options.serializers["3802"]=W;let X=new C0({casing:T.casing}),Y;if(T.logger===!0)Y=new A7;else if(T.logger!==!1)Y=T.logger;let U;if(T.schema){let z=EO(T.schema,AO);U={fullSchema:T.schema,schema:z.tables,tableNamesMap:z.tableNamesMap}}let G=new XX($,X,U,{logger:Y}),J=new rO(X,G,U);return J.$client=$,J}function JU(...$){if(typeof $[0]==="string"){let T=PT($[0]);return vT(T,$[1])}if(sQ($[0])){let{connection:T,client:W,...X}=$[0];if(W)return vT(W,X);if(typeof T==="object"&&T.url!==void 0){let{url:U,...G}=T,J=PT(U,G);return vT(J,X)}let Y=PT(T);return vT(Y,X)}return vT($[0],$[1])}(($)=>{function T(W){return vT({options:{parsers:{},serializers:{}}},W)}$.mock=T})(JU||(JU={}));function iO($,T){if($ instanceof Promise)throw new Error(T)}function ik($,T){let W={},X=[];for(let Y in $){let U=$[Y]["~standard"].validate(T[Y]);if(iO(U,`Validation must be synchronous, but ${Y} returned a Promise.`),U.issues){X.push(...U.issues.map((G)=>({...G,path:[Y,...G.path??[]]})));continue}W[Y]=U.value}if(X.length)return{issues:X};return{value:W}}function X_($){let T=$.runtimeEnvStrict??$.runtimeEnv??process.env;if($.emptyStringAsUndefined??!1){for(let[A,N]of Object.entries(T))if(N==="")delete T[A]}if(!!$.skipValidation)return T;let Y=typeof $.client==="object"?$.client:{},U=typeof $.server==="object"?$.server:{},G=typeof $.shared==="object"?$.shared:{},J=$.isServer??(typeof window==="undefined"||("Deno"in window)),z=J?{...U,...G,...Y}:{...Y,...G},w=$.createFinalSchema?.(z,J)["~standard"].validate(T)??ik(z,T);iO(w,"Validation must be synchronous");let H=$.onValidationError??((A)=>{throw console.error("\u274C Invalid environment variables:",A),new Error("Invalid environment variables")}),_=$.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(w.issues)return H(w.issues);let F=(A)=>{if(!$.clientPrefix)return!0;return!A.startsWith($.clientPrefix)&&!(A in G)},D=(A)=>{return J||!F(A)},V=(A)=>{return A==="__esModule"||A==="$$typeof"},E=($.extends??[]).reduce((A,N)=>{return Object.assign(A,N)},{}),R=Object.assign(E,w.value);return new Proxy(R,{get(A,N){if(typeof N!=="string")return;if(V(N))return;if(!D(N))return _(N);return Reflect.get(A,N)}})}var m1=($)=>Array.isArray($)?$:[$],nO=($,T)=>{let W=[[],[]];for(let X of $)if(T(X))W[0].push(X);else W[1].push(X);return W},wU=Array,J1=($,T)=>$.includes(T),tO=($,T=0)=>[...new Array($)].map((W,X)=>X+T),Q$=($,T,W)=>{if($===void 0)return T===void 0?[]:Array.isArray(T)?T:[T];if(W?.prepend)if(Array.isArray(T))$.unshift(...T);else $.unshift(T);else if(Array.isArray(T))$.push(...T);else $.push(T);return $},w1=($,T)=>{if(T===void 0||T===null)return $??[];if($===void 0||$===null)return m1(T);return $.concat(T)},aO=(...$)=>$.reduce(w1,[]),g6=($,T,W)=>{if($===void 0)return Array.isArray(T)?T:[T];let X=W?.isEqual??((Y,U)=>Y===U);for(let Y of m1(T))if(!$.some((U)=>X(U,Y)))$.push(Y);return $},sO=($,T)=>$.reduce((W,X)=>{let Y=X[T];return W[Y]=Q$(W[Y],X),W},{}),z1=($,T,W)=>$.length===T.length&&$.every(W?.isEqual?(X,Y)=>W.isEqual(X,T[Y]):(X,Y)=>X===T[Y]);var c4=($,T)=>w4($)===T,w4=($)=>{let T=typeof $;return T==="object"?$===null?"null":"object":T==="function"?"object":T},u4={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},eO={...u4,function:"a function"};class $V extends Error{}var O$=($)=>v0($,$V),v0=($,T=Error)=>{throw new T($)};class YX extends Error{name="ParseError"}var L=($)=>v0($,YX),L6=($)=>` ${$}`;var Y$=($,T)=>{let W={},X=Array.isArray($),Y=!1;for(let[U,G]of Object.entries($).entries()){let J=X?T(U,G[1]):T(...G,U);Y||=typeof J[0]==="number";let z=Array.isArray(J[0])||J.length===0?J:[J];for(let[w,H]of z)if(typeof w==="object")W[w.group]=Q$(W[w.group],H);else W[w]=H}return Y?Object.values(W):W};var Y_=Object.entries;var z4=($,T)=>($ in T),jT=($,T)=>(T in $);class U_{constructor($){Object.assign(this,$)}}var TV=class{};class UX extends TV{}var nk=($,T)=>{let W={},X={},Y;for(Y in $)if(Y in T)W[Y]=$[Y];else X[Y]=$[Y];return[W,X]};var WV=($,T)=>nk($,T)[1],m6=($)=>Object.keys($).length===0,j0=($)=>[...Object.entries($),...Object.getOwnPropertySymbols($).map((T)=>[T,$[T]])],XV=($,T)=>Object.defineProperties($,Object.getOwnPropertyDescriptors(T)),YV=($)=>{let T=Object.keys($).sort(),W={};for(let X=0;X<T.length;X++)W[T[X]]=$[T[X]];return W};var X6=L6("represents an uninitialized value"),UV=($)=>Object.values($).filter((T)=>{if(typeof T==="number")return!0;return typeof $[T]!=="number"});var G_={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},J_=globalThis.File??Blob,w_={ArrayBuffer,Blob,File:J_,FormData,Headers,Request,Response,URL},tk={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},x0={...G_,...w_,...tk,String,Number,Boolean},GX=($)=>{let T=Object.getPrototypeOf($);while(T?.constructor&&(!z4(T.constructor.name,x0)||!($ instanceof x0[T.constructor.name])))T=Object.getPrototypeOf(T);let W=T?.constructor?.name;if(W===void 0||W==="Object")return;return W},JX=($)=>typeof $==="object"&&$!==null?GX($)??"object":w4($);var I$=Array.isArray,ak={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"},sk={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"},ek={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"},GV={...ak,...sk,...ek},wX=($)=>{let T=Object($).name??null;return T&&z4(T,x0)&&x0[T]===$?T:null};var z_=($,T)=>{let W=$.prototype;while(W!==null){if(W===T.prototype)return!0;W=Object.getPrototypeOf(W)}return!1};var JV=($)=>wV($,new Map),wV=($,T)=>{if(typeof $!=="object"||$===null)return $;if(T?.has($))return T.get($);let W=wX($.constructor);if(W==="Date")return new Date($.getTime());if(W&&W!=="Array")return $;let X=Array.isArray($)?$.slice():Object.create(Object.getPrototypeOf($)),Y=Object.getOwnPropertyDescriptors($);if(T){T.set($,X);for(let U in Y){let G=Y[U];if("get"in G||"set"in G)continue;G.value=wV(G.value,T)}}return Object.defineProperties(X,Y),X};var $q=($)=>{let T=X6;return()=>T===X6?T=$():T},c1=($)=>typeof $==="function"&&$.length===0;var zV=class extends Function{constructor(...$){let T=$.slice(0,-1),W=$.at(-1);try{super(...T,W)}catch(X){return O$(`Encountered an unexpected error while compiling your definition:
|
|
84
108
|
Message: ${X}
|
|
85
|
-
Source: (${
|
|
86
|
-
${
|
|
87
|
-
}`)}}};class
|
|
88
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
89
|
-
`+X);return
|
|
90
|
-
${X}${
|
|
91
|
-
${
|
|
92
|
-
${
|
|
109
|
+
Source: (${$.slice(0,-1)}) => {
|
|
110
|
+
${$.at(-1)}
|
|
111
|
+
}`)}}};class S6{constructor($,...[T]){return Object.assign(Object.setPrototypeOf($.bind(T?.bind??this),this.constructor.prototype),T?.attach)}}var _V=$q(()=>{try{return new Function("return false")()}catch{return!0}});var Ws=L6("brand");var HV=L6("arkInferred");var Us=L6("args");class L4{constructor(){}}var Tq=()=>{try{return((new Error().stack?.split(`
|
|
112
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},Wq=globalThis.process?.env??{},FV={fileName:Tq,env:Wq};var QV=($)=>$[0].toUpperCase()+$.slice(1);var __=($)=>new RegExp(Xq($),typeof $==="string"?"":$.flags);var Xq=($)=>{return`^(?:${typeof $==="string"?$:$.source})$`};var _1={negativeLookahead:($)=>`(?!${$})`,nonCapturingGroup:($)=>`(?:${$})`},zX="\\",u1={" ":1,"\n":1,"\t":1};var Yq=/^-0\.?0*$/.source,DV=/[1-9]\d*/.source,Uq=/\.\d+/.source,Gq=/\.\d*[1-9]/.source,OV=($)=>__(_1.negativeLookahead(Yq)+_1.nonCapturingGroup("-?"+_1.nonCapturingGroup(_1.nonCapturingGroup("0|"+DV)+_1.nonCapturingGroup($.decimalPattern)+"?")+($.allowDecimalOnly?"|"+$.decimalPattern:"")+"?")),ZV=OV({decimalPattern:Gq,allowDecimalOnly:!1}),Jq=ZV.test.bind(ZV),zU=OV({decimalPattern:Uq,allowDecimalOnly:!0}),Fs=zU.test.bind(zU),wq=/^-?\d*\.?\d*$/,zq=($)=>$.length!==0&&wq.test($),_X=__(_1.negativeLookahead("^-0$")+"-?"+_1.nonCapturingGroup(_1.nonCapturingGroup("0|"+DV))),_q=_X.test.bind(_X),H_=/^-?\d+$/,Hq=H_.test.bind(H_),VV={number:"a number",bigint:"a bigint",integer:"an integer"},KV=($,T)=>`'${$}' was parsed as ${VV[T]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Fq=($,T)=>T==="number"?Jq($):_q($),Qq=($,T)=>T==="number"?Number($):Number.parseInt($),Zq=($,T)=>T==="number"?zq($):Hq($),EV=($,T)=>F_($,"number",T),MV=($,T)=>F_($,"number",{...T,strict:!0}),AV=($,T)=>F_($,"integer",T),F_=($,T,W)=>{let X=Qq($,T);if(!Number.isNaN(X)){if(Zq($,T)){if(W?.strict)return Fq($,T)?X:L(KV($,T));return X}}return W?.errorOnFail?L(W?.errorOnFail===!0?`Failed to parse ${VV[T]} from '${$}'`:W?.errorOnFail):void 0},NV=($)=>{if($[$.length-1]!=="n")return;let T=$.slice(0,-1),W;try{W=BigInt(T)}catch{return}if(_X.test(T))return W;if(H_.test(T))return L(KV($,"bigint"))};var Dq="0.46.0",Oq={version:Dq,filename:FV.fileName(),FileConstructor:J_},b0=Oq,LV=new Map,Q_=Object.create(null),HX=($)=>{let T=LV.get($);if(T)return T;let W=Vq($);if(Q_[W])W=`${W}${Q_[W]++}`;else Q_[W]=1;return b0[W]=$,LV.set($,W),W},p1=($)=>/^[$A-Z_a-z][\w$]*$/.test($),Vq=($)=>{switch(typeof $){case"object":{if($===null)break;let T=GX($)??"object";return T[0].toLowerCase()+T.slice(1)}case"function":return p1($.name)?$.name:"fn";case"symbol":return $.description&&p1($.description)?$.description:"symbol"}return O$(`Unexpected attempt to register serializable value of type ${w4($)}`)};var FX=($)=>typeof $==="string"?JSON.stringify($):typeof $==="bigint"?`${$}n`:`${$}`;var SV=($,T={})=>QX($,{onUndefined:"$ark.undefined",onBigInt:(W)=>`$ark.bigint-${W}`,...T},[]);var U$=($,T)=>{switch(w4($)){case"object":let W=$,X=W.constructor.name;return X==="Object"||X==="Array"?T?.quoteKeys===!1?_U(W,T?.indent??0,""):JSON.stringify(QX(W,xT,[]),null,T?.indent):_U(W,T?.indent??0,"");case"symbol":return xT.onSymbol($);default:return FX($)}},_U=($,T,W)=>{if(typeof $==="function")return xT.onFunction($);if(typeof $!=="object"||$===null)return FX($);let X=W+" ".repeat(T);if(Array.isArray($)){if($.length===0)return"[]";let U=$.map((G)=>_U(G,T,X)).join(`,
|
|
113
|
+
`+X);return T?`[
|
|
114
|
+
${X}${U}
|
|
115
|
+
${W}]`:`[${U}]`}let Y=$.constructor.name;if(Y==="Object"){let U=j0($).map(([G,J])=>{let z=typeof G==="symbol"?xT.onSymbol(G):p1(G)?G:JSON.stringify(G),w=_U(J,T,X);return`${X}${z}: ${w}`});if(U.length===0)return"{}";return T?`{
|
|
116
|
+
${U.join(`,
|
|
93
117
|
`)}
|
|
94
|
-
${
|
|
95
|
-
`,this}const(
|
|
96
|
-
`).map((
|
|
97
|
-
`):this.body} }`}compile(){return new
|
|
98
|
-
`)}_add(
|
|
99
|
-
|
|
100
|
-
`));Object.defineProperty(this,"arkErrors",{value
|
|
118
|
+
${W}}`:`{${U.join(", ")}}`}if($ instanceof Date)return f0($);if("expression"in $&&typeof $.expression==="string")return $.expression;return Y},xT={onCycle:()=>"(cycle)",onSymbol:($)=>`Symbol(${HX($)})`,onFunction:($)=>`Function(${HX($)})`},QX=($,T,W)=>{switch(w4($)){case"object":{let X=$;if("toJSON"in X&&typeof X.toJSON==="function")return X.toJSON();if(typeof X==="function")return xT.onFunction(X);if(W.includes(X))return"(cycle)";let Y=[...W,X];if(Array.isArray(X))return X.map((G)=>QX(G,T,Y));if(X instanceof Date)return X.toDateString();let U={};for(let G in X)U[G]=QX(X[G],T,Y);for(let G of Object.getOwnPropertySymbols(X))U[T.onSymbol?.(G)??G.toString()]=QX(X[G],T,Y);return U}case"symbol":return xT.onSymbol($);case"bigint":return T.onBigInt?.($)??`${$}n`;case"undefined":return T.onUndefined??"undefined";case"string":return $.replaceAll("\\","\\\\");default:return $}},f0=($)=>{let T=$.getFullYear(),W=$.getMonth(),X=$.getDate(),Y=$.getHours(),U=$.getMinutes(),G=$.getSeconds(),J=$.getMilliseconds();if(W===0&&X===1&&Y===0&&U===0&&G===0&&J===0)return`${T}`;let z=`${Kq[W]} ${X}, ${T}`;if(Y===0&&U===0&&G===0&&J===0)return z;let w=$.toLocaleTimeString(),H=w.endsWith(" AM")||w.endsWith(" PM")?w.slice(-3):"";if(H)w=w.slice(0,-H.length);if(J)w+=`.${Mq(J,3)}`;else if(Eq.test(w))w=w.slice(0,-3);return`${w+H}, ${z}`},Kq=["January","February","March","April","May","June","July","August","September","October","November","December"],Eq=/:\d\d:00$/,Mq=($,T)=>String($).padStart(T,"0");var BV=($,T,...[W])=>{let X=W?.stringifySymbol??U$,Y=$;switch(typeof T){case"string":Y=p1(T)?$===""?T:`${$}.${T}`:`${$}[${JSON.stringify(T)}]`;break;case"number":Y=`${$}[${T}]`;break;case"symbol":Y=`${$}[${X(T)}]`;break;default:if(W?.stringifyNonKey)Y=`${$}[${W.stringifyNonKey(T)}]`;else L(`${U$(T)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return Y},H1=($,...T)=>$.reduce((W,X)=>BV(W,X,...T),"");class ZX extends wU{cache={};constructor(...$){super();this.push(...$)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let $=0;$<this.length;$++)this.cache.json.push(typeof this[$]==="symbol"?U$(this[$]):this[$]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=H1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let $="",T=[$];for(let W of this)$=BV($,W),T.push($);return this.cache.stringifyAncestors=T}}class Z_{chars;i;def;constructor($){this.def=$,this.chars=[...$],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($){let T="";while(this.lookahead){if($(this,T))if(T[T.length-1]===zX)T=T.slice(0,-1);else break;T+=this.shift()}return T}shiftUntilLookahead($){return typeof $==="string"?this.shiftUntil((T)=>T.lookahead===$):this.shiftUntil((T)=>(T.lookahead in $))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in u1))}jumpToIndex($){this.i=$<0?this.length+$:$}jumpForward($){this.i+=$}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($,T){return this.chars.slice($,T).join("")}lookaheadIs($){return this.lookahead===$}lookaheadIsIn($){return this.lookahead in $}}var ys=L6("implementedTraits");var D_="$ark",Aq=2;while(D_ in globalThis)D_=`$ark${Aq++}`;var RV=D_;globalThis[RV]=b0;var I=b0,Nq=($)=>`${RV}.${$}`,d$=($)=>Nq(HX($));class HU extends UX{argNames;body="";constructor(...$){super();this.argNames=$;for(let T of $){if(T in this)throw new Error(`Arg name '${T}' would overwrite an existing property on FunctionBody`);this[T]=T}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop($,T=!1){return O_($,T)}index($,T=!1){return IV(`${$}`,T)}line($){return this.body+=`${" ".repeat(this.indentation)}${$}
|
|
119
|
+
`,this}const($,T){return this.line(`const ${$} = ${T}`),this}let($,T){return this.line(`let ${$} = ${T}`)}set($,T){return this.line(`${$} = ${T}`)}if($,T){return this.block(`if (${$})`,T)}elseIf($,T){return this.block(`else if (${$})`,T)}else($){return this.block("else",$)}for($,T,W=0){return this.block(`for (let i = ${W}; ${$}; i++)`,T)}forIn($,T){return this.block(`for (const k in ${$})`,T)}block($,T,W=""){return this.line(`${$} {`),this.indent(),T(this),this.dedent(),this.line(`}${W}`)}return($=""){return this.line(`return ${$}`)}write($="anonymous",T=0){return`${$}(${this.argNames.join(", ")}) { ${T?this.body.split(`
|
|
120
|
+
`).map((W)=>" ".repeat(T)+`${W}`).join(`
|
|
121
|
+
`):this.body} }`}compile(){return new zV(...this.argNames,this.body)}}var F1=($)=>c4($,"object")||typeof $==="symbol"?d$($):FX($),O_=($,T=!1)=>{if(typeof $==="string"&&p1($))return`${T?"?":""}.${$}`;return IV(Lq($),T)},Lq=($)=>typeof $==="symbol"?d$($):JSON.stringify($),IV=($,T=!1)=>`${T?"?.":""}[${$}]`;class DX extends HU{traversalKind;optimistic;constructor($){super("data","ctx");this.traversalKind=$.kind,this.optimistic=$.optimistic===!0}invoke($,T){let W=T?.arg??this.data,X=typeof $==="string"?!0:this.requiresContextFor($),Y=typeof $==="string"?$:$.id;if(X)return`${this.referenceToId(Y,T)}(${W}, ${this.ctx})`;return`${this.referenceToId(Y,T)}(${W})`}referenceToId($,T){let W=T?.kind??this.traversalKind,X=`this.${$}${W}`;return T?.bind?`${X}.bind(${T?.bind})`:X}requiresContextFor($){return this.traversalKind==="Apply"||$.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($,T,W){let X=this.requiresContextFor(W);if(X)this.line(`${this.ctx}.path.push(${$})`);if(this.check(W,{arg:T}),X)this.line(`${this.ctx}.path.pop()`);return this}check($,T){return this.traversalKind==="Allows"?this.if(`!${this.invoke($,T)}`,()=>this.return(!1)):this.line(this.invoke($,T))}}var FU=($)=>Y$($,(T,W)=>[T,I$(W)?[...W]:W]),C4=L6("arkKind"),o=($,T)=>$?.[C4]===T,v$=($)=>o($,"root")||o($,"constraint");var kV=["unit","proto","domain"],bT=["required","optional","index","sequence"],V_=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],QU=[...V_,...bT,"structure","predicate"],fT=["alias","union","morph","unit","intersection","proto","domain"],Sq=[...fT,...QU],ZU=Y$(QU,($,T)=>[T,1]),qV=Y$([...bT,"undeclared"],($,T)=>[T,1]),PV=Y$(Sq,($,T)=>[T,$]),yT=($)=>typeof $==="string"&&($ in PV);var hT=($)=>PV[$],DU=($)=>fT.slice(hT($)+1),Me=[...DU("union"),"alias"],Ae=[...DU("morph"),"alias"],H6=($)=>{if(typeof $==="string"||typeof $==="boolean"||$===null)return $;if(typeof $==="number"){if(Number.isNaN($))return"NaN";if($===Number.POSITIVE_INFINITY)return"Infinity";if($===Number.NEGATIVE_INFINITY)return"-Infinity";return $}return F1($)},d1=($)=>{let T="{ ";for(let[W,X]of Object.entries($))T+=`${W}: ${F1(X)}, `;return T+" }"},G$=($)=>{let T=$;if(T.hasAssociatedError)T.defaults.expected??=(W)=>("description"in W)?W.description:T.defaults.description(W),T.defaults.actual??=(W)=>U$(W),T.defaults.problem??=(W)=>`must be ${W.expected}${W.actual?` (was ${W.actual})`:""}`,T.defaults.message??=(W)=>{if(W.path.length===0)return W.problem;let X=`${W.propString} ${W.problem}`;if(X[0]==="[")return`value at ${X}`;return X};return T};class CV extends Error{name="ToJsonSchemaError";code;context;constructor($,T){super(U$(T,{quoteKeys:!1,indent:4}));this.code=$,this.context=T}hasCode($){return this.code===$}}var Bq={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:($)=>y$.throw("arrayObject",$),arrayPostfix:($)=>y$.throw("arrayPostfix",$),defaultValue:($)=>y$.throw("defaultValue",$),domain:($)=>y$.throw("domain",$),morph:($)=>y$.throw("morph",$),patternIntersection:($)=>y$.throw("patternIntersection",$),predicate:($)=>y$.throw("predicate",$),proto:($)=>y$.throw("proto",$),symbolKey:($)=>y$.throw("symbolKey",$),unit:($)=>y$.throw("unit",$),date:($)=>y$.throw("date",$)}},y$={Error:CV,throw:(...$)=>{throw new y$.Error(...$)},throwInternalOperandError:($,T)=>O$(`Unexpected JSON Schema input for ${$}: ${U$(T)}`),defaultConfig:Bq};I.config??={};var OX=($,T)=>{if(!T)return $;let W={...$},X;for(X in T){let Y={...$.keywords};if(X==="keywords"){for(let U in T[X]){let G=T.keywords[U];if(G===void 0)continue;Y[U]=typeof G==="string"?{description:G}:G}W.keywords=Y}else if(X==="toJsonSchema")W[X]=K_($.toJsonSchema,T.toJsonSchema);else if(yT(X))W[X]={...$[X],...T[X]};else W[X]=T[X]}return W},K_=($,T)=>{if(!$)return T??{};if(!T)return $;let W={...$},X;for(X in T)if(X==="fallback")W.fallback=Rq($.fallback,T.fallback);else W[X]=T[X];return W},Rq=($,T)=>{$=vV($),T=vV(T);let W={},X;for(X in y$.defaultConfig.fallback)W[X]=T[X]??T.default??$[X]??$.default??y$.defaultConfig.fallback[X];return W},vV=($)=>typeof $==="function"?{default:$}:$??{};class o1 extends UX{[C4]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:$,relativePath:T,...W},X){super();this.input=W,this.ctx=X,XV(this,W);let Y=X.data;if(W.code==="union")W.errors=W.errors.flatMap((G)=>{let J=G.hasCode("union")?G.errors:[G];if(!$&&!T)return J;return J.map((z)=>z.transform((w)=>({...w,path:aO($,w.path,T)})))});this.nodeConfig=X.config[this.code];let U=[...W.path??X.path];if(T)U.push(...T);if($)U.unshift(...$);this.path=new ZX(...U),this.data="data"in W?W.data:Y}transform($){return new o1($({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode($){return this.code===$}get propString(){return H1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let $=this.meta?.expected??this.nodeConfig.expected;return typeof $==="function"?$(this.input):$}get actual(){if(this.input.actual)return this.input.actual;let $=this.meta?.actual??this.nodeConfig.actual;return typeof $==="function"?$(this.data):$}get problem(){if(this.input.problem)return this.input.problem;let $=this.meta?.problem??this.nodeConfig.problem;return typeof $==="function"?$(this):$}get message(){if(this.input.message)return this.input.message;let $=this.meta?.message??this.nodeConfig.message;return typeof $==="function"?$(this):$}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 p4 extends wU{[C4]="errors";ctx;constructor($){super();this.ctx=$}byPath=Object.create(null);get flatByPath(){return Y$(this.byPath,($,T)=>[$,T.flat])}get flatProblemsByPath(){return Y$(this.byPath,($,T)=>[$,T.flat.map((W)=>W.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new E_(this)}add($){if(this.includes($))return;this._add($)}transform($){let T=new p4(this.ctx);for(let W of this)T.add($(W));return T}merge($){for(let T of $){if(this.includes(T))continue;this._add(new o1({...T,path:[...this.ctx.path,...T.path]},this.ctx))}}affectsPath($){if(this.length===0)return!1;return $.stringifyAncestors().some((T)=>(T in this.byPath))||$.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(($)=>$.toJSON())]}toString(){return this.join(`
|
|
122
|
+
`)}_add($){let T=this.byPath[$.propString];if(T){if(T.hasCode("union")&&T.errors.length===0)return;let W=$.hasCode("union")&&$.errors.length===0?$:new o1({code:"intersection",errors:T.hasCode("intersection")?[...T.errors,$]:[T,$]},this.ctx),X=this.indexOf(T);this.mutable[X===-1?this.length:X]=W,this.byPath[$.propString]=W,this.addAncestorPaths($)}else this.byPath[$.propString]=$,this.addAncestorPaths($),this.mutable.push($);this.count++}addAncestorPaths($){for(let T of $.path.stringifyAncestors())this.byAncestorPath[T]=Q$(this.byAncestorPath[T],$)}}class E_ extends Error{name="TraversalError";constructor($){if($.length===1)super($.summary);else super(`
|
|
123
|
+
`+$.map((T)=>` \u2022 ${Iq(T)}`).join(`
|
|
124
|
+
`));Object.defineProperty(this,"arkErrors",{value:$,enumerable:!1})}}var Iq=($)=>$.toString().split(`
|
|
101
125
|
`).join(`
|
|
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 F$(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 g6(...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 l$(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:Y}of W){if(this.errors.affectsPath($))continue;this.applyMorphsAtPath($,Y)}}}applyMorphsAtPath(W,$){let Y=W.at(-1),X;if(Y!==void 0){X=this.root;for(let G=0;G<W.length-1;G++)X=X[W[G]]}this.path=[...W];for(let G of $){let J=b0(G),H=G(X===void 0?this.root:X[Y],this);if(H instanceof l$){this.errors.add(H);break}if(H instanceof c1){if(!J)this.errors.merge(H);break}if(X===void 0)this.root=H;else X[Y]=H;this.applyQueuedMorphs()}}}var d1=(W,$,Y)=>{if(!Y)return $();Y.path.push(W);let X=$();return Y.path.pop(),X};class c6 extends qW{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(W,$){super((X,G,J=this.onFail)=>{if(G)return this.traverseApply(X,G),G.hasError()?G.errors:G.data;return this.rootApply(X,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((X,G)=>mK(X,G.shallowReferences),[this]);let Y=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let X=0;X<this.children.length;X++){if(this.includesTransform||=this.children[X].includesTransform,this.includesContextualPredicate||=this.children[X].includesContextualPredicate,this.isCyclic||=this.children[X].isCyclic,!Y){let G=this.children[X].flatRefs;for(let J=0;J<G.length;J++){let H=G[J];if(!this.flatRefs.some((T)=>ez(T,H))){this.flatRefs.push(H);for(let T of H.node.branches)if(T.hasKind("morph")||T.hasKind("intersection")&&T.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:H.path,propString:H.propString,node:T})}}}Object.assign(this.referencesById,this.children[X].referencesById)}this.flatRefs.sort((X,G)=>X.path.length>G.path.length?1:X.path.length<G.path.length?-1:X.propString>G.propString?1:X.propString<G.propString?-1:X.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((X)=>X.length===1||X.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((X)=>X.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(X)=>this.traverseAllows(X,new CW(X,this.$.resolvedConfig)):(X)=>this.traverseAllows(X)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return($,Y)=>{if(this.allows($))return $;let X=new CW($,this.$.resolvedConfig);return this.traverseApply($,X),X.finalize(Y)};case"contextual":return($,Y)=>{let X=new CW($,this.$.resolvedConfig);return this.traverseApply($,X),X.finalize(Y)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let W=this.$.resolvedConfig.clone;return($,Y)=>{if(this.allows($))return this.contextFreeMorph(W&&(typeof $==="object"&&$!==null||typeof $==="function")?W($):$);let X=new CW($,this.$.resolvedConfig);return this.traverseApply($,X),X.finalize(Y)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,E0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=gK(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=j8(this.kind);precompilation;assert=(W,$)=>this(W,$,(Y)=>Y.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[Y,X]of this.innerEntries){let G=this.impl.keys[Y];if(G.reduceIo)G.reduceIo(W,$,X);else if(G.child){let J=X;$[Y]=k0(J)?J.map((H)=>H[W]):J[W]}else $[Y]=X}return this.$.node(this.kind,$)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(W){let $=b0(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)q2(`${this.kind} node was not of asserted kind ${W}`);return this}hasKindIn(...W){return W.includes(this.kind)}assertHasKindIn(...W){if(!T$(W,this.kind))q2(`${this.kind} node was not one of asserted kinds ${W}`);return this}isBasis(){return T$(iz,this.kind)}isConstraint(){return T$(rX,this.kind)}isStructural(){return T$(q8,this.kind)}isRefinement(){return T$(n7,this.kind)}isRoot(){return T$(C8,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 $=u6.normalize(W);return this._select($)}_select(W){let $=u6.applyBoundary[W.boundary??"references"](this);if(W.kind)$=$.filter((Y)=>Y.kind===W.kind);if(W.where)$=$.filter(W.where);return u6.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 Y=$.bindScope??this.$;if($.seen[this.id])return this.$.lazilyResolve($.seen[this.id]);if($.shouldTransform?.(this,$)===!1)return this;let X;if($.seen[this.id]=()=>X,this.hasKind("structure")&&this.undeclared!==$.undeclaredKeyHandling)$={...$,undeclaredKeyHandling:this.undeclared};let G=X0(this.inner,(_,z)=>{if(!this.impl.keys[_].child)return[_,z];let F=z;if(!k0(F)){let O=F._transform(W,$);return O?[_,O]:[]}if(F.length===0)return[_,z];let w=F.flatMap((O)=>{return O._transform(W,$)??[]});return w.length?[_,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(b0(H))return X=H;let T=Object.keys(H);if((T.length===0||T.length===1&&T[0]==="meta")&&!cW(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in H))return $.undeclaredKeyHandling?{...H,value:R.intrinsic.unknown}:null;if(this.kind==="morph")H.in??=R.intrinsic.unknown;return X=Y.node(this.kind,H,$.parseOptions)}configureReferences(W,$="references"){let Y=u6.normalize($),X=typeof W==="string"?(T,Q)=>({...Q,meta:{...Q.meta,description:W}}):typeof W==="function"?(T,Q)=>({...Q,meta:W(Q.meta)}):(T,Q)=>({...Q,meta:{...Q.meta,...W}});if(Y.boundary==="self")return this.$.node(this.kind,X(this.kind,{...this.inner,meta:this.meta}));let G=this._select(Y),J=G&&m$(G),H=Y.boundary==="child"?(T,Q)=>Q.root.children.includes(T):Y.boundary==="shallow"?(T)=>T.kind!=="structure":()=>!0;return this.$.finalize(this.transform(X,{shouldTransform:H,selected:J}))}}var u6={applyBoundary:{self:(W)=>[W],child:(W)=>[...W.children],shallow:(W)=>[...W.shallowReferences],references:(W)=>[...W.references]},applyMethod:{filter:(W)=>W,assertFilter:(W,$,Y)=>{if(W.length===0)q2(sz($,Y));return W},find:(W)=>W[0],assertFind:(W,$,Y)=>{if(W.length===0)q2(sz($,Y));return W[0]}},normalize:(W)=>typeof W==="function"?{boundary:"references",method:"filter",where:W}:typeof W==="string"?_1(W,u6.applyBoundary)?{method:"filter",boundary:W}:{boundary:"references",method:"filter",kind:W}:{boundary:"references",method:"filter",...W}},sz=(W,$)=>`${W} had no references matching ${G0($)}.`,yK=(W)=>F$(W,{stringifyNonKey:($)=>$.expression}),hK=/"(\$ark\.[^"]+)"/g,gK=(W)=>JSON.stringify(W).replaceAll(hK,"$1"),kW=(W,$)=>({path:W,node:$,propString:yK(W)}),ez=(W,$)=>W.propString===$.propString&&W.node.equals($.node),a7=(W,$)=>uW(W,$,{isEqual:ez}),mK=(W,$)=>uW(W,$,{isEqual:(Y,X)=>Y.equals(X)});class v extends Array{static init(W,$,Y,X){return new v({kind:W,l:$,r:Y,path:X?.path??[],optional:X?.optional??!1})}add(W,$,Y,X){return this.push({kind:W,l:$,r:Y,path:X?.path??[],optional:X?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:W,l:$,r:Y}=this[0],X=F$(W);return e7(`Intersection${X&&` at ${X}`} of ${WF($,Y)}`)}return`The following intersections result in unsatisfiable types:
|
|
103
|
-
\u2022 ${this.map(({path:
|
|
104
|
-
\u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let W=this.map(($)=>({...$,l:$.r,r:$.l}));if(!(W instanceof v))return new v(...W);return W}withPrefixKey(W,$){return this.map((Y)=>({...Y,path:[W,...Y.path],optional:Y.optional||$==="optional"}))}toNeverIfDisjoint(){return R.intrinsic.never}}var WF=(W,$)=>`${s7(W)} and ${s7($)}`,s7=(W)=>b0(W)?W.expression:k0(W)?W.map(s7).join(" | ")||"never":String(W),e7=(W)=>`${W} results in an unsatisfiable type`;var I8={},l1=(W,$,Y)=>x0(W,$,{$:Y,invert:!1,pipe:!1}),d6=(W,$,Y)=>x0(W,$,{$:Y,invert:!1,pipe:!0}),x0=(W,$,Y)=>{let X=Y.pipe?"|>":"&",G=`${W.hash}${X}${$.hash}`;if(I8[G]!==void 0)return I8[G];if(!Y.pipe){let T=`${$.hash}${X}${W.hash}`;if(I8[T]!==void 0){let Q=I8[T],_=Q instanceof v?Q.invert():Q;return I8[G]=_,_}}let J=!Y.pipe||!W.includesTransform&&!$.includesTransform;if(J&&W.equals($))return W;let H=J?WG(W,$,Y):W.hasKindIn(...C8)?pK(W,$,Y):WG(W,$,Y);if(b0(H)){if(W.equals(H))H=W;else if($.equals(H))H=$}return I8[G]=H,H},WG=(W,$,Y)=>{let X=W.precedence<$.precedence?W.kind:$.kind,G=W.impl.intersections[$.kind]??$.impl.intersections[W.kind];if(G===void 0)return null;else if(X===W.kind)return G(W,$,Y);else{let J=G($,W,{...Y,invert:!Y.invert});if(J instanceof v)J=J.invert();return J}},pK=(W,$,Y)=>W.includesTransform||$.includesTransform?Y.invert?$F($,W,Y):$F(W,$,Y):WG(W,$,Y),$F=(W,$,Y)=>W.distribute((X)=>uK(X,$,Y),(X)=>{let G=X.filter(b0);if(G.length===0)return v.init("union",W.branches,$.branches);if(G.length<W.branches.length||!W.branches.every((T,Q)=>T.in.equals(G[Q].in)))return Y.$.parseSchema(G);let J;if(G.length===1){let T=G[0];if(!J)return T;return Y.$.node("morph",{...T.inner,in:T.in.configure(J,"self")})}let H={branches:G};if(J)H.meta=J;return Y.$.parseSchema(H)}),uK=(W,$,Y)=>{if(W.hasKind("morph")){let G=[...W.morphs];if(W.lastMorphIfNode){let J=x0(W.lastMorphIfNode,$,Y);if(J instanceof v)return J;G[G.length-1]=J}else G.push($);return Y.$.node("morph",{morphs:G,in:W.inner.in})}if($.hasKind("morph")){let G=x0(W,$.in,Y);if(G instanceof v)return G;return Y.$.node("morph",{morphs:[$],in:G})}return Y.$.node("morph",{morphs:[$],in:W})};class wW extends c6{constructor(W,$){super(W,$);Object.defineProperty(this,b1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(W){return l1(this,W,this.$)}}class U$ 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 d$(this.errorContext)}}var B1=(W)=>($,Y)=>{if(k0($)){if($.length===0)return;let G=$.map((J)=>Y.$.node(W,J));if(W==="predicate")return G;return G.sort((J,H)=>J.hash<H.hash?-1:1)}let X=Y.$.node(W,$);return X.hasOpenIntersection()?[X]:X},P8=(W)=>{let $=W.r.shift();if(!$){let X=W.l.length===0&&W.kind==="structure"?R.intrinsic.unknown.internal:W.ctx.$.node(W.kind,Object.assign(W.baseInner,cK(W.l)),{prereduced:!0});for(let G of W.roots){if(X instanceof v)return X;X=x0(G,X,W.ctx)}return X}let Y=!1;for(let X=0;X<W.l.length;X++){let G=x0(W.l[X],$,W.ctx);if(G===null)continue;if(G instanceof v)return G;if(!Y){if(G.isRoot())return W.roots.push(G),W.l.splice(X),P8(W);W.l[X]=G,Y=!0}else if(!W.l.includes(G))return E0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!Y)W.l.push($);if(W.kind==="intersection"){if($.impliedSiblings)for(let X of $.impliedSiblings)uW(W.r,X)}return P8(W)},f8=(W)=>{return Object.entries(W).flatMap(([Y,X])=>(Y in tX)?X:[]).sort((Y,X)=>Y.precedence<X.precedence?-1:Y.precedence>X.precedence?1:Y.kind==="predicate"&&X.kind==="predicate"?0:Y.hash<X.hash?-1:1)},cK=(W)=>{let $={};for(let Y of W)if(Y.hasOpenIntersection())$[Y.kind]=D0($[Y.kind],Y);else{if($[Y.kind])return E0(`Unexpected intersection of closed refinements of kind ${Y.kind}`);$[Y.kind]=Y}return $},YF=(...W)=>A(XF(...W)),XF=(W,$,Y)=>{let X=Y.hasKind("morph")?"a morph":Y.isUnknown()?"unknown":Y.exclude($).defaultShortDescription;return`${Pz(W)} operand must be ${$.description} (was ${X})`};var GF=(W,$,Y)=>new o$(W,$,Y,Y,null);class sX extends qW{}class o$ extends qW{[b1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(W,$,Y,X,G){super((...J)=>{let H=X0(this.names,(T,Q)=>{let _=this.arg$.parse(J[T]);if(!_.extends(this.constraints[T]))A(dK(Q,this.constraints[T].expression,_.expression));return[Q,_]});if(this.defIsLazy()){let T=this.bodyDef(H);return this.$.parse(T)}return this.$.parse($,{args:H})});this.paramDefs=W,this.bodyDef=$,this.$=Y,this.arg$=X,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 sX}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:cz(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((W)=>typeof W==="string"?[W,R.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 dK=(W,$,Y)=>`${W} must be assignable to ${$} (was ${Y})`;var lK=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 JF 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=d$(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 $G={implementation:lK,Node:JF};var oK=J0({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(W)=>Number.isInteger(W)?W:A(iK(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,$,Y)=>Y.$.node("divisor",{rule:Math.abs(W.rule*$.rule/nK(W.rule,$.rule))})},obviatesBasisDescription:!0});class HF extends U${traverseAllows=(W)=>W%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=R.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(W){if(W.type="integer",this.rule===1)return W;return W.multipleOf=this.rule,W}}var YG={implementation:oK,Node:HF};var iK=(W)=>`divisor must be an integer (was ${W})`,nK=(W,$)=>{let Y,X=W,G=$;while(G!==0)Y=G,G=X%G,X=Y;return X};class XW extends U${boundOperandKind=sK[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=eK(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${rK[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?WE(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 rK={"<":">=","<=":">",">":"<=",">=":"<"},tK={min:"max",minLength:"maxLength",after:"before"},eX={parse:(W)=>W||void 0},W9=(W)=>($)=>{if(typeof $==="number")return{rule:$};let{exclusive:Y,...X}=$;return Y?{...X,rule:W==="minLength"?X.rule+1:X.rule-1}:X},$9=(W)=>($)=>{if(typeof $==="number"||typeof $==="string"||$ instanceof Date)return{rule:$};let{exclusive:Y,...X}=$;if(!Y)return X;let G=typeof X.rule==="number"?X.rule:typeof X.rule==="string"?new Date(X.rule).valueOf():X.rule.valueOf();return Y?{...X,rule:W==="after"?G+1:G-1}:X},Y9=(W)=>typeof W==="string"||typeof W==="number"?new Date(W):W,aK=(W,$)=>`${W} bound must be a positive integer (was ${$})`,b8=(W)=>($)=>{if(!Number.isInteger($)||$<0)A(aK(W,$));return $},sK={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},eK=(W,$)=>`${_1(W,tK)?">":"<"}${$?"":"="}`,WE=(W)=>typeof W==="string"?W:new Date(W).toLocaleString(),TF=(W)=>`Bounded expression ${W} must be exactly one of number, string, Array, or Date`;var $E=J0({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y9,serialize:(W)=>W.toISOString()}},normalize:$9("after"),defaults:{description:(W)=>`${W.collapsibleLimitString} or later`,actual:I2},intersections:{after:(W,$)=>W.isStricterThan($)?W:$}});class QF extends XW{impliedBasis=R.intrinsic.Date.internal;collapsibleLimitString=I2(this.rule);traverseAllows=(W)=>W>=this.rule;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,after:this.rule})}}var XG={implementation:$E,Node:QF};var YE=J0({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y9,serialize:(W)=>W.toISOString()}},normalize:$9("before"),defaults:{description:(W)=>`${W.collapsibleLimitString} or earlier`,actual:I2},intersections:{before:(W,$)=>W.isStricterThan($)?W:$,after:(W,$,Y)=>W.overlapsRange($)?W.overlapIsUnit($)?Y.$.node("unit",{unit:W.rule}):null:v.init("range",W,$)}});class _F extends XW{collapsibleLimitString=I2(this.rule);traverseAllows=(W)=>W<=this.rule;impliedBasis=R.intrinsic.Date.internal;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,before:this.rule})}}var GG={implementation:YE,Node:_F};var XE=J0({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:b8("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,$,Y)=>v.init("unit",Y.$.node("unit",{unit:W.rule}),Y.$.node("unit",{unit:$.rule}),{path:["length"]}),minLength:(W,$)=>W.rule>=$.rule?W:v.init("range",W,$),maxLength:(W,$)=>W.rule<=$.rule?W:v.init("range",W,$)}});class zF extends U${traverseAllows=(W)=>W.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=R.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 JG={implementation:XE,Node:zF};var GE=J0({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:eX},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,$,Y)=>W.overlapsRange($)?W.overlapIsUnit($)?Y.$.node("unit",{unit:W.rule}):null:v.init("range",W,$)},obviatesBasisDescription:!0});class FF extends XW{impliedBasis=R.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 HG={implementation:GE,Node:FF};var JE=J0({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:b8("maxLength")}},reduce:(W,$)=>W.rule===0?$.node("exactLength",W):void 0,normalize:W9("maxLength"),defaults:{description:(W)=>`at most length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{maxLength:(W,$)=>W.isStricterThan($)?W:$,minLength:(W,$,Y)=>W.overlapsRange($)?W.overlapIsUnit($)?Y.$.node("exactLength",{rule:W.rule}):null:v.init("range",W,$)}});class wF extends XW{impliedBasis=R.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 TG={implementation:JE,Node:wF};var HE=J0({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:eX},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 UF extends XW{impliedBasis=R.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 QG={implementation:HE,Node:UF};var TE=J0({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:b8("minLength")}},reduce:(W)=>W.rule===0?R.intrinsic.unknown:void 0,normalize:W9("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 DF extends XW{impliedBasis=R.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 _G={implementation:TE,Node:DF};var MF={min:QG.implementation,max:HG.implementation,minLength:_G.implementation,maxLength:TG.implementation,exactLength:JG.implementation,after:XG.implementation,before:GG.implementation},VF={min:QG.Node,max:HG.Node,minLength:_G.Node,maxLength:TG.Node,exactLength:JG.Node,after:XG.Node,before:GG.Node};var QE=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 OF extends U${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=R.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:QE,Node:OF};var l6=(W,$)=>{let Y=_E(W);if($&&!$.includes(Y))return A(`Root of kind ${Y} should be one of ${$}`);return Y},_E=(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 A(KF(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((Y)=>(Y in tX)))return"intersection";if("proto"in W)return"proto";if("domain"in W)return"domain";return A(KF(W))},KF=(W)=>`${G0(W)} is not a valid type schema`,EF={},zE=(W)=>k0(W)?W.map(($)=>$.collapsibleJson):W.collapsibleJson,x1={};R.nodesByRegisteredId=x1;var FG=(W)=>{return EF[W]??=0,`${W}${++EF[W]}`},wG=(W)=>{let $=x8[W.kind],Y=$.applyConfig?.(W.def,W.$.resolvedConfig)??W.def,X={},{meta:G,...J}=Y,H=G===void 0?{}:typeof G==="string"?{description:G}:G,T=x7(J).sort(([_],[z])=>k8(_)?k8(z)?j8(_)-j8(z):1:k8(z)?-1:_<z?-1:1).filter(([_,z])=>{if(_.startsWith("meta.")){let F=_.slice(5);return H[F]=z,!1}return!0});for(let _ of T){let z=_[0],F=$.keys[z];if(!F)return A(`Key ${z} is not valid on ${W.kind} schema`);let w=F.parse?F.parse(_[1],W):_[1];if(w!==YW&&(w!==void 0||F.preserveUndefined))X[z]=w}if($.reduce&&!W.prereduced){let _=$.reduce(X,W.$);if(_){if(_ instanceof v)return _.throw();return FE(_,H)}}return UG({id:W.id,kind:W.kind,inner:X,meta:H,$:W.$})},UG=({id:W,kind:$,inner:Y,meta:X,$:G,ignoreCache:J})=>{let H=x8[$],T=x7(Y),Q=[],_={};for(let[j,N]of T){let B=H.keys[j],P=B.serialize??(B.child?zE:FW);if(_[j]=P(N),B.child===!0){let g=N;if(k0(g))Q.push(...g);else Q.push(g)}else if(typeof B.child==="function")Q.push(...B.child(N))}if(H.finalizeInnerJson)_=H.finalizeInnerJson(_);let z={..._},F={};if(!cW(X))F=X0(X,(j,N)=>[j,j==="examples"?N:FW(N)]),z.meta=X9(F,"description",!0);_=X9(_,H.collapsibleKey,!1);let w=JSON.stringify({kind:$,..._});z=X9(z,H.collapsibleKey,!1);let O=X9(z,H.collapsibleKey,!0),V=JSON.stringify({kind:$,...z});if(G.nodesByHash[V]&&!J)return G.nodesByHash[V];let E={id:W,kind:$,impl:H,inner:Y,innerEntries:T,innerJson:_,innerHash:w,meta:X,metaJson:F,json:z,hash:V,collapsibleJson:O,children:Q};if($!=="intersection"){for(let j in Y)if(j!=="in"&&j!=="out")E[j]=Y[j]}let I=new LF[$](E,G);return G.nodesByHash[V]=I},AF=(W,$)=>{if(W.id===$)return W;if(b0(x1[$]))E0(`Unexpected attempt to overwrite node id ${$}`);return UG({id:$,kind:W.kind,inner:W.inner,meta:W.meta,$:W.$,ignoreCache:!0})},FE=(W,$,Y)=>{if(Y&&b0(x1[Y]))E0(`Unexpected attempt to overwrite node id ${Y}`);return UG({id:Y??FG($.alias??W.kind),kind:W.kind,inner:W.inner,meta:$,$:W.$})},X9=(W,$,Y)=>{let X=Object.keys(W);if(X.length===1&&X[0]===$){let G=W[$];if(Y)return G;if(p1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return W};var o6=(W,$,Y)=>{if(W.key!==$.key)return null;let X=W.key,G=x0(W.value,$.value,Y),J=W.required||$.required?"required":"optional";if(G instanceof v)if(J==="optional")G=R.intrinsic.never.internal;else return G.withPrefixKey(W.key,W.required&&$.required?"required":"optional");if(J==="required")return Y.$.node("required",{key:X,value:G});let H=W.hasDefault()?$.hasDefault()?W.default===$.default?W.default:A(DG(W.default,$.default)):W.default:$.hasDefault()?$.default:YW;return Y.$.node("optional",{key:X,value:G,default:H})};class i6 extends wW{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=R.intrinsic.object.internal;serializedKey=w$(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 Y=super._transform(W,$);return $.path.pop(),Y}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 DG=(W,$)=>`Invalid intersection of default values ${G0(W)} & ${G0($)}`;var wE=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:o6}});class ZF extends i6{constructor(...W){super(...W);if("default"in this.inner)r6(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=DE(this);defaultValueMorphRef=this.defaultValueMorph&&d0(this.defaultValueMorph)}var n6={implementation:wE,Node:ZF},UE={},DE=(W)=>{if(!W.hasDefault())return;let $=`{${W.compiledKey}: ${W.value.id} = ${FW(W.default)}}`;return UE[$]??=MG(W.key,W.value,W.default)},MG=(W,$,Y)=>{if(typeof Y==="function")return $.includesTransform?(G,J)=>{return d1(W,()=>$(G[W]=Y(),J),J),G}:(G)=>{return G[W]=Y(),G};let X=$.includesTransform?$.assert(Y):Y;return p1(X,"object")?(G,J)=>{return d1(W,()=>$(G[W]=Y,J),J),G}:(G)=>{return G[W]=X,G}},r6=(W,$,Y)=>{let X=p$($);if(p1($,"object")&&!X)A(ME(Y));let G=W.in(X?$():$);if(G instanceof c1){if(Y===null)A(`Default ${G.summary}`);let J=G.transform((H)=>H.transform((T)=>({...T,prefixPath:[Y]})));A(`Default for ${J.summary}`)}return $},ME=(W)=>{return`Non-primitive default ${W===null?"":typeof W==="number"?`for value at [${W}] `:`for ${w$(W)} `}must be specified as a function like () => ({my: 'object'})`};class UW extends c6{constructor(W,$){super(W,$);Object.defineProperty(this,b1,{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 A(VE);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(W,$){let Y=this.branches.map(W);return $?.(Y)??Y}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(W={}){let $=r7(this.$.resolvedConfig.toJsonSchema,W);$.useRefs||=this.isCyclic;let Y=typeof $.dialect==="string"?{$schema:$.dialect}:{};if(Object.assign(Y,this.toJsonSchemaRecurse($)),$.useRefs)Y.$defs=X0(this.references,(X,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema($)]:[]);return Y}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),Y=this.rawIntersect($);if(Y instanceof v)return Y;return this.$.finalize(Y)}rawIntersect(W){return l1(this,W,this.$)}toNeverIfDisjoint(){return this}and(W){let $=this.intersect(W);return $ instanceof v?$.throw():$}rawAnd(W){let $=this.rawIntersect(W);return $ instanceof v?$.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(($,Y)=>$.intersect(Y).toNeverIfDisjoint(),R.intrinsic.unknown.internal);if(W.branches.length===0)A(e7(`keyof ${this.expression}`));return this._keyof=this.$.finalize(W)}get props(){if(this.branches.length!==1)return A(OE(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(W){let $=this.$.parseDefinition(W);return this.$.schema($.distribute((Y)=>this.applyStructuralOperation("merge",[NF(Y)??A(RF("merge",Y.expression))])))}applyStructuralOperation(W,$){return this.distribute((Y)=>{if(Y.equals(R.intrinsic.object)&&W!=="merge")return Y;let X=NF(Y);if(!X)A(RF(W,Y.expression));if(W==="keyof")return X.keyof();if(W==="get")return X.get(...$);if(W==="props")return X.props;let G=W==="required"?"require":W==="partial"?"optionalize":W;return this.$.node("intersection",{...Y.inner,structure:X[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((Y)=>Y.extends($)))}exclude(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((Y)=>!Y.extends($)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(W){return!(this.intersect(W)instanceof v)}extends(W){let $=this.intersect(W);return!($ instanceof v)&&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 r6(this,W,null),[this,"=",W]}from(W){return this.assert(W)}_pipe(...W){let $=W.reduce((Y,X)=>Y.rawPipeOnce(X),this);return this.$.finalize($)}tryPipe(...W){let $=W.reduce((Y,X)=>Y.rawPipeOnce(d(X,"root")?X:(G,J)=>{try{return X(G,J)}catch(H){return J.error({code:"predicate",predicate:X,actual:`aborted due to error:
|
|
105
|
-
${
|
|
106
|
-
`})}}),this);return this.$.finalize(
|
|
107
|
-
${
|
|
108
|
-
Seen: [${
|
|
109
|
-
Resolution: ${
|
|
110
|
-
\u25E6 `)}`,problem:(
|
|
111
|
-
${
|
|
112
|
-
Left: ${
|
|
113
|
-
Right: ${
|
|
126
|
+
`);class B6{path=[];errors=new p4(this);root;config;queuedMorphs=[];branches=[];seen={};constructor($,T){this.root=$,this.config=T}get data(){let $=this.root;for(let T of this.path)$=$?.[T];return $}get propString(){return H1(this.path)}reject($){return this.error($),!1}mustBe($){return this.error($),!1}error($){let T=typeof $==="object"?$.code?$:{...$,code:"predicate"}:{code:"predicate",expected:$};return this.errorFromContext(T)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs($){let T={path:new ZX(...this.path),morphs:$};if(this.currentBranch)this.currentBranch.queuedMorphs.push(T);else this.queuedMorphs.push(T)}finalize($){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 $?$(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($){return this.errorFromContext($)}errorFromContext($){let T=new o1($,this);if(this.currentBranch)this.currentBranch.error=T;else this.errors.add(T);return T}applyQueuedMorphs(){while(this.queuedMorphs.length){let $=this.queuedMorphs;this.queuedMorphs=[];for(let{path:T,morphs:W}of $){if(this.errors.affectsPath(T))continue;this.applyMorphsAtPath(T,W)}}}applyMorphsAtPath($,T){let W=$.at(-1),X;if(W!==void 0){X=this.root;for(let Y=0;Y<$.length-1;Y++)X=X[$[Y]]}this.path=[...$];for(let Y of T){let U=v$(Y),G=Y(X===void 0?this.root:X[W],this);if(G instanceof o1){this.errors.add(G);break}if(G instanceof p4){if(!U)this.errors.merge(G);break}if(X===void 0)this.root=G;else X[W]=G;this.applyQueuedMorphs()}}}var d4=($,T,W)=>{if(!W)return T();W.path.push($);let X=T();return W.path.pop(),X};class KX extends S6{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor($,T){super((X,Y,U=this.onFail)=>{if(Y)return this.traverseApply(X,Y),Y.hasError()?Y.errors:Y.data;return this.rootApply(X,U)},{attach:$});this.attachments=$,this.$=T,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((X,Y)=>Cq(X,Y.shallowReferences),[this]);let W=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let X=0;X<this.children.length;X++){if(this.includesTransform||=this.children[X].includesTransform,this.includesContextualPredicate||=this.children[X].includesContextualPredicate,this.isCyclic||=this.children[X].isCyclic,!W){let Y=this.children[X].flatRefs;for(let U=0;U<Y.length;U++){let G=Y[U];if(!this.flatRefs.some((J)=>xV(J,G))){this.flatRefs.push(G);for(let J of G.node.branches)if(J.hasKind("morph")||J.hasKind("intersection")&&J.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:J})}}}Object.assign(this.referencesById,this.children[X].referencesById)}this.flatRefs.sort((X,Y)=>X.path.length>Y.path.length?1:X.path.length<Y.path.length?-1:X.propString>Y.propString?1:X.propString<Y.propString?-1:X.node.expression<Y.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((X)=>X.length===1||X.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((X)=>X.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(X)=>this.traverseAllows(X,new B6(X,this.$.resolvedConfig)):(X)=>this.traverseAllows(X)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(T,W)=>{if(this.allows(T))return T;let X=new B6(T,this.$.resolvedConfig);return this.traverseApply(T,X),X.finalize(W)};case"contextual":return(T,W)=>{let X=new B6(T,this.$.resolvedConfig);return this.traverseApply(T,X),X.finalize(W)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let $=this.$.resolvedConfig.clone;return(T,W)=>{if(this.allows(T))return this.contextFreeMorph($&&(typeof T==="object"&&T!==null||typeof T==="function")?$(T):T);let X=new B6(T,this.$.resolvedConfig);return this.traverseApply(T,X),X.finalize(W)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,O$(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Pq(this.metaJson);cacheGetter($,T){return Object.defineProperty(this,$,{value:T}),T}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=hT(this.kind);precompilation;assert=($,T)=>this($,T,(W)=>W.throw());traverse($,T){return this($,T,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo($){if(!this.includesTransform)return this;let T={};for(let[W,X]of this.innerEntries){let Y=this.impl.keys[W];if(Y.reduceIo)Y.reduceIo($,T,X);else if(Y.child){let U=X;T[W]=I$(U)?U.map((G)=>G[$]):U[$]}else T[W]=X}return this.$.node(this.kind,T)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals($){let T=v$($)?$:this.$.parseDefinition($);return this.innerHash===T.innerHash}ifEquals($){return this.equals($)?this:void 0}hasKind($){return this.kind===$}assertHasKind($){if(this.kind!==$)v0(`${this.kind} node was not of asserted kind ${$}`);return this}hasKindIn(...$){return $.includes(this.kind)}assertHasKindIn(...$){if(!J1($,this.kind))v0(`${this.kind} node was not one of asserted kinds ${$}`);return this}isBasis(){return J1(kV,this.kind)}isConstraint(){return J1(QU,this.kind)}isStructural(){return J1(bT,this.kind)}isRefinement(){return J1(V_,this.kind)}isRoot(){return J1(fT,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit($){return this.hasKind("unit")&&this.allows($)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select($){let T=VX.normalize($);return this._select(T)}_select($){let T=VX.applyBoundary[$.boundary??"references"](this);if($.kind)T=T.filter((W)=>W.kind===$.kind);if($.where)T=T.filter($.where);return VX.applyMethod[$.method??"filter"](T,this,$)}transform($,T){return this._transform($,this._createTransformContext(T))}_createTransformContext($){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:$?.prereduced??!1},undeclaredKeyHandling:void 0,...$}}_transform($,T){let W=T.bindScope??this.$;if(T.seen[this.id])return this.$.lazilyResolve(T.seen[this.id]);if(T.shouldTransform?.(this,T)===!1)return this;let X;if(T.seen[this.id]=()=>X,this.hasKind("structure")&&this.undeclared!==T.undeclaredKeyHandling)T={...T,undeclaredKeyHandling:this.undeclared};let Y=Y$(this.inner,(w,H)=>{if(!this.impl.keys[w].child)return[w,H];let _=H;if(!I$(_)){let D=_._transform($,T);return D?[w,D]:[]}if(_.length===0)return[w,H];let F=_.flatMap((D)=>{return D._transform($,T)??[]});return F.length?[w,F]:[]});delete T.seen[this.id];let U=Object.assign(Y,{meta:this.meta}),G=T.selected&&!T.selected.includes(this)?U:$(this.kind,U,T);if(G===null)return null;if(v$(G))return X=G;let J=Object.keys(G);if((J.length===0||J.length===1&&J[0]==="meta")&&!m6(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in G))return T.undeclaredKeyHandling?{...G,value:I.intrinsic.unknown}:null;if(this.kind==="morph")G.in??=I.intrinsic.unknown;return X=W.node(this.kind,G,T.parseOptions)}configureReferences($,T="references"){let W=VX.normalize(T),X=typeof $==="string"?(J,z)=>({...z,meta:{...z.meta,description:$}}):typeof $==="function"?(J,z)=>({...z,meta:$(z.meta)}):(J,z)=>({...z,meta:{...z.meta,...$}});if(W.boundary==="self")return this.$.node(this.kind,X(this.kind,{...this.inner,meta:this.meta}));let Y=this._select(W),U=Y&&m1(Y),G=W.boundary==="child"?(J,z)=>z.root.children.includes(J):W.boundary==="shallow"?(J)=>J.kind!=="structure":()=>!0;return this.$.finalize(this.transform(X,{shouldTransform:G,selected:U}))}}var VX={applyBoundary:{self:($)=>[$],child:($)=>[...$.children],shallow:($)=>[...$.shallowReferences],references:($)=>[...$.references]},applyMethod:{filter:($)=>$,assertFilter:($,T,W)=>{if($.length===0)v0(jV(T,W));return $},find:($)=>$[0],assertFind:($,T,W)=>{if($.length===0)v0(jV(T,W));return $[0]}},normalize:($)=>typeof $==="function"?{boundary:"references",method:"filter",where:$}:typeof $==="string"?z4($,VX.applyBoundary)?{method:"filter",boundary:$}:{boundary:"references",method:"filter",kind:$}:{boundary:"references",method:"filter",...$}},jV=($,T)=>`${$} had no references matching ${U$(T)}.`,kq=($)=>H1($,{stringifyNonKey:(T)=>T.expression}),qq=/"(\$ark\.[^"]+)"/g,Pq=($)=>JSON.stringify($).replaceAll(qq,"$1"),R6=($,T)=>({path:$,node:T,propString:kq($)}),xV=($,T)=>$.propString===T.propString&&$.node.equals(T.node),M_=($,T)=>g6($,T,{isEqual:xV}),Cq=($,T)=>g6($,T,{isEqual:(W,X)=>W.equals(X)});class f extends Array{static init($,T,W,X){return new f({kind:$,l:T,r:W,path:X?.path??[],optional:X?.optional??!1})}add($,T,W,X){return this.push({kind:$,l:T,r:W,path:X?.path??[],optional:X?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:$,l:T,r:W}=this[0],X=H1($);return N_(`Intersection${X&&` at ${X}`} of ${bV(T,W)}`)}return`The following intersections result in unsatisfiable types:
|
|
127
|
+
\u2022 ${this.map(({path:$,l:T,r:W})=>`${$}: ${bV(T,W)}`).join(`
|
|
128
|
+
\u2022 `)}`}throw(){return L(this.describeReasons())}invert(){let $=this.map((T)=>({...T,l:T.r,r:T.l}));if(!($ instanceof f))return new f(...$);return $}withPrefixKey($,T){return this.map((W)=>({...W,path:[$,...W.path],optional:W.optional||T==="optional"}))}toNeverIfDisjoint(){return I.intrinsic.never}}var bV=($,T)=>`${A_($)} and ${A_(T)}`,A_=($)=>v$($)?$.expression:I$($)?$.map(A_).join(" | ")||"never":String($),N_=($)=>`${$} results in an unsatisfiable type`;var gT={},o4=($,T,W)=>j$($,T,{$:W,invert:!1,pipe:!1}),EX=($,T,W)=>j$($,T,{$:W,invert:!1,pipe:!0}),j$=($,T,W)=>{let X=W.pipe?"|>":"&",Y=`${$.hash}${X}${T.hash}`;if(gT[Y]!==void 0)return gT[Y];if(!W.pipe){let J=`${T.hash}${X}${$.hash}`;if(gT[J]!==void 0){let z=gT[J],w=z instanceof f?z.invert():z;return gT[Y]=w,w}}let U=!W.pipe||!$.includesTransform&&!T.includesTransform;if(U&&$.equals(T))return $;let G=U?L_($,T,W):$.hasKindIn(...fT)?vq($,T,W):L_($,T,W);if(v$(G)){if($.equals(G))G=$;else if(T.equals(G))G=T}return gT[Y]=G,G},L_=($,T,W)=>{let X=$.precedence<T.precedence?$.kind:T.kind,Y=$.impl.intersections[T.kind]??T.impl.intersections[$.kind];if(Y===void 0)return null;else if(X===$.kind)return Y($,T,W);else{let U=Y(T,$,{...W,invert:!W.invert});if(U instanceof f)U=U.invert();return U}},vq=($,T,W)=>$.includesTransform||T.includesTransform?W.invert?fV(T,$,W):fV($,T,W):L_($,T,W),fV=($,T,W)=>$.distribute((X)=>jq(X,T,W),(X)=>{let Y=X.filter(v$);if(Y.length===0)return f.init("union",$.branches,T.branches);if(Y.length<$.branches.length||!$.branches.every((J,z)=>J.in.equals(Y[z].in)))return W.$.parseSchema(Y);let U;if(Y.length===1){let J=Y[0];if(!U)return J;return W.$.node("morph",{...J.inner,in:J.in.configure(U,"self")})}let G={branches:Y};if(U)G.meta=U;return W.$.parseSchema(G)}),jq=($,T,W)=>{if($.hasKind("morph")){let Y=[...$.morphs];if($.lastMorphIfNode){let U=j$($.lastMorphIfNode,T,W);if(U instanceof f)return U;Y[Y.length-1]=U}else Y.push(T);return W.$.node("morph",{morphs:Y,in:$.inner.in})}if(T.hasKind("morph")){let Y=j$($,T.in,W);if(Y instanceof f)return Y;return W.$.node("morph",{morphs:[T],in:Y})}return W.$.node("morph",{morphs:[T],in:$})};class F6 extends KX{constructor($,T){super($,T);Object.defineProperty(this,C4,{value:"constraint",enumerable:!1})}impliedSiblings;intersect($){return o4(this,$,this.$)}}class Q1 extends F6{traverseApply=($,T)=>{if(!this.traverseAllows($,T))T.errorFromNodeContext(this.errorContext)};compile($){if($.traversalKind==="Allows")$.return(this.compiledCondition);else $.if(this.compiledNegation,()=>$.line(`${$.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return d1(this.errorContext)}}var S4=($)=>(T,W)=>{if(I$(T)){if(T.length===0)return;let Y=T.map((U)=>W.$.node($,U));if($==="predicate")return Y;return Y.sort((U,G)=>U.hash<G.hash?-1:1)}let X=W.$.node($,T);return X.hasOpenIntersection()?[X]:X},mT=($)=>{let T=$.r.shift();if(!T){let X=$.l.length===0&&$.kind==="structure"?I.intrinsic.unknown.internal:$.ctx.$.node($.kind,Object.assign($.baseInner,xq($.l)),{prereduced:!0});for(let Y of $.roots){if(X instanceof f)return X;X=j$(Y,X,$.ctx)}return X}let W=!1;for(let X=0;X<$.l.length;X++){let Y=j$($.l[X],T,$.ctx);if(Y===null)continue;if(Y instanceof f)return Y;if(!W){if(Y.isRoot())return $.roots.push(Y),$.l.splice(X),mT($);$.l[X]=Y,W=!0}else if(!$.l.includes(Y))return O$(`Unexpectedly encountered multiple distinct intersection results for refinement ${Y}`)}if(!W)$.l.push(T);if($.kind==="intersection"){if(T.impliedSiblings)for(let X of T.impliedSiblings)g6($.r,X)}return mT($)},cT=($)=>{return Object.entries($).flatMap(([W,X])=>(W in ZU)?X:[]).sort((W,X)=>W.precedence<X.precedence?-1:W.precedence>X.precedence?1:W.kind==="predicate"&&X.kind==="predicate"?0:W.hash<X.hash?-1:1)},xq=($)=>{let T={};for(let W of $)if(W.hasOpenIntersection())T[W.kind]=Q$(T[W.kind],W);else{if(T[W.kind])return O$(`Unexpected intersection of closed refinements of kind ${W.kind}`);T[W.kind]=W}return T},yV=(...$)=>L(hV(...$)),hV=($,T,W)=>{let X=W.hasKind("morph")?"a morph":W.isUnknown()?"unknown":W.exclude(T).defaultShortDescription;return`${QV($)} operand must be ${T.description} (was ${X})`};var gV=($,T,W)=>new l1($,T,W,W,null);class OU extends S6{}class l1 extends S6{[C4]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor($,T,W,X,Y){super((...U)=>{let G=Y$(this.names,(J,z)=>{let w=this.arg$.parse(U[J]);if(!w.extends(this.constraints[J]))L(bq(z,this.constraints[J].expression,w.expression));return[z,w]});if(this.defIsLazy()){let J=this.bodyDef(G);return this.$.parse(J)}return this.$.parse(T,{args:G})});this.paramDefs=$,this.bodyDef=T,this.$=W,this.arg$=X,this.hkt=Y,this.description=Y?new Y().description??`a generic type for ${Y.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof OU}cacheGetter($,T){return Object.defineProperty(this,$,{value:T}),T}get json(){return this.cacheGetter("json",{params:this.params.map(($)=>$[1].isUnknown()?$[0]:[$[0],$[1].json]),body:SV(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map(($)=>typeof $==="string"?[$,I.intrinsic.unknown]:[$[0],this.$.parse($[1])]))}get names(){return this.cacheGetter("names",this.params.map(($)=>$[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map(($)=>$[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var bq=($,T,W)=>`${$} must be assignable to ${T} (was ${W})`;var fq=G$({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:($)=>typeof $==="function"?{predicate:$}:$,defaults:{description:($)=>`valid according to ${$.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class mV extends F6{serializedPredicate=d$(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=d1(this.errorContext);traverseApply=($,T)=>{if(!this.predicate($,T.external)&&!T.hasError())T.errorFromNodeContext(this.errorContext)};compile($){if($.traversalKind==="Allows"){$.return(this.compiledCondition);return}$.if(`${this.compiledNegation} && !ctx.hasError()`,()=>$.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema($,T){return T.fallback.predicate({code:"predicate",base:$,predicate:this.predicate})}}var S_={implementation:fq,Node:mV};var yq=G$({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:($)=>Number.isInteger($)?$:L(hq($))}},normalize:($)=>typeof $==="number"?{rule:$}:$,hasAssociatedError:!0,defaults:{description:($)=>$.rule===1?"an integer":$.rule===2?"even":`a multiple of ${$.rule}`},intersections:{divisor:($,T,W)=>W.$.node("divisor",{rule:Math.abs($.rule*T.rule/gq($.rule,T.rule))})},obviatesBasisDescription:!0});class cV extends Q1{traverseAllows=($)=>$%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=I.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema($){if($.type="integer",this.rule===1)return $;return $.multipleOf=this.rule,$}}var B_={implementation:yq,Node:cV};var hq=($)=>`divisor must be an integer (was ${$})`,gq=($,T)=>{let W,X=$,Y=T;while(Y!==0)W=Y,Y=X%Y,X=W;return X};class Y6 extends Q1{boundOperandKind=pq[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=dq(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${mq[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?oq(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan($){return(this.limitKind==="upper"?this.numericLimit<$.numericLimit:this.numericLimit>$.numericLimit)||this.numericLimit===$.numericLimit&&this.exclusive===!0&&!$.exclusive}overlapsRange($){if(this.isStricterThan($))return!1;if(this.numericLimit===$.numericLimit&&(this.exclusive||$.exclusive))return!1;return!0}overlapIsUnit($){return this.numericLimit===$.numericLimit&&!this.exclusive&&!$.exclusive}}var mq={"<":">=","<=":">",">":"<=",">=":"<"},cq={min:"max",minLength:"maxLength",after:"before"},VU={parse:($)=>$||void 0},KU=($)=>(T)=>{if(typeof T==="number")return{rule:T};let{exclusive:W,...X}=T;return W?{...X,rule:$==="minLength"?X.rule+1:X.rule-1}:X},EU=($)=>(T)=>{if(typeof T==="number"||typeof T==="string"||T instanceof Date)return{rule:T};let{exclusive:W,...X}=T;if(!W)return X;let Y=typeof X.rule==="number"?X.rule:typeof X.rule==="string"?new Date(X.rule).valueOf():X.rule.valueOf();return W?{...X,rule:$==="after"?Y+1:Y-1}:X},MU=($)=>typeof $==="string"||typeof $==="number"?new Date($):$,uq=($,T)=>`${$} bound must be a positive integer (was ${T})`,uT=($)=>(T)=>{if(!Number.isInteger(T)||T<0)L(uq($,T));return T},pq={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},dq=($,T)=>`${z4($,cq)?">":"<"}${T?"":"="}`,oq=($)=>typeof $==="string"?$:new Date($).toLocaleString(),uV=($)=>`Bounded expression ${$} must be exactly one of number, string, Array, or Date`;var lq=G$({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:MU,serialize:($)=>$.toISOString()}},normalize:EU("after"),defaults:{description:($)=>`${$.collapsibleLimitString} or later`,actual:f0},intersections:{after:($,T)=>$.isStricterThan(T)?$:T}});class pV extends Y6{impliedBasis=I.intrinsic.Date.internal;collapsibleLimitString=f0(this.rule);traverseAllows=($)=>$>=this.rule;reduceJsonSchema($,T){return T.fallback.date({code:"date",base:$,after:this.rule})}}var R_={implementation:lq,Node:pV};var rq=G$({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:MU,serialize:($)=>$.toISOString()}},normalize:EU("before"),defaults:{description:($)=>`${$.collapsibleLimitString} or earlier`,actual:f0},intersections:{before:($,T)=>$.isStricterThan(T)?$:T,after:($,T,W)=>$.overlapsRange(T)?$.overlapIsUnit(T)?W.$.node("unit",{unit:$.rule}):null:f.init("range",$,T)}});class dV extends Y6{collapsibleLimitString=f0(this.rule);traverseAllows=($)=>$<=this.rule;impliedBasis=I.intrinsic.Date.internal;reduceJsonSchema($,T){return T.fallback.date({code:"date",base:$,before:this.rule})}}var I_={implementation:rq,Node:dV};var iq=G$({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:uT("exactLength")}},normalize:($)=>typeof $==="number"?{rule:$}:$,hasAssociatedError:!0,defaults:{description:($)=>`exactly length ${$.rule}`,actual:($)=>`${$.length}`},intersections:{exactLength:($,T,W)=>f.init("unit",W.$.node("unit",{unit:$.rule}),W.$.node("unit",{unit:T.rule}),{path:["length"]}),minLength:($,T)=>$.rule>=T.rule?$:f.init("range",$,T),maxLength:($,T)=>$.rule<=T.rule?$:f.init("range",$,T)}});class oV extends Q1{traverseAllows=($)=>$.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=I.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema($){switch($.type){case"string":return $.minLength=this.rule,$.maxLength=this.rule,$;case"array":return $.minItems=this.rule,$.maxItems=this.rule,$;default:return y$.throwInternalOperandError("exactLength",$)}}}var k_={implementation:iq,Node:oV};var nq=G$({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:VU},normalize:($)=>typeof $==="number"?{rule:$}:$,defaults:{description:($)=>{if($.rule===0)return $.exclusive?"negative":"non-positive";return`${$.exclusive?"less than":"at most"} ${$.rule}`}},intersections:{max:($,T)=>$.isStricterThan(T)?$:T,min:($,T,W)=>$.overlapsRange(T)?$.overlapIsUnit(T)?W.$.node("unit",{unit:$.rule}):null:f.init("range",$,T)},obviatesBasisDescription:!0});class lV extends Y6{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?($)=>$<this.rule:($)=>$<=this.rule;reduceJsonSchema($){if(this.exclusive)$.exclusiveMaximum=this.rule;else $.maximum=this.rule;return $}}var q_={implementation:nq,Node:lV};var tq=G$({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:uT("maxLength")}},reduce:($,T)=>$.rule===0?T.node("exactLength",$):void 0,normalize:KU("maxLength"),defaults:{description:($)=>`at most length ${$.rule}`,actual:($)=>`${$.length}`},intersections:{maxLength:($,T)=>$.isStricterThan(T)?$:T,minLength:($,T,W)=>$.overlapsRange(T)?$.overlapIsUnit(T)?W.$.node("exactLength",{rule:$.rule}):null:f.init("range",$,T)}});class rV extends Y6{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=($)=>$.length<=this.rule;reduceJsonSchema($){switch($.type){case"string":return $.maxLength=this.rule,$;case"array":return $.maxItems=this.rule,$;default:return y$.throwInternalOperandError("maxLength",$)}}}var P_={implementation:tq,Node:rV};var aq=G$({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:VU},normalize:($)=>typeof $==="number"?{rule:$}:$,defaults:{description:($)=>{if($.rule===0)return $.exclusive?"positive":"non-negative";return`${$.exclusive?"more than":"at least"} ${$.rule}`}},intersections:{min:($,T)=>$.isStricterThan(T)?$:T},obviatesBasisDescription:!0});class iV extends Y6{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?($)=>$>this.rule:($)=>$>=this.rule;reduceJsonSchema($){if(this.exclusive)$.exclusiveMinimum=this.rule;else $.minimum=this.rule;return $}}var C_={implementation:aq,Node:iV};var sq=G$({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:uT("minLength")}},reduce:($)=>$.rule===0?I.intrinsic.unknown:void 0,normalize:KU("minLength"),defaults:{description:($)=>$.rule===1?"non-empty":`at least length ${$.rule}`,actual:($)=>$.length===0?"":`${$.length}`},intersections:{minLength:($,T)=>$.isStricterThan(T)?$:T}});class nV extends Y6{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=($)=>$.length>=this.rule;reduceJsonSchema($){switch($.type){case"string":return $.minLength=this.rule,$;case"array":return $.minItems=this.rule,$;default:return y$.throwInternalOperandError("minLength",$)}}}var v_={implementation:sq,Node:nV};var tV={min:C_.implementation,max:q_.implementation,minLength:v_.implementation,maxLength:P_.implementation,exactLength:k_.implementation,after:R_.implementation,before:I_.implementation},aV={min:C_.Node,max:q_.Node,minLength:v_.Node,maxLength:P_.Node,exactLength:k_.Node,after:R_.Node,before:I_.Node};var eq=G$({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:($)=>typeof $==="string"?{rule:$}:$ instanceof RegExp?$.flags?{rule:$.source,flags:$.flags}:{rule:$.source}:$,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:($)=>`matched by ${$.rule}`},intersections:{pattern:()=>null}});class sV extends Q1{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=I.intrinsic.string.internal;reduceJsonSchema($,T){if($.pattern)return T.fallback.patternIntersection({code:"patternIntersection",base:$,pattern:this.rule});return $.pattern=this.rule,$}}var j_={implementation:eq,Node:sV};var MX=($,T)=>{let W=$P($);if(T&&!T.includes(W))return L(`Root of kind ${W} should be one of ${T}`);return W},$P=($)=>{if(o($,"root"))return $.kind;if(typeof $==="string")return $[0]==="$"?"alias":($ in u4)?"domain":"proto";if(typeof $==="function")return"proto";if(typeof $!=="object"||$===null)return L(eV($));if("morphs"in $)return"morph";if("branches"in $||I$($))return"union";if("unit"in $)return"unit";if("reference"in $)return"alias";let T=Object.keys($);if(T.length===0||T.some((W)=>(W in ZU)))return"intersection";if("proto"in $)return"proto";if("domain"in $)return"domain";return L(eV($))},eV=($)=>`${U$($)} is not a valid type schema`,$K={},TP=($)=>I$($)?$.map((T)=>T.collapsibleJson):$.collapsibleJson,v4={};I.nodesByRegisteredId=v4;var x_=($)=>{return $K[$]??=0,`${$}${++$K[$]}`},b_=($)=>{let T=pT[$.kind],W=T.applyConfig?.($.def,$.$.resolvedConfig)??$.def,X={},{meta:Y,...U}=W,G=Y===void 0?{}:typeof Y==="string"?{description:Y}:Y,J=Y_(U).sort(([w],[H])=>yT(w)?yT(H)?hT(w)-hT(H):1:yT(H)?-1:w<H?-1:1).filter(([w,H])=>{if(w.startsWith("meta.")){let _=w.slice(5);return G[_]=H,!1}return!0});for(let w of J){let H=w[0],_=T.keys[H];if(!_)return L(`Key ${H} is not valid on ${$.kind} schema`);let F=_.parse?_.parse(w[1],$):w[1];if(F!==X6&&(F!==void 0||_.preserveUndefined))X[H]=F}if(T.reduce&&!$.prereduced){let w=T.reduce(X,$.$);if(w){if(w instanceof f)return w.throw();return WP(w,G)}}return f_({id:$.id,kind:$.kind,inner:X,meta:G,$:$.$})},f_=({id:$,kind:T,inner:W,meta:X,$:Y,ignoreCache:U})=>{let G=pT[T],J=Y_(W),z=[],w={};for(let[P,A]of J){let N=G.keys[P],k=N.serialize??(N.child?TP:H6);if(w[P]=k(A),N.child===!0){let y=A;if(I$(y))z.push(...y);else z.push(y)}else if(typeof N.child==="function")z.push(...N.child(A))}if(G.finalizeInnerJson)w=G.finalizeInnerJson(w);let H={...w},_={};if(!m6(X))_=Y$(X,(P,A)=>[P,P==="examples"?A:H6(A)]),H.meta=AU(_,"description",!0);w=AU(w,G.collapsibleKey,!1);let F=JSON.stringify({kind:T,...w});H=AU(H,G.collapsibleKey,!1);let D=AU(H,G.collapsibleKey,!0),V=JSON.stringify({kind:T,...H});if(Y.nodesByHash[V]&&!U)return Y.nodesByHash[V];let E={id:$,kind:T,impl:G,inner:W,innerEntries:J,innerJson:w,innerHash:F,meta:X,metaJson:_,json:H,hash:V,collapsibleJson:D,children:z};if(T!=="intersection"){for(let P in W)if(P!=="in"&&P!=="out")E[P]=W[P]}let R=new WK[T](E,Y);return Y.nodesByHash[V]=R},TK=($,T)=>{if($.id===T)return $;if(v$(v4[T]))O$(`Unexpected attempt to overwrite node id ${T}`);return f_({id:T,kind:$.kind,inner:$.inner,meta:$.meta,$:$.$,ignoreCache:!0})},WP=($,T,W)=>{if(W&&v$(v4[W]))O$(`Unexpected attempt to overwrite node id ${W}`);return f_({id:W??x_(T.alias??$.kind),kind:$.kind,inner:$.inner,meta:T,$:$.$})},AU=($,T,W)=>{let X=Object.keys($);if(X.length===1&&X[0]===T){let Y=$[T];if(W)return Y;if(c4(Y,"object")&&(Object.keys(Y).length===1||Array.isArray(Y)))return Y}return $};var AX=($,T,W)=>{if($.key!==T.key)return null;let X=$.key,Y=j$($.value,T.value,W),U=$.required||T.required?"required":"optional";if(Y instanceof f)if(U==="optional")Y=I.intrinsic.never.internal;else return Y.withPrefixKey($.key,$.required&&T.required?"required":"optional");if(U==="required")return W.$.node("required",{key:X,value:Y});let G=$.hasDefault()?T.hasDefault()?$.default===T.default?$.default:L(y_($.default,T.default)):$.default:T.hasDefault()?T.default:X6;return W.$.node("optional",{key:X,value:Y,default:G})};class NX extends F6{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=I.intrinsic.object.internal;serializedKey=F1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Q$(this.value.flatRefs.map(($)=>R6([this.key,...$.path],$.node)),R6([this.key],this.value));_transform($,T){T.path.push(this.key);let W=super._transform($,T);return T.path.pop(),W}hasDefault(){return"default"in this.inner}traverseAllows=($,T)=>{if(this.key in $)return d4(this.key,()=>this.value.traverseAllows($[this.key],T),T);return this.optional};traverseApply=($,T)=>{if(this.key in $)d4(this.key,()=>this.value.traverseApply($[this.key],T),T);else if(this.hasKind("required"))T.errorFromNodeContext(this.errorContext)};compile($){if($.if(`${this.serializedKey} in data`,()=>$.traverseKey(this.serializedKey,`data${$.prop(this.key)}`,this.value)),this.hasKind("required"))$.else(()=>$.traversalKind==="Apply"?$.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):$.return(!1));if($.traversalKind==="Allows")$.return(!0)}}var y_=($,T)=>`Invalid intersection of default values ${U$($)} & ${U$(T)}`;var XP=G$({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:($,T)=>T.$.parseSchema($)},default:{preserveUndefined:!0}},normalize:($)=>$,reduce:($,T)=>{if(T.resolvedConfig.exactOptionalPropertyTypes===!1){if(!$.value.allows(void 0))return T.node("optional",{...$,value:$.value.or(n.undefined)},{prereduced:!0})}},defaults:{description:($)=>`${$.compiledKey}?: ${$.value.description}`},intersections:{optional:AX}});class XK extends NX{constructor(...$){super(...$);if("default"in this.inner)SX(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:$,...T}=this.inner;return this.cacheGetter("outProp",this.$.node("required",T,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${U$(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=UP(this);defaultValueMorphRef=this.defaultValueMorph&&d$(this.defaultValueMorph)}var LX={implementation:XP,Node:XK},YP={},UP=($)=>{if(!$.hasDefault())return;let T=`{${$.compiledKey}: ${$.value.id} = ${H6($.default)}}`;return YP[T]??=h_($.key,$.value,$.default)},h_=($,T,W)=>{if(typeof W==="function")return T.includesTransform?(Y,U)=>{return d4($,()=>T(Y[$]=W(),U),U),Y}:(Y)=>{return Y[$]=W(),Y};let X=T.includesTransform?T.assert(W):W;return c4(X,"object")?(Y,U)=>{return d4($,()=>T(Y[$]=W,U),U),Y}:(Y)=>{return Y[$]=X,Y}},SX=($,T,W)=>{let X=c1(T);if(c4(T,"object")&&!X)L(GP(W));let Y=$.in(X?T():T);if(Y instanceof p4){if(W===null)L(`Default ${Y.summary}`);let U=Y.transform((G)=>G.transform((J)=>({...J,prefixPath:[W]})));L(`Default for ${U.summary}`)}return T},GP=($)=>{return`Non-primitive default ${$===null?"":typeof $==="number"?`for value at [${$}] `:`for ${F1($)} `}must be specified as a function like () => ({my: 'object'})`};class Q6 extends KX{constructor($,T){super($,T);Object.defineProperty(this,C4,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:($)=>{let T=this($);if(T instanceof p4)return T;return{value:T}}}}as(){return this}brand($){if($==="")return L(JP);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute($,T){let W=this.branches.map($);return T?.(W)??W}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema($={}){let T=K_(this.$.resolvedConfig.toJsonSchema,$);T.useRefs||=this.isCyclic;let W=typeof T.dialect==="string"?{$schema:T.dialect}:{};if(Object.assign(W,this.toJsonSchemaRecurse(T)),T.useRefs)W.$defs=Y$(this.references,(X,Y)=>Y.isRoot()&&!Y.alwaysExpandJsonSchema?[Y.id,Y.toResolvedJsonSchema(T)]:[]);return W}toJsonSchemaRecurse($){if($.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema($)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema($){let T=this.innerToJsonSchema($);return Object.assign(T,this.metaJson)}intersect($){let T=this.$.parseDefinition($),W=this.rawIntersect(T);if(W instanceof f)return W;return this.$.finalize(W)}rawIntersect($){return o4(this,$,this.$)}toNeverIfDisjoint(){return this}and($){let T=this.intersect($);return T instanceof f?T.throw():T}rawAnd($){let T=this.rawIntersect($);return T instanceof f?T.throw():T}or($){let T=this.$.parseDefinition($);return this.$.finalize(this.rawOr(T))}rawOr($){let T=[...this.branches,...$.branches];return this.$.node("union",T)}map($){return this.$.schema(this.applyStructuralOperation("map",[$]))}pick(...$){return this.$.schema(this.applyStructuralOperation("pick",$))}omit(...$){return this.$.schema(this.applyStructuralOperation("omit",$))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let $=this.applyStructuralOperation("keyof",[]).reduce((T,W)=>T.intersect(W).toNeverIfDisjoint(),I.intrinsic.unknown.internal);if($.branches.length===0)L(N_(`keyof ${this.expression}`));return this._keyof=this.$.finalize($)}get props(){if(this.branches.length!==1)return L(wP(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge($){let T=this.$.parseDefinition($);return this.$.schema(T.distribute((W)=>this.applyStructuralOperation("merge",[YK(W)??L(UK("merge",W.expression))])))}applyStructuralOperation($,T){return this.distribute((W)=>{if(W.equals(I.intrinsic.object)&&$!=="merge")return W;let X=YK(W);if(!X)L(UK($,W.expression));if($==="keyof")return X.keyof();if($==="get")return X.get(...T);if($==="props")return X.props;let Y=$==="required"?"require":$==="partial"?"optionalize":$;return this.$.node("intersection",{...W.inner,structure:X[Y](...T)})})}get(...$){if($[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",$))}extract($){let T=this.$.parseDefinition($);return this.$.schema(this.branches.filter((W)=>W.extends(T)))}exclude($){let T=this.$.parseDefinition($);return this.$.schema(this.branches.filter((W)=>!W.extends(T)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps($){return!(this.intersect($)instanceof f)}extends($){let T=this.intersect($);return!(T instanceof f)&&this.equals(T)}ifExtends($){return this.extends($)?this:void 0}subsumes($){return this.$.parseDefinition($).extends(this)}configure($,T="shallow"){return this.configureReferences($,T)}describe($,T="shallow"){return this.configure({description:$},T)}optional(){return[this,"?"]}default($){return SX(this,$,null),[this,"=",$]}from($){return this.assert($)}_pipe(...$){let T=$.reduce((W,X)=>W.rawPipeOnce(X),this);return this.$.finalize(T)}tryPipe(...$){let T=$.reduce((W,X)=>W.rawPipeOnce(o(X,"root")?X:(Y,U)=>{try{return X(Y,U)}catch(G){return U.error({code:"predicate",predicate:X,actual:`aborted due to error:
|
|
129
|
+
${G}
|
|
130
|
+
`})}}),this);return this.$.finalize(T)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to($){return this.$.finalize(this.toNode(this.$.parseDefinition($)))}toNode($){let T=EX(this,$,this.$);if(T instanceof f)return T.throw();return T}rawPipeOnce($){if(o($,"root"))return this.toNode($);return this.distribute((T)=>T.hasKind("morph")?this.$.node("morph",{in:T.inner.in,morphs:[...T.morphs,$]}):this.$.node("morph",{in:T,morphs:[$]}),this.$.parseSchema)}narrow($){return this.constrainOut("predicate",$)}constrain($,T){return this._constrain("root",$,T)}constrainIn($,T){return this._constrain("in",$,T)}constrainOut($,T){return this._constrain("out",$,T)}_constrain($,T,W){let X=this.$.node(T,W);if(X.isRoot())return X.isUnknown()?this:O$(`Unexpected constraint node ${X}`);let Y=$==="root"?this:this[$];if(Y.hasKind("morph")||X.impliedBasis&&!Y.extends(X.impliedBasis))return yV(T,X.impliedBasis,this);let U=this.$.node("intersection",{[X.kind]:X}),G=$==="out"?EX(this,U,this.$):o4(this,U,this.$);if(G instanceof f)G.throw();return this.$.finalize(G)}onUndeclaredKey($){let T=typeof $==="string"?$:$.rule,W=typeof $==="string"?!1:$.deep;return this.$.finalize(this.transform((X,Y)=>X==="structure"?T==="ignore"?WV(Y,{undeclared:1}):{...Y,undeclared:T}:Y,W?void 0:{shouldTransform:(X)=>!J1(bT,X.kind)}))}hasEqualMorphs($){if(!this.includesTransform&&!$.includesTransform)return!0;if(!z1(this.shallowMorphs,$.shallowMorphs))return!1;if(!z1(this.flatMorphs,$.flatMorphs,{isEqual:(T,W)=>T.propString===W.propString&&(T.node.hasKind("morph")&&W.node.hasKind("morph")?T.node.hasEqualMorphs(W.node):T.node.hasKind("intersection")&&W.node.hasKind("intersection")?T.node.structure?.structuralMorphRef===W.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey($){return this.onUndeclaredKey({rule:$,deep:!0})}filter($){return this.constrainIn("predicate",$)}divisibleBy($){return this.constrain("divisor",$)}matching($){return this.constrain("pattern",$)}atLeast($){return this.constrain("min",$)}atMost($){return this.constrain("max",$)}moreThan($){return this.constrain("min",dT($))}lessThan($){return this.constrain("max",dT($))}atLeastLength($){return this.constrain("minLength",$)}atMostLength($){return this.constrain("maxLength",$)}moreThanLength($){return this.constrain("minLength",dT($))}lessThanLength($){return this.constrain("maxLength",dT($))}exactlyLength($){return this.constrain("exactLength",$)}atOrAfter($){return this.constrain("after",$)}atOrBefore($){return this.constrain("before",$)}laterThan($){return this.constrain("after",dT($))}earlierThan($){return this.constrain("before",dT($))}}var JP="Expected a non-empty brand name after #",dT=($)=>typeof $==="object"&&!($ instanceof Date)?{...$,exclusive:!0}:{rule:$,exclusive:!0},BX=($,T)=>o(T,"root")?o($,"root")?$.extends(T):T.allows($):o($,"root")?$.hasUnit(T):T===$,YK=($)=>{if($.hasKind("morph"))return null;if($.hasKind("intersection"))return $.inner.structure??($.basis?.domain==="object"?$.$.bindReference(I.intrinsic.emptyStructure):null);if($.isBasis()&&$.domain==="object")return $.$.bindReference(I.intrinsic.emptyStructure);return null},wP=($)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
131
|
+
${$}`,UK=($,T)=>`${$} operand must be an object (was ${T})`;var c6=($,T)=>Y$(DU($),(W,X)=>[X,T]);var zP=($)=>typeof $==="string"?{reference:$}:$,GK=($)=>$ instanceof f?I.intrinsic.never.internal:$,_P=G$({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:($)=>$.startsWith("$")?$:`$ark.${$}`},resolve:{}},normalize:zP,defaults:{description:($)=>$.reference},intersections:{alias:($,T,W)=>W.$.lazilyResolve(()=>GK(j$($.resolution,T.resolution,W)),`${$.reference}${W.pipe?"=>":"&"}${T.reference}`),...c6("alias",($,T,W)=>{if(T.isUnknown())return $;if(T.isNever())return T;if(T.isBasis()&&!T.overlaps(I.intrinsic.object))return f.init("assignability",I.intrinsic.object,T);return W.$.lazilyResolve(()=>GK(j$($.resolution,T,W)),`${$.reference}${W.pipe?"=>":"&"}${T.id}`)})}});class JK extends Q6{expression=this.reference;structure=void 0;get resolution(){let $=this._resolve();return v4[this.id]=$}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let $=this.reference,T=v4[$],W=[];while(o(T,"context")){if(W.includes(T.id))return L(HP(T.id,W));W.push(T.id),T=v4[T.id]}if(!o(T,"root"))return O$(`Unexpected resolution for reference ${this.reference}
|
|
132
|
+
Seen: [${W.join("->")}]
|
|
133
|
+
Resolution: ${U$(T)}`);return T}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let $=this.reference.slice(1),T=this.$.resolutions[$];if(typeof T==="string")return T;if(o(T,"root"))return T.id;return O$(`Unexpected resolution for reference ${this.reference}: ${U$(T)}`)}get defaultShortDescription(){return u4.object}innerToJsonSchema($){return this.resolution.toJsonSchemaRecurse($)}traverseAllows=($,T)=>{let W=T.seen[this.reference];if(W?.includes($))return!0;return T.seen[this.reference]=Q$(W,$),this.resolution.traverseAllows($,T)};traverseApply=($,T)=>{let W=T.seen[this.reference];if(W?.includes($))return;T.seen[this.reference]=Q$(W,$),this.resolution.traverseApply($,T)};compile($){let T=this.resolutionId;$.if(`ctx.seen.${T} && ctx.seen.${T}.includes(data)`,()=>$.return(!0)),$.if(`!ctx.seen.${T}`,()=>$.line(`ctx.seen.${T} = []`)),$.line(`ctx.seen.${T}.push(data)`),$.return($.invoke(T))}}var HP=($,T)=>`Alias '${$}' has a shallow resolution cycle: ${[...T,$].join("->")}`,RX={implementation:_P,Node:JK};class y0 extends Q6{traverseApply=($,T)=>{if(!this.traverseAllows($,T))T.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return d1(this.errorContext)}compile($){if($.traversalKind==="Allows")$.return(this.compiledCondition);else $.if(this.compiledNegation,()=>$.line(`${$.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var FP=G$({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:($)=>typeof $==="string"?{domain:$}:jT($,"numberAllowsNaN")&&$.domain!=="number"?L(NU.writeBadAllowNanMessage($.domain)):$,applyConfig:($,T)=>$.numberAllowsNaN===void 0&&$.domain==="number"&&T.numberAllowsNaN?{...$,numberAllowsNaN:!0}:$,defaults:{description:($)=>u4[$.domain],actual:($)=>Number.isNaN($)?"NaN":u4[w4($)]},intersections:{domain:($,T)=>$.domain==="number"&&T.domain==="number"?$.numberAllowsNaN?T:$:f.init("domain",$,T)}});class wK extends y0{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?($)=>typeof $==="number"&&!Number.isNaN($):($)=>w4($)===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 u4[this.domain]}innerToJsonSchema($){if(this.domain==="bigint"||this.domain==="symbol")return $.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var NU={implementation:FP,Node:wK,writeBadAllowNanMessage:($)=>`numberAllowsNaN may only be specified with domain "number" (was ${$})`};var QP=G$({kind:"intersection",hasAssociatedError:!0,normalize:($)=>{if(v$($))return $;let{structure:T,...W}=$,X=!!T,Y=T??{},U=Y$(W,(G,J)=>{if(z4(G,qV)){if(X)L(`Flattened structure key ${G} cannot be specified alongside a root 'structure' key.`);return Y[G]=J,[]}return[G,J]});if(o(Y,"constraint")||!m6(Y))U.structure=Y;return U},finalizeInnerJson:({structure:$,...T})=>c4($,"object")?{...$,...T}:T,keys:{domain:{child:!0,parse:($,T)=>T.$.node("domain",$)},proto:{child:!0,parse:($,T)=>T.$.node("proto",$)},structure:{child:!0,parse:($,T)=>T.$.node("structure",$),serialize:($)=>{if(!$.sequence?.minLength)return $.collapsibleJson;let{sequence:T,...W}=$.collapsibleJson,{minVariadicLength:X,...Y}=T,U=Y.variadic&&Object.keys(Y).length===1?Y.variadic:Y;return{...W,sequence:U}}},divisor:{child:!0,parse:S4("divisor")},max:{child:!0,parse:S4("max")},min:{child:!0,parse:S4("min")},maxLength:{child:!0,parse:S4("maxLength")},minLength:{child:!0,parse:S4("minLength")},exactLength:{child:!0,parse:S4("exactLength")},before:{child:!0,parse:S4("before")},after:{child:!0,parse:S4("after")},pattern:{child:!0,parse:S4("pattern")},predicate:{child:!0,parse:S4("predicate")}},reduce:($,T)=>zK({},$,{$:T,invert:!1,pipe:!1}),defaults:{description:($)=>{if($.children.length===0)return"unknown";if($.structure)return $.structure.description;let T=[];if($.basis&&!$.refinements.some((W)=>W.impl.obviatesBasisDescription))T.push($.basis.description);if($.refinements.length){let W=$.refinements.toSorted((X,Y)=>X.kind==="min"&&Y.kind==="max"?-1:0).map((X)=>X.description);T.push(...W)}if($.inner.predicate)T.push(...$.inner.predicate.map((W)=>W.description));return T.join(" and ")},expected:($)=>` \u25E6 ${$.errors.map((T)=>T.expected).join(`
|
|
134
|
+
\u25E6 `)}`,problem:($)=>`(${$.actual}) must be...
|
|
135
|
+
${$.expected}`},intersections:{intersection:($,T,W)=>zK($.inner,T.inner,W),...c6("intersection",($,T,W)=>{if($.children.length===0)return T;let{domain:X,proto:Y,...U}=$.inner,G=Y??X,J=G?j$(G,T,W):T;return J instanceof f?J:$?.basis?.equals(J)?$:$.$.node("intersection",{...U,[J.kind]:J},{prereduced:!0})})}});class _K extends Q6{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter(($)=>$.isRefinement());structure=this.inner.structure;expression=ZP(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema($){return this.children.reduce((T,W)=>W.isBasis()?W.toJsonSchemaRecurse($):W.reduceJsonSchema(T,$),{})}traverseAllows=($,T)=>this.children.every((W)=>W.traverseAllows($,T));traverseApply=($,T)=>{let W=T.currentErrorCount;if(this.basis){if(this.basis.traverseApply($,T),T.currentErrorCount>W)return}if(this.refinements.length){for(let X=0;X<this.refinements.length-1;X++)if(this.refinements[X].traverseApply($,T),T.failFast&&T.currentErrorCount>W)return;if(this.refinements.at(-1).traverseApply($,T),T.currentErrorCount>W)return}if(this.structure){if(this.structure.traverseApply($,T),T.currentErrorCount>W)return}if(this.inner.predicate){for(let X=0;X<this.inner.predicate.length-1;X++)if(this.inner.predicate[X].traverseApply($,T),T.failFast&&T.currentErrorCount>W)return;this.inner.predicate.at(-1).traverseApply($,T)}};compile($){if($.traversalKind==="Allows"){for(let T of this.children)$.check(T);$.return(!0);return}if($.initializeErrorCount(),this.basis){if($.check(this.basis),this.children.length>1)$.returnIfFail()}if(this.refinements.length){for(let T=0;T<this.refinements.length-1;T++)$.check(this.refinements[T]),$.returnIfFailFast();if($.check(this.refinements.at(-1)),this.structure||this.inner.predicate)$.returnIfFail()}if(this.structure){if($.check(this.structure),this.inner.predicate)$.returnIfFail()}if(this.inner.predicate){for(let T=0;T<this.inner.predicate.length-1;T++)$.check(this.inner.predicate[T]),$.returnIfFail();$.check(this.inner.predicate.at(-1))}}}var g_={implementation:QP,Node:_K},ZP=($)=>{let T=$.structure?.expression||`${$.basis&&!$.refinements.some((W)=>W.impl.obviatesBasisExpression)?$.basis.nestableExpression+" ":""}${$.refinements.map((W)=>W.expression).join(" & ")}`||"unknown";if(T==="Array == 0")T="[]";return T},zK=($,T,W)=>{let X={},Y=$.proto??$.domain,U=T.proto??T.domain,G=Y?U?j$(Y,U,W):Y:U;if(G instanceof f)return G;if(G)X[G.kind]=G;return mT({kind:"intersection",baseInner:X,l:cT($),r:cT(T),roots:[],ctx:W})};var DP=G$({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:($,T)=>T.$.parseSchema($)},morphs:{parse:m1,serialize:($)=>$.map((T)=>o(T,"root")?T.json:d$(T))},declaredIn:{child:!1,serialize:($)=>$.json},declaredOut:{child:!1,serialize:($)=>$.json}},normalize:($)=>$,defaults:{description:($)=>`a morph from ${$.in.description} to ${$.out?.description??"unknown"}`},intersections:{morph:($,T,W)=>{if(!$.hasEqualMorphs(T))return L(OP($.expression,T.expression));let X=j$($.in,T.in,W);if(X instanceof f)return X;let Y={morphs:$.morphs};if($.declaredIn||T.declaredIn){let U=j$($.in,T.in,W);if(U instanceof f)return U.throw();else Y.declaredIn=U}if($.declaredOut||T.declaredOut){let U=j$($.out,T.out,W);if(U instanceof f)return U.throw();else Y.declaredOut=U}return X.distribute((U)=>W.$.node("morph",{...Y,in:U}),W.$.parseSchema)},...c6("morph",($,T,W)=>{let X=$.inner.in?j$($.inner.in,T,W):T;return X instanceof f?X:X.equals($.inner.in)?$:W.$.node("morph",{...$.inner,in:X})})}});class HK extends Q6{serializedMorphs=this.morphs.map(d$);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=o(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??I.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??I.intrinsic.unknown.internal}declareIn($){return this.$.node("morph",{...this.inner,declaredIn:$})}declareOut($){return this.$.node("morph",{...this.inner,declaredOut:$})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema($){return $.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse($),out:this.introspectableOut?.toJsonSchemaRecurse($)??null})}compile($){if($.traversalKind==="Allows"){if(!this.introspectableIn)return;$.return($.invoke(this.introspectableIn));return}if(this.introspectableIn)$.line($.invoke(this.introspectableIn));$.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=($,T)=>!this.introspectableIn||this.introspectableIn.traverseAllows($,T);traverseApply=($,T)=>{if(this.introspectableIn)this.introspectableIn.traverseApply($,T);T.queueMorphs(this.morphs)};hasEqualMorphs($){return z1(this.morphs,$.morphs,{isEqual:(T,W)=>T===W||o(T,"root")&&o(W,"root")&&T.equals(W)})}}var m_={implementation:DP,Node:HK},OP=($,T)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
136
|
+
Left: ${$}
|
|
137
|
+
Right: ${T}`;var VP=G$({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:($)=>wX($)??H6($)},dateAllowsInvalid:{}},normalize:($)=>{let T=typeof $==="string"?{proto:x0[$]}:typeof $==="function"?v$($)?$:{proto:$}:typeof $.proto==="string"?{...$,proto:x0[$.proto]}:$;if(typeof T.proto!=="function")L(IX.writeInvalidSchemaMessage(T.proto));if(jT(T,"dateAllowsInvalid")&&T.proto!==Date)L(IX.writeBadInvalidDateMessage(T.proto));return T},applyConfig:($,T)=>{if($.dateAllowsInvalid===void 0&&$.proto===Date&&T.dateAllowsInvalid)return{...$,dateAllowsInvalid:!0};return $},defaults:{description:($)=>$.builtinName?GV[$.builtinName]:`an instance of ${$.proto.name}`,actual:($)=>$ instanceof Date&&$.toString()==="Invalid Date"?"an invalid Date":JX($)},intersections:{proto:($,T)=>$.proto===Date&&T.proto===Date?$.dateAllowsInvalid?T:$:z_($.proto,T.proto)?$:z_(T.proto,$.proto)?T:f.init("proto",$,T),domain:($,T)=>T.domain==="object"?$:f.init("domain",I.intrinsic.object.internal,T)}});class FK extends y0{builtinName=wX(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?($)=>$ instanceof Date&&$.toString()!=="Invalid Date":($)=>$ instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema($){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return $.fallback.date?.({code:"date",base:{}})??$.fallback.proto({code:"proto",base:{},proto:this.proto});default:return $.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 IX={implementation:VP,Node:FK,writeBadInvalidDateMessage:($)=>`dateAllowsInvalid may only be specified with constructor Date (was ${$.name})`,writeInvalidSchemaMessage:($)=>`instanceOf operand must be a function (was ${w4($)})`};var KP=G$({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:($,T)=>{let W=[];for(let X of $){let Y=o(X,"root")?X.branches:T.$.parseSchema(X).branches;for(let U of Y)if(U.hasKind("morph")){let G=W.findIndex((J)=>J.hasKind("morph")&&J.hasEqualMorphs(U));if(G===-1)W.push(U);else{let J=W[G];W[G]=T.$.node("morph",{...J.inner,in:J.in.rawOr(U.in)})}}else W.push(U)}if(!T.def.ordered)W.sort((X,Y)=>X.hash<Y.hash?-1:1);return W}}},normalize:($)=>I$($)?{branches:$}:$,reduce:($,T)=>{let W=kP($);if(W.length===1)return W[0];if(W.length===$.branches.length)return;return T.node("union",{...$,branches:W},{prereduced:!0})},defaults:{description:($)=>$.distribute((T)=>T.description,oT),expected:($)=>{let T=sO($.errors,"propString"),W=Object.entries(T).map(([X,Y])=>{let U=[];for(let z of Y)g6(U,z.expected);let G=oT(U),J=Y.every((z)=>z.actual===Y[0].actual)?Y[0].actual:U$(Y[0].data);return`${X&&`${X} `}must be ${G}${J&&` (was ${J})`}`});return oT(W)},problem:($)=>$.expected,message:($)=>$.problem},intersections:{union:($,T,W)=>{if($.isNever!==T.isNever)return f.init("presence",$,T);let X;if($.ordered){if(T.ordered)L(PP($.expression,T.expression));if(X=c_(T.branches,$.branches,W),X instanceof f)X.invert()}else X=c_($.branches,T.branches,W);if(X instanceof f)return X;return W.$.parseSchema($.ordered||T.ordered?{branches:X,ordered:!0}:{branches:X})},...c6("union",($,T,W)=>{let X=c_($.branches,[T],W);if(X instanceof f)return X;if(X.length===1)return X[0];return W.$.parseSchema($.ordered?{branches:X,ordered:!0}:{branches:X})})}});class DK extends Q6{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let $=[],T=-1;for(let W of this.branches){if(W.hasKind("unit")&&W.domain==="boolean"){if(T===-1)T=$.length,$.push(W);else $[T]=I.intrinsic.boolean;continue}$.push(W)}return $}unitBranches=this.branches.filter(($)=>$.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?BP(this.discriminant):null;expression=this.distribute(($)=>$.nestableExpression,IP);createBranchedOptimisticRootApply(){return($,T)=>{let W=this.traverseOptimistic($);if(W!==X6)return W;let X=new B6($,this.$.resolvedConfig);return this.traverseApply($,X),X.finalize(T)}}get shallowMorphs(){return this.branches.reduce(($,T)=>g6($,T.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(($)=>$.defaultShortDescription,oT)}innerToJsonSchema($){if(this.branchGroups.length===1&&this.branchGroups[0].equals(I.intrinsic.boolean))return{type:"boolean"};let T=this.branchGroups.map((W)=>W.toJsonSchemaRecurse($));if(T.every((W)=>Object.keys(W).length===1&&jT(W,"const")))return{enum:T.map((W)=>W.const)};return{anyOf:T}}traverseAllows=($,T)=>this.branches.some((W)=>W.traverseAllows($,T));traverseApply=($,T)=>{let W=[];for(let X=0;X<this.branches.length;X++){if(T.pushBranch(),this.branches[X].traverseApply($,T),!T.hasError()){if(this.branches[X].includesTransform)return T.queuedMorphs.push(...T.popBranch().queuedMorphs);return T.popBranch()}W.push(T.popBranch().error)}T.errorFromNodeContext({code:"union",errors:W,meta:this.meta})};traverseOptimistic=($)=>{for(let T=0;T<this.branches.length;T++){let W=this.branches[T];if(W.traverseAllows($)){if(W.contextFreeMorph)return W.contextFreeMorph($);return $}}return X6};compile($){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable($);let T=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")T=`typeof ${T} === "object" ? ${T} === null ? "null" : "object" : typeof ${T} === "function" ? "object" : typeof ${T}`;let W=this.discriminant.cases,X=Object.keys(W),{optimistic:Y}=$;if($.optimistic=!1,$.block(`switch(${T})`,()=>{for(let w in W){let H=W[w],_=w==="default"?w:`case ${w}`;$.line(`${_}: return ${H===!0?Y?$.data:H:Y?`${$.invoke(H)} ? ${H.contextFreeMorph?`${d$(H.contextFreeMorph)}(${$.data})`:$.data} : "${X6}"`:$.invoke(H)}`)}return $}),$.traversalKind==="Allows"){$.return(Y?`"${X6}"`:!1);return}let U=oT(this.discriminant.kind==="domain"?X.map((w)=>{let H=w.slice(1,-1);return H==="function"?u4.object:u4[H]}):X),G=this.discriminant.path.map((w)=>typeof w==="symbol"?d$(w):JSON.stringify(w)),J=JSON.stringify(U),z=this.discriminant.kind==="domain"?`${LP}[${T}]`:`${SP}(${T})`;$.line(`ctx.errorFromNodeContext({
|
|
114
138
|
code: "predicate",
|
|
115
|
-
expected: ${
|
|
116
|
-
actual: ${
|
|
117
|
-
relativePath: [${
|
|
139
|
+
expected: ${J},
|
|
140
|
+
actual: ${z},
|
|
141
|
+
relativePath: [${G}],
|
|
118
142
|
meta: ${this.compiledMeta}
|
|
119
|
-
})`)}compileIndiscriminable(
|
|
120
|
-
Left: ${
|
|
121
|
-
Right: ${
|
|
122
|
-
Left: ${
|
|
123
|
-
Right: ${$}`;var mE=J0({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(W)=>W instanceof Date?W.toISOString():FW(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,$)=>v.init("unit",W,$),...dW("unit",(W,$)=>{if($.allows(W.unit))return W;let Y=$.hasKind("intersection")?$.basis:$;if(Y){let X=Y.hasKind("domain")?Y:R.intrinsic.object;if(W.domain!==X.domain){let G=W.domain==="undefined"||W.domain==="null"||W.domain==="boolean"?W.domain:R.intrinsic[W.domain];return v.init("domain",G,X)}}return v.init("assignability",W,$.hasKind("intersection")?$.children.find((X)=>!X.allows(W.unit)):$)})}});class yF extends P2{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=vF(this.unit,this.serializedValue);compiledNegation=vF(this.unit,this.serializedValue,"negated");expression=G0(this.unit);domain=Q1(this.unit);get defaultShortDescription(){return this.domain==="object"?u1.object:this.description}innerToJsonSchema(W){return this.unit===null?{type:"null"}:R.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 AG={implementation:mE,Node:yF},vF=(W,$,Y)=>{if(W instanceof Date){let X=`data instanceof Date && data.toISOString() === ${$}`;return Y?`!(${X})`:X}if(Number.isNaN(W))return`${Y?"!":""}Number.isNaN(data)`;return`data ${Y?"!":"="}== ${$}`};var pE=J0({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(W,$)=>{let Y=$.$.parseSchema(W);if(!Y.extends(R.intrinsic.key))return A(cE(Y.expression));let X=Y.branches.filter((G)=>G.hasKind("unit"));if(X.length)return A(uE(X.map((G)=>G0(G.unit))));return Y}},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`[${W.signature.expression}]: ${W.value.description}`},intersections:{index:(W,$,Y)=>{if(W.signature.equals($.signature)){let X=x0(W.value,$.value,Y),G=X instanceof v?R.intrinsic.never.internal:X;return Y.$.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 hF extends wW{impliedBasis=R.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,$)=>C2(W).every((Y)=>{if(this.signature.traverseAllows(Y[0],$))return d1(Y[0],()=>this.value.traverseAllows(Y[1],$),$);return!0});traverseApply=(W,$)=>{for(let Y of C2(W))if(this.signature.traverseAllows(Y[0],$))d1(Y[0],()=>this.value.traverseApply(Y[1],$),$)};_transform(W,$){$.path.push(this.signature);let Y=super._transform(W,$);return $.path.pop(),Y}compile(){}}var LG={implementation:pE,Node:hF},uE=(W)=>`Index keys ${W.join(", ")} should be specified as named props.`,cE=(W)=>`Indexed key definition '${W}' must be a string or symbol`;var dE=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:o6,optional:o6}});class gF extends i6{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=d$(this.errorContext)}var ZG={implementation:dE,Node:gF};var lE=J0({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((Y)=>$.$.parseSchema(Y))}},optionals:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((Y)=>$.$.parseSchema(Y))}},defaultables:{child:(W)=>W.map(($)=>$[0]),parse:(W,$)=>{if(W.length===0)return;return W.map((Y)=>{let X=$.$.parseSchema(Y[0]);return r6(X,Y[1],null),[X,Y[1]]})},serialize:(W)=>W.map(($)=>[$[0].collapsibleJson,FW($[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((Y)=>$.$.parseSchema(Y))}}},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(rE);if(W.optionals?.length||W.defaultables?.length)return A(RG)}if(W.minVariadicLength&&!W.variadic)return A("minVariadicLength may not be specified without a variadic element");return W}return{variadic:W}},reduce:(W,$)=>{let Y=W.minVariadicLength??0,X=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(X.at(-1)?.equals(W.variadic))X.pop(),Y++;while(H[0]?.equals(W.variadic))H.shift(),Y++}else if(J.length===0&&G.length===0)X.push(...H.splice(0));if(Y!==W.minVariadicLength||W.prefix&&W.prefix.length!==X.length)return $.node("sequence",{...W,prefix:X,defaultables:G,optionals:J,postfix:H,minVariadicLength:Y},{prereduced:!0})},defaults:{description:(W)=>{if(W.isVariadicOnly)return`${W.variadic.nestableExpression}[]`;return`[${W.tuple.map((Y)=>Y.kind==="defaultables"?`${Y.node.nestableExpression} = ${G0(Y.default)}`:Y.kind==="optionals"?`${Y.node.nestableExpression}?`:Y.kind==="variadic"?`...${Y.node.nestableExpression}[]`:Y.node.expression).join(", ")}]`}},intersections:{sequence:(W,$,Y)=>{let X=e6({l:W.tuple,r:$.tuple,disjoint:new v,result:[],fixedVariants:[],ctx:Y}),G=X.disjoint.length===0?[X,...X.fixedVariants]:X.fixedVariants;return G.length===0?X.disjoint:G.length===1?Y.$.node("sequence",mF(G[0].result)):Y.$.node("union",G.map((J)=>({proto:Array,sequence:mF(J.result)})))}}});class pF extends wW{impliedBasis=R.intrinsic.Array.internal;tuple=nE(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=Q$(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return a7(this.flatRefs,this.prevariadic.flatMap((W,$)=>D0(W.node.flatRefs.map((Y)=>kW([`${$}`,...Y.path],Y.node)),kW([`${$}`],W.node)))),a7(this.flatRefs,this.variadicOrPostfix.flatMap((W)=>D0(W.flatRefs.map(($)=>kW([R.intrinsic.nonNegativeIntegerString.internal,...$.path],$.node)),kW([R.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=iE(this);defaultValueMorphsReference=this.defaultValueMorphs.length?d0(this.defaultValueMorphs):void 0;elementAtIndex(W,$){if($<this.prevariadic.length)return this.tuple[$];let Y=W.length-this.postfixLength;if($>=Y)return{kind:"postfix",node:this.postfix[$-Y]};return{kind:"variadic",node:this.variadic??E0(`Unexpected attempt to access index ${$} on ${this}`)}}traverseAllows=(W,$)=>{for(let Y=0;Y<W.length;Y++)if(!this.elementAtIndex(W,Y).node.traverseAllows(W[Y],$))return!1;return!0};traverseApply=(W,$)=>{let Y=0;for(;Y<W.length;Y++)d1(Y,()=>this.elementAtIndex(W,Y).node.traverseApply(W[Y],$),$)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(W){if(this.prefix)for(let[$,Y]of this.prefix.entries())W.traverseKey(`${$}`,`data[${$}]`,Y);for(let[$,Y]of this.defaultablesAndOptionals.entries()){let X=`${$+this.prefixLength}`;W.if(`${X} >= ${W.data}.length`,()=>W.traversalKind==="Allows"?W.return(!0):W.return()),W.traverseKey(X,`data[${X}]`,Y)}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[$,Y]of this.postfix.entries()){let X=`firstPostfixIndex + ${$}`;W.traverseKey(X,`data[${X}]`,Y)}}if(W.traversalKind==="Allows")W.return(!0)}_transform(W,$){$.path.push(R.intrinsic.nonNegativeIntegerString.internal);let Y=super._transform(W,$);return $.path.pop(),Y}expression=this.description;reduceJsonSchema(W,$){if(this.prevariadic.length)W.prefixItems=this.prevariadic.map((Y)=>{let X=Y.node.toJsonSchemaRecurse($);if(Y.kind==="defaultables"){let G=typeof Y.default==="function"?Y.default():Y.default;X.default=R.intrinsic.jsonData.allows(G)?G:$.fallback.defaultValue({code:"defaultValue",base:X,value:G})}return X});if(this.minLength)W.minItems=this.minLength;if(this.variadic){let Y=Object.assign(W,{items:this.variadic.toJsonSchemaRecurse($)});if(this.maxLength)Y.maxItems=this.maxLength;if(this.postfix){let X=this.postfix.map((G)=>G.toJsonSchemaRecurse($));W=$.fallback.arrayPostfix({code:"arrayPostfix",base:Y,elements:X})}}else W.items=!1,delete W.maxItems;return W}}var oE={},iE=(W)=>{if(!W.defaultables)return[];let $=[],Y="[",X=W.prefixLength+W.defaultablesLength-1;for(let G=W.prefixLength;G<=X;G++){let[J,H]=W.defaultables[G-W.prefixLength];$.push(MG(G,J,H)),Y+=`${G}: ${J.id} = ${FW(H)}, `}return Y+="]",oE[Y]??=$},NG={implementation:lE,Node:pF},nE=(W)=>{let $=[];if(W.prefix)for(let Y of W.prefix)$.push({kind:"prefix",node:Y});if(W.defaultables)for(let[Y,X]of W.defaultables)$.push({kind:"defaultables",node:Y,default:X});if(W.optionals)for(let Y of W.optionals)$.push({kind:"optionals",node:Y});if(W.variadic)$.push({kind:"variadic",node:W.variadic});if(W.postfix)for(let Y of W.postfix)$.push({kind:"postfix",node:Y});return $},mF=(W)=>W.reduce(($,Y)=>{if(Y.kind==="variadic")$.variadic=Y.node;else if(Y.kind==="defaultables")$.defaultables=D0($.defaultables,[[Y.node,Y.default]]);else $[Y.kind]=D0($[Y.kind],Y.node);return $},{}),RG="A postfix required element cannot follow an optional or defaultable element",rE="A postfix element requires a variadic element",e6=(W)=>{let[$,...Y]=W.l,[X,...G]=W.r;if(!$||!X)return W;let J=Y.at(-1)?.kind==="postfix",H=G.at(-1)?.kind==="postfix",T=$.kind==="prefix"||X.kind==="prefix"?"prefix":$.kind==="postfix"||X.kind==="postfix"?"postfix":$.kind==="variadic"&&X.kind==="variadic"?"variadic":J||H?"prefix":$.kind==="defaultables"||X.kind==="defaultables"?"defaultables":"optionals";if($.kind==="prefix"&&X.kind==="variadic"&&H){let F=e6({...W,fixedVariants:[],r:G.map((w)=>({...w,kind:"prefix"}))});if(F.disjoint.length===0)W.fixedVariants.push(F)}else if(X.kind==="prefix"&&$.kind==="variadic"&&J){let F=e6({...W,fixedVariants:[],l:Y.map((w)=>({...w,kind:"prefix"}))});if(F.disjoint.length===0)W.fixedVariants.push(F)}let Q=x0($.node,X.node,W.ctx);if(Q instanceof v)if(T==="prefix"||T==="postfix")W.disjoint.push(...Q.withPrefixKey(T==="prefix"?W.result.length:`-${Y.length+1}`,"required")),W.result=[...W.result,{kind:T,node:R.intrinsic.never.internal}];else if(T==="optionals"||T==="defaultables")return W;else return e6({...W,fixedVariants:[],l:Y.map((F)=>({...F,kind:"prefix"})),r:Y.map((F)=>({...F,kind:"prefix"}))});else if(T==="defaultables"){if($.kind==="defaultables"&&X.kind==="defaultables"&&$.default!==X.default)A(DG($.default,X.default));W.result=[...W.result,{kind:T,node:Q,default:$.kind==="defaultables"?$.default:X.kind==="defaultables"?X.default:E0(`Unexpected defaultable intersection from ${$.kind} and ${X.kind} elements.`)}]}else W.result=[...W.result,{kind:T,node:Q}];let _=W.l.length,z=W.r.length;if($.kind!=="variadic"||_>=z&&(X.kind==="variadic"||z===1))W.l=Y;if(X.kind!=="variadic"||z>=_&&($.kind==="variadic"||_===1))W.r=G;return e6(W)};var dF=(W)=>($)=>{if($.props.length||$.index){let Y=$.index?.map((G)=>G[W])??[];for(let G of $.props)Y.push(G[W]);if($.undeclared)Y.push(`+ (undeclared): ${$.undeclared}`);let X=`{ ${Y.join(", ")} }`;return $.sequence?`${X} & ${$.sequence.description}`:X}return $.sequence?.description??"{}"},tE=dF("description"),aE=dF("expression"),uF=(W,$,Y)=>{let X=W.required?"required":"optional";if(!$.signature.allows(W.key))return null;let G=l1(W.value,$.value,Y);if(G instanceof v)return X==="optional"?Y.node("optional",{key:W.key,value:R.intrinsic.never.internal}):G.withPrefixKey(W.key,W.kind);return null},sE=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:B1("required"),reduceIo:(W,$,Y)=>{$.required=D0($.required,Y.map((X)=>X[W]));return}},optional:{child:!0,parse:B1("optional"),reduceIo:(W,$,Y)=>{if(W==="in"){$.optional=Y.map((X)=>X.in);return}for(let X of Y)$[X.outProp.kind]=D0($[X.outProp.kind],X.outProp.out)}},index:{child:!0,parse:B1("index")},sequence:{child:!0,parse:B1("sequence")},undeclared:{parse:(W)=>W==="ignore"?void 0:W,reduceIo:(W,$,Y)=>{if(Y!=="delete")return;if(W==="in")delete $.undeclared;else $.undeclared="reject"}}},defaults:{description:tE},intersections:{structure:(W,$,Y)=>{let X={...W.inner},G={...$.inner},J=new v;if(W.undeclared){let Q=W.keyof();for(let _ of $.requiredKeys)if(!Q.allows(_))J.add("presence",R.intrinsic.never.internal,$.propsByKey[_].value,{path:[_]});if(G.optional)G.optional=G.optional.filter((_)=>Q.allows(_.key));if(G.index)G.index=G.index.flatMap((_)=>{if(_.signature.extends(Q))return _;let z=l1(Q,_.signature,Y.$);if(z instanceof v)return[];let F=J9(z,_.value,Y.$);if(F.required)G.required=Q$(G.required,F.required);if(F.optional)G.optional=Q$(G.optional,F.optional);return F.index??[]})}if($.undeclared){let Q=$.keyof();for(let _ of W.requiredKeys)if(!Q.allows(_))J.add("presence",W.propsByKey[_].value,R.intrinsic.never.internal,{path:[_]});if(X.optional)X.optional=X.optional.filter((_)=>Q.allows(_.key));if(X.index)X.index=X.index.flatMap((_)=>{if(_.signature.extends(Q))return _;let z=l1(Q,_.signature,Y.$);if(z instanceof v)return[];let F=J9(z,_.value,Y.$);if(F.required)X.required=Q$(X.required,F.required);if(F.optional)X.optional=Q$(X.optional,F.optional);return F.index??[]})}let H={};if(W.undeclared||$.undeclared)H.undeclared=W.undeclared==="reject"||$.undeclared==="reject"?"reject":"delete";let T=P8({kind:"structure",baseInner:H,l:f8(X),r:f8(G),roots:[],ctx:Y});if(T instanceof v)J.push(...T);if(J.length)return J;return T}},reduce:(W,$)=>{if(W.index){if(!(W.required||W.optional))return;let Y=!1,X=W.required??[],G=W.optional??[],J=[...G];for(let H of W.index){for(let T of X){let Q=uF(T,H,$);if(Q instanceof v)return Q}for(let[T,Q]of G.entries()){let _=uF(Q,H,$);if(_ instanceof v)return _;if(_===null)continue;J[T]=_,Y=!0}}if(Y)return $.node("structure",{...W,optional:J},{prereduced:!0})}}});class lF extends wW{impliedBasis=R.intrinsic.object.internal;impliedSiblings=this.children.flatMap((W)=>W.impliedSiblings??[]);props=Q$(this.required,this.optional);propsByKey=X0(this.props,(W,$)=>[$.key,$]);propsByKeyReference=d0(this.propsByKey);expression=aE(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(($,Y)=>{let X=this.propsByKey[Y.key];if(b0(Y)){if(Y.kind!=="required"&&Y.kind!=="optional")return A(`Map result must have kind "required" or "optional" (was ${Y.kind})`);return $[Y.kind]=D0($[Y.kind],Y),$}let G=Y.kind??X?.kind??"required",J=X0(Y,(H,T)=>(H in n6.implementation.keys)?[H,T]:[]);return $[G]=D0($[G],this.$.node(G,J)),$},{}))}assertHasKeys(W){let $=W.filter((Y)=>!t6(Y,this.keyof()));if($.length)return A(cF(this.expression,$))}get(W,...$){let Y,X=!1,G=YA(W);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])Y=this.propsByKey[G].value,X=this.propsByKey[G].required;if(this.index){for(let H of this.index)if(t6(G,H.signature))Y=Y?.and(H.value)??H.value}if(this.sequence&&t6(G,R.intrinsic.nonNegativeIntegerString))if(d(G,"root")){if(this.sequence.variadic)Y=Y?.and(this.sequence.element)??this.sequence.element}else{let H=Number.parseInt(G);if(H<this.sequence.prevariadic.length){let T=this.sequence.prevariadic[H].node;Y=Y?.and(T)??T,X||=H<this.sequence.prefixLength}else if(this.sequence.variadic){let T=this.$.node("union",this.sequence.variadicOrPostfix);Y=Y?.and(T)??T}}if(!Y){if(this.sequence?.variadic&&d(G,"root")&&G.extends(R.intrinsic.number))return A(XA(G.expression,this.sequence.expression));return A(cF(this.expression,[G]))}let J=Y.get(...$);return X?J:J.or(R.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((Y)=>Y.hasKind("required")?this.$.node("optional",Y.inner):Y)})}require(){let{optional:W,...$}=this.inner;return this.$.node("structure",{...$,required:this.props.map((Y)=>Y.hasKind("optional")?{key:Y.key,value:Y.value}:Y)})}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 Y=nX(this.inner),X=(G)=>{let J=$.some((H)=>t6(G,H));return W==="pick"?J:!J};if(Y.required)Y.required=Y.required.filter((G)=>X(G.key));if(Y.optional)Y.optional=Y.optional.filter((G)=>X(G.key));if(Y.index)Y.index=Y.index.filter((G)=>X(G.signature));return Y}traverseAllows=(W,$)=>this._traverse("Allows",W,$);traverseApply=(W,$)=>this._traverse("Apply",W,$);_traverse=(W,$,Y)=>{let X=Y?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(W==="Allows"){if(!this.props[G].traverseAllows($,Y))return!1}else if(this.props[G].traverseApply($,Y),Y.failFast&&Y.currentErrorCount>X)return!1;if(this.sequence){if(W==="Allows"){if(!this.sequence.traverseAllows($,Y))return!1}else if(this.sequence.traverseApply($,Y),Y.failFast&&Y.currentErrorCount>X)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 T of this.index)if(T.signature.traverseAllows(H,Y)){if(W==="Allows"){if(!d1(H,()=>T.value.traverseAllows($[H],Y),Y))return!1}else if(d1(H,()=>T.value.traverseApply($[H],Y),Y),Y.failFast&&Y.currentErrorCount>X)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(H)){if(W==="Allows")return!1;if(Y.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[H],meta:this.meta}),Y.failFast)return!1}}}if(this.structuralMorph&&Y&&!Y.hasError())Y.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&&R.intrinsic.nonNegativeIntegerString.allows(W);_compileDeclaresKey(W){let $=[];if(this.props.length)$.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Y of this.index)$.push(W.invoke(Y.signature,{kind:"Allows",arg:"k"}));if(this.sequence)$.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return $.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",WA(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(["),$A(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 Y=this.sequence?.reduceJsonSchema(W,$)??W;if(this.props.length||this.index)return $.fallback.arrayObject({code:"arrayObject",base:Y,object:this.reduceObjectJsonSchema({type:"object"},$)});return Y;default:return h0.throwInternalOperandError("structure",W)}}reduceObjectJsonSchema(W,$){if(this.props.length){W.properties={};for(let Y of this.props){let X=Y.value.toJsonSchemaRecurse($);if(typeof Y.key==="symbol"){$.fallback.symbolKey({code:"symbolKey",base:W,key:Y.key,value:X,optional:Y.optional});continue}if(Y.hasDefault()){let G=typeof Y.default==="function"?Y.default():Y.default;X.default=R.intrinsic.jsonData.allows(G)?G:$.fallback.defaultValue({code:"defaultValue",base:X,value:G})}W.properties[Y.key]=X}if(this.requiredKeys.length&&W.properties)W.required=this.requiredKeys.filter((Y)=>typeof Y==="string"&&(Y in W.properties))}if(this.index)for(let Y of this.index){let X=Y.value.toJsonSchemaRecurse($);if(Y.signature.equals(R.intrinsic.string)){W.additionalProperties=X;continue}for(let G of Y.signature.branches){if(!G.extends(R.intrinsic.string)){W=$.fallback.symbolKey({code:"symbolKey",base:W,key:null,value:X,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 E0(`Unexpected index branch kind ${G.kind}.`);let{pattern:H}=G.inner;if(H){let T=Object.assign(J,{pattern:H[0].rule});for(let Q=1;Q<H.length;Q++)J=$.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:H[Q].rule});W.patternProperties??={},W.patternProperties[T.pattern]=X}}}if(this.undeclared&&!W.additionalProperties)W.additionalProperties=!1;return W}}var BG={},eE=(W)=>{let $="";for(let Y=0;Y<W.defaultable.length;Y++)$+=W.defaultable[Y].defaultValueMorphRef;if(W.sequence?.defaultValueMorphsReference)$+=W.sequence?.defaultValueMorphsReference;if(W.undeclared==="delete"){if($+="delete !(",W.required)for(let Y of W.required)$+=Y.compiledKey+" | ";if(W.optional)for(let Y of W.optional)$+=Y.compiledKey+" | ";if(W.index)for(let Y of W.index)$+=Y.signature.id+" | ";if(W.sequence)if(W.sequence.maxLength===null)$+=r.nonNegativeIntegerString.id;else for(let Y=0;Y<W.sequence.tuple.length;Y++)$+=Y+" | ";$+=")"}return $},WA=(W)=>{let $=eE(W);if(!$)return;if(BG[$])return BG[$];let Y=(X,G)=>{for(let J=0;J<W.defaultable.length;J++)if(!(W.defaultable[J].key in X))W.defaultable[J].defaultValueMorph(X,G);if(W.sequence?.defaultables)for(let J=X.length-W.sequence.prefixLength;J<W.sequence.defaultables.length;J++)W.sequence.defaultValueMorphs[J](X,G);if(W.undeclared==="delete"){for(let J in X)if(!W.declaresKey(J))delete X[J]}return X};return BG[$]=Y},$A=(W,$)=>{let X=`(data${$.defaultable.some((G)=>G.defaultValueMorph.length===2)||$.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return W.block(`${X} => `,(G)=>{for(let J=0;J<$.defaultable.length;J++){let{serializedKey:H,defaultValueMorphRef:T}=$.defaultable[J];G.if(`!(${H} in data)`,(Q)=>Q.line(`${T}${X}`))}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")})},SG={implementation:sE,Node:lF},YA=(W)=>{if(d(W,"root")&&W.hasKind("unit"))W=W.unit;if(typeof W==="number")W=`${W}`;return W},XA=(W,$)=>`${W} is not allowed as an array index on ${$}. Use the 'nonNegativeIntegerString' keyword instead.`,J9=(W,$,Y)=>{let[X,G]=Dz(W.branches,(H)=>H.hasKind("unit"));if(!X.length)return{index:Y.node("index",{signature:W,value:$})};let J={};for(let H of X){let T=Y.node("required",{key:H.unit,value:$});J[T.kind]=D0(J[T.kind],T)}if(G.length)J.index=Y.node("index",{signature:G,value:$});return J},GA=(W)=>d(W,"root")?W.expression:G0(W),cF=(W,$)=>`Key${$.length===1?"":"s"} ${$.map(GA).join(", ")} ${$.length===1?"does":"do"} not exist on ${W}`;var x8={...MF,alias:a6.implementation,domain:G9.implementation,unit:AG.implementation,proto:s6.implementation,union:EG.implementation,morph:OG.implementation,intersection:VG.implementation,divisor:YG.implementation,pattern:zG.implementation,predicate:$G.implementation,required:ZG.implementation,optional:n6.implementation,index:LG.implementation,sequence:NG.implementation,structure:SG.implementation};R.defaultConfig=Nz(Object.assign(X0(x8,(W,$)=>[W,$.defaults]),{jitless:kz(),clone:Sz,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:h0.defaultConfig}));R.resolvedConfig=p6(R.defaultConfig,R.config);var LF={...VF,alias:a6.Node,domain:G9.Node,unit:AG.Node,proto:s6.Node,union:EG.Node,morph:OG.Node,intersection:VG.Node,divisor:YG.Node,pattern:zG.Node,predicate:$G.Node,required:ZG.Node,optional:n6.Node,index:LG.Node,sequence:NG.Node,structure:SG.Node};class h8 extends v7{get[b1](){return"module"}}var qG=(W,$)=>new h8(X0(W,(Y,X)=>[Y,d(X,"module")?qG(X,$):$.bindReference(X)]));var JA=(W)=>k0(W)?W:("branches"in W)&&k0(W.branches)?W.branches:void 0,HA=(W,$)=>A(`Node of kind ${$} is not valid as a ${W} definition`),oF=(W)=>`#${W} duplicates public alias ${W}`,CG={};R.ambient??={};var iF,rF="function $",TA=(W)=>tF(W,aF(W)),tF=(W,$)=>{let Y=$.write(rF,4),X=$.compile()();for(let G of W){if(G.precompilation)continue;if(G.traverseAllows=X[`${G.id}Allows`].bind(X),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=X[`${G.id}Apply`].bind(X),X[`${G.id}Optimistic`])G.traverseOptimistic=X[`${G.id}Optimistic`].bind(X);G.precompilation=Y}},aF=(W)=>new iX().return(W.reduce(($,Y)=>{let X=new m6({kind:"Allows"}).indent();Y.compile(X);let G=X.write(`${Y.id}Allows`),J=new m6({kind:"Apply"}).indent();Y.compile(J);let H=J.write(`${Y.id}Apply`),T=`${$}${G},
|
|
124
|
-
${
|
|
125
|
-
`;if(!
|
|
143
|
+
})`)}compileIndiscriminable($){if($.traversalKind==="Apply"){$.const("errors","[]");for(let T of this.branches)$.line("ctx.pushBranch()").line($.invoke(T)).if("!ctx.hasError()",()=>$.return(T.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");$.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:T}=$;$.optimistic=!1;for(let W of this.branches)$.if(`${$.invoke(W)}`,()=>$.return(T?W.contextFreeMorph?`${d$(W.contextFreeMorph)}(${$.data})`:$.data:!0));$.return(T?`"${X6}"`:!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 Y=Y$(this.unitBranches,(U,G)=>[`${G.in.serializedValue}`,G.hasKind("morph")?G:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:Y}}let $=[];for(let Y=0;Y<this.branches.length-1;Y++){let U=this.branches[Y];for(let G=Y+1;G<this.branches.length;G++){let J=this.branches[G],z=o4(U.in,J.in,U.$);if(!(z instanceof f))continue;for(let w of z){if(!w.kind||w.optional)continue;let H,_;if(w.kind==="domain"){let{l:D,r:V}=w;H=`"${typeof D==="string"?D:D.domain}"`,_=`"${typeof V==="string"?V:V.domain}"`}else if(w.kind==="unit")H=w.l.serializedValue,_=w.r.serializedValue;else continue;let F=$.find((D)=>z1(D.path,w.path)&&D.kind===w.kind);if(!F)$.push({kind:w.kind,cases:{[H]:{branchIndices:[Y],condition:w.l},[_]:{branchIndices:[G],condition:w.r}},path:w.path});else{if(F.cases[H])F.cases[H].branchIndices=g6(F.cases[H].branchIndices,Y);else F.cases[H]??={branchIndices:[Y],condition:w.l};if(F.cases[_])F.cases[_].branchIndices=g6(F.cases[_].branchIndices,G);else F.cases[_]??={branchIndices:[G],condition:w.r}}}}}let T=this.ordered?AP($,this.branches):$;if(!T.length)return null;let W=EP(T,this),X={};for(let Y in W.best.cases){let U=MP(W,Y);if(U===null){X[Y]=!0;continue}if(U.length===this.branches.length)return null;if(this.ordered)U.sort((z,w)=>z.originalIndex-w.originalIndex);let G=U.map((z)=>z.branch),J=G.length===1?G[0]:this.$.node("union",this.ordered?{branches:G,ordered:!0}:G);Object.assign(this.referencesById,J.referencesById),X[Y]=J}if(W.defaultEntries.length){let Y=W.defaultEntries.map((U)=>U.branch);X.default=this.$.node("union",this.ordered?{branches:Y,ordered:!0}:Y,{prereduced:!0}),Object.assign(this.referencesById,X.default.referencesById)}return Object.assign(W.location,{cases:X})}}var EP=($,T)=>{let W=$.sort((U,G)=>Object.keys(G.cases).length-Object.keys(U.cases).length)[0],X={kind:W.kind,path:W.path,optionallyChainedPropString:OK(W.path)},Y=T.branches.map((U,G)=>({originalIndex:G,branch:U}));return{best:W,location:X,defaultEntries:Y,node:T}},MP=($,T)=>{let W=$.best.cases[T],X=NP(W.condition,$.location.path,$.node.$),Y=[],U=[];for(let G=0;G<$.defaultEntries.length;G++){let J=$.defaultEntries[G];if(W.branchIndices.includes(J.originalIndex)){let z=QK($.node.branches[J.originalIndex],$.location);if(z===null)Y=null;else Y?.push({originalIndex:J.originalIndex,branch:z})}else if(J.branch.hasKind("alias")&&X.hasKind("domain")&&X.domain==="object")Y?.push(J);else{if(J.branch.in.overlaps(X)){let z=QK(J.branch,$.location);Y?.push({originalIndex:J.originalIndex,branch:z})}U.push(J)}}return $.defaultEntries=U,Y},AP=($,T)=>{return $.filter((X)=>{let Y=Object.values(X.cases).map((U)=>U.branchIndices);for(let U=0;U<Y.length-1;U++){let G=Y[U];for(let J=U+1;J<Y.length;J++){let z=Y[J];for(let w of G)for(let H of z)if(w>H){if(T[w].overlaps(T[H]))return!1}}}return!0})},NP=($,T,W)=>{let X=$==="undefined"?W.node("unit",{unit:void 0}):$==="null"?W.node("unit",{unit:null}):$==="boolean"?W.units([!0,!1]):$;for(let Y=T.length-1;Y>=0;Y--){let U=T[Y];X=W.node("intersection",typeof U==="number"?{proto:"Array",sequence:[...tO(U).map((G)=>({})),X]}:{domain:"object",required:[{key:U,value:X}]})}return X},OK=($)=>$.reduce((T,W)=>T+O_(W,!0),"data"),LP=d$(eO),SP=d$(U$),u_={implementation:KP,Node:DK},BP=($)=>({kind:$.kind,path:$.path.map((T)=>typeof T==="string"?T:F1(T)),cases:Y$($.cases,(T,W)=>[T,W===!0?W:W.hasKind("union")&&W.discriminantJson?W.discriminantJson:W.json])}),RP={delimiter:" | ",finalDelimiter:" | "},IP=($)=>oT($,RP),oT=($,T)=>{let W=T?.delimiter??", ",X=T?.finalDelimiter??" or ";if($.length===0)return"never";if($.length===1)return $[0];if($.length===2&&$[0]==="false"&&$[1]==="true"||$[0]==="true"&&$[1]==="false")return"boolean";let Y={},U=$.filter((J)=>Y[J]?!1:Y[J]=!0),G=U.pop();return`${U.join(W)}${U.length?X:""}${G}`},c_=($,T,W)=>{let X=T.map(()=>[]);for(let U=0;U<$.length;U++){let G={};for(let J=0;J<T.length;J++){if(X[J]===null)continue;if($[U].equals(T[J])){X[J]=null,G={};break}let z=j$($[U],T[J],W);if(z instanceof f)continue;if(z.equals($[U])){X[J].push($[U]),G={};break}if(z.equals(T[J]))X[J]=null;else G[J]=z}for(let J in G)X[J][U]=G[J]}let Y=X.flatMap((U,G)=>U?.flatMap((J)=>J.branches)??T[G]);return Y.length===0?f.init("union",$,T):Y},kP=({branches:$,ordered:T})=>{if($.length<2)return $;let W=$.map(()=>!0);for(let X=0;X<$.length;X++)for(let Y=X+1;Y<$.length&&W[X]&&W[Y];Y++){if($[X].equals($[Y])){W[Y]=!1;continue}let U=o4($[X].in,$[Y].in,$[0].$);if(U instanceof f)continue;if(!T)qP($[X],$[Y]);if(U.equals($[X].in))W[X]=!!T;else if(U.equals($[Y].in))W[Y]=!1}return $.filter((X,Y)=>W[Y])},qP=($,T)=>{if(!$.includesTransform&&!T.includesTransform)return;if(!z1($.shallowMorphs,T.shallowMorphs))L(ZK($.expression,T.expression));if(!z1($.flatMorphs,T.flatMorphs,{isEqual:(W,X)=>W.propString===X.propString&&(W.node.hasKind("morph")&&X.node.hasKind("morph")?W.node.hasEqualMorphs(X.node):W.node.hasKind("intersection")&&X.node.hasKind("intersection")?W.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))L(ZK($.expression,T.expression))},QK=($,T)=>$.transform((W,X)=>{if(W==="domain"||W==="unit")return null;return X},{shouldTransform:(W,X)=>{let Y=OK(X.path);if(!T.optionallyChainedPropString.startsWith(Y))return!1;if(W.hasKind("domain")&&W.domain==="object")return!0;if((W.hasKind("domain")||T.kind==="unit")&&Y===T.optionallyChainedPropString)return!0;return W.children.length!==0&&W.kind!=="index"}}),ZK=($,T)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
144
|
+
Left: ${$}
|
|
145
|
+
Right: ${T}`,PP=($,T)=>`The intersection of two ordered unions is indeterminate:
|
|
146
|
+
Left: ${$}
|
|
147
|
+
Right: ${T}`;var CP=G$({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:($)=>$ instanceof Date?$.toISOString():H6($)}},normalize:($)=>$,defaults:{description:($)=>U$($.unit),problem:({expected:$,actual:T})=>`${$===T?`must be reference equal to ${$} (serialized to the same value)`:`must be ${$} (was ${T})`}`},intersections:{unit:($,T)=>f.init("unit",$,T),...c6("unit",($,T)=>{if(T.allows($.unit))return $;let W=T.hasKind("intersection")?T.basis:T;if(W){let X=W.hasKind("domain")?W:I.intrinsic.object;if($.domain!==X.domain){let Y=$.domain==="undefined"||$.domain==="null"||$.domain==="boolean"?$.domain:I.intrinsic[$.domain];return f.init("domain",Y,X)}}return f.init("assignability",$,T.hasKind("intersection")?T.children.find((X)=>!X.allows($.unit)):T)})}});class KK extends y0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=VK(this.unit,this.serializedValue);compiledNegation=VK(this.unit,this.serializedValue,"negated");expression=U$(this.unit);domain=w4(this.unit);get defaultShortDescription(){return this.domain==="object"?u4.object:this.description}innerToJsonSchema($){return this.unit===null?{type:"null"}:I.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:$.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?($)=>$ instanceof Date&&$.toISOString()===this.compiledValue:Number.isNaN(this.unit)?($)=>Number.isNaN($):($)=>$===this.unit}var p_={implementation:CP,Node:KK},VK=($,T,W)=>{if($ instanceof Date){let X=`data instanceof Date && data.toISOString() === ${T}`;return W?`!(${X})`:X}if(Number.isNaN($))return`${W?"!":""}Number.isNaN(data)`;return`data ${W?"!":"="}== ${T}`};var vP=G$({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:($,T)=>{let W=T.$.parseSchema($);if(!W.extends(I.intrinsic.key))return L(xP(W.expression));let X=W.branches.filter((Y)=>Y.hasKind("unit"));if(X.length)return L(jP(X.map((Y)=>U$(Y.unit))));return W}},value:{child:!0,parse:($,T)=>T.$.parseSchema($)}},normalize:($)=>$,defaults:{description:($)=>`[${$.signature.expression}]: ${$.value.description}`},intersections:{index:($,T,W)=>{if($.signature.equals(T.signature)){let X=j$($.value,T.value,W),Y=X instanceof f?I.intrinsic.never.internal:X;return W.$.node("index",{signature:$.signature,value:Y})}if($.signature.extends(T.signature)&&$.value.subsumes(T.value))return T;if(T.signature.extends($.signature)&&T.value.subsumes($.value))return $;return null}}});class EK extends F6{impliedBasis=I.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Q$(this.value.flatRefs.map(($)=>R6([this.signature,...$.path],$.node)),R6([this.signature],this.value));traverseAllows=($,T)=>j0($).every((W)=>{if(this.signature.traverseAllows(W[0],T))return d4(W[0],()=>this.value.traverseAllows(W[1],T),T);return!0});traverseApply=($,T)=>{for(let W of j0($))if(this.signature.traverseAllows(W[0],T))d4(W[0],()=>this.value.traverseApply(W[1],T),T)};_transform($,T){T.path.push(this.signature);let W=super._transform($,T);return T.path.pop(),W}compile(){}}var d_={implementation:vP,Node:EK},jP=($)=>`Index keys ${$.join(", ")} should be specified as named props.`,xP=($)=>`Indexed key definition '${$}' must be a string or symbol`;var bP=G$({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:($,T)=>T.$.parseSchema($)}},normalize:($)=>$,defaults:{description:($)=>`${$.compiledKey}: ${$.value.description}`,expected:($)=>$.missingValueDescription,actual:()=>"missing"},intersections:{required:AX,optional:AX}});class MK extends NX{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=d1(this.errorContext)}var o_={implementation:bP,Node:MK};var fP=G$({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:($,T)=>{if($.length===0)return;return $.map((W)=>T.$.parseSchema(W))}},optionals:{child:!0,parse:($,T)=>{if($.length===0)return;return $.map((W)=>T.$.parseSchema(W))}},defaultables:{child:($)=>$.map((T)=>T[0]),parse:($,T)=>{if($.length===0)return;return $.map((W)=>{let X=T.$.parseSchema(W[0]);return SX(X,W[1],null),[X,W[1]]})},serialize:($)=>$.map((T)=>[T[0].collapsibleJson,H6(T[1])])},variadic:{child:!0,parse:($,T)=>T.$.parseSchema($,T)},minVariadicLength:{parse:($)=>$===0?void 0:$},postfix:{child:!0,parse:($,T)=>{if($.length===0)return;return $.map((W)=>T.$.parseSchema(W))}}},normalize:($)=>{if(typeof $==="string")return{variadic:$};if("variadic"in $||"prefix"in $||"defaultables"in $||"optionals"in $||"postfix"in $||"minVariadicLength"in $){if($.postfix?.length){if(!$.variadic)return L(mP);if($.optionals?.length||$.defaultables?.length)return L(r_)}if($.minVariadicLength&&!$.variadic)return L("minVariadicLength may not be specified without a variadic element");return $}return{variadic:$}},reduce:($,T)=>{let W=$.minVariadicLength??0,X=$.prefix?.slice()??[],Y=$.defaultables?.slice()??[],U=$.optionals?.slice()??[],G=$.postfix?.slice()??[];if($.variadic){while(U.at(-1)?.equals($.variadic))U.pop();if(U.length===0&&Y.length===0)while(X.at(-1)?.equals($.variadic))X.pop(),W++;while(G[0]?.equals($.variadic))G.shift(),W++}else if(U.length===0&&Y.length===0)X.push(...G.splice(0));if(W!==$.minVariadicLength||$.prefix&&$.prefix.length!==X.length)return T.node("sequence",{...$,prefix:X,defaultables:Y,optionals:U,postfix:G,minVariadicLength:W},{prereduced:!0})},defaults:{description:($)=>{if($.isVariadicOnly)return`${$.variadic.nestableExpression}[]`;return`[${$.tuple.map((W)=>W.kind==="defaultables"?`${W.node.nestableExpression} = ${U$(W.default)}`:W.kind==="optionals"?`${W.node.nestableExpression}?`:W.kind==="variadic"?`...${W.node.nestableExpression}[]`:W.node.expression).join(", ")}]`}},intersections:{sequence:($,T,W)=>{let X=kX({l:$.tuple,r:T.tuple,disjoint:new f,result:[],fixedVariants:[],ctx:W}),Y=X.disjoint.length===0?[X,...X.fixedVariants]:X.fixedVariants;return Y.length===0?X.disjoint:Y.length===1?W.$.node("sequence",AK(Y[0].result)):W.$.node("union",Y.map((U)=>({proto:Array,sequence:AK(U.result)})))}}});class NK extends F6{impliedBasis=I.intrinsic.Array.internal;tuple=gP(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(($)=>{if($.kind==="defaultables"||$.kind==="optionals")return this.defaultablesAndOptionals.push($.node),!0;return $.kind==="prefix"});variadicOrPostfix=w1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return M_(this.flatRefs,this.prevariadic.flatMap(($,T)=>Q$($.node.flatRefs.map((W)=>R6([`${T}`,...W.path],W.node)),R6([`${T}`],$.node)))),M_(this.flatRefs,this.variadicOrPostfix.flatMap(($)=>Q$($.flatRefs.map((T)=>R6([I.intrinsic.nonNegativeIntegerString.internal,...T.path],T.node)),R6([I.intrinsic.nonNegativeIntegerString.internal],$)))),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=hP(this);defaultValueMorphsReference=this.defaultValueMorphs.length?d$(this.defaultValueMorphs):void 0;elementAtIndex($,T){if(T<this.prevariadic.length)return this.tuple[T];let W=$.length-this.postfixLength;if(T>=W)return{kind:"postfix",node:this.postfix[T-W]};return{kind:"variadic",node:this.variadic??O$(`Unexpected attempt to access index ${T} on ${this}`)}}traverseAllows=($,T)=>{for(let W=0;W<$.length;W++)if(!this.elementAtIndex($,W).node.traverseAllows($[W],T))return!1;return!0};traverseApply=($,T)=>{let W=0;for(;W<$.length;W++)d4(W,()=>this.elementAtIndex($,W).node.traverseApply($[W],T),T)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile($){if(this.prefix)for(let[T,W]of this.prefix.entries())$.traverseKey(`${T}`,`data[${T}]`,W);for(let[T,W]of this.defaultablesAndOptionals.entries()){let X=`${T+this.prefixLength}`;$.if(`${X} >= ${$.data}.length`,()=>$.traversalKind==="Allows"?$.return(!0):$.return()),$.traverseKey(X,`data[${X}]`,W)}if(this.variadic){if(this.postfix)$.const("firstPostfixIndex",`${$.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if($.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>$.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[T,W]of this.postfix.entries()){let X=`firstPostfixIndex + ${T}`;$.traverseKey(X,`data[${X}]`,W)}}if($.traversalKind==="Allows")$.return(!0)}_transform($,T){T.path.push(I.intrinsic.nonNegativeIntegerString.internal);let W=super._transform($,T);return T.path.pop(),W}expression=this.description;reduceJsonSchema($,T){if(this.prevariadic.length)$.prefixItems=this.prevariadic.map((W)=>{let X=W.node.toJsonSchemaRecurse(T);if(W.kind==="defaultables"){let Y=typeof W.default==="function"?W.default():W.default;X.default=I.intrinsic.jsonData.allows(Y)?Y:T.fallback.defaultValue({code:"defaultValue",base:X,value:Y})}return X});if(this.minLength)$.minItems=this.minLength;if(this.variadic){let W=Object.assign($,{items:this.variadic.toJsonSchemaRecurse(T)});if(this.maxLength)W.maxItems=this.maxLength;if(this.postfix){let X=this.postfix.map((Y)=>Y.toJsonSchemaRecurse(T));$=T.fallback.arrayPostfix({code:"arrayPostfix",base:W,elements:X})}}else $.items=!1,delete $.maxItems;return $}}var yP={},hP=($)=>{if(!$.defaultables)return[];let T=[],W="[",X=$.prefixLength+$.defaultablesLength-1;for(let Y=$.prefixLength;Y<=X;Y++){let[U,G]=$.defaultables[Y-$.prefixLength];T.push(h_(Y,U,G)),W+=`${Y}: ${U.id} = ${H6(G)}, `}return W+="]",yP[W]??=T},l_={implementation:fP,Node:NK},gP=($)=>{let T=[];if($.prefix)for(let W of $.prefix)T.push({kind:"prefix",node:W});if($.defaultables)for(let[W,X]of $.defaultables)T.push({kind:"defaultables",node:W,default:X});if($.optionals)for(let W of $.optionals)T.push({kind:"optionals",node:W});if($.variadic)T.push({kind:"variadic",node:$.variadic});if($.postfix)for(let W of $.postfix)T.push({kind:"postfix",node:W});return T},AK=($)=>$.reduce((T,W)=>{if(W.kind==="variadic")T.variadic=W.node;else if(W.kind==="defaultables")T.defaultables=Q$(T.defaultables,[[W.node,W.default]]);else T[W.kind]=Q$(T[W.kind],W.node);return T},{}),r_="A postfix required element cannot follow an optional or defaultable element",mP="A postfix element requires a variadic element",kX=($)=>{let[T,...W]=$.l,[X,...Y]=$.r;if(!T||!X)return $;let U=W.at(-1)?.kind==="postfix",G=Y.at(-1)?.kind==="postfix",J=T.kind==="prefix"||X.kind==="prefix"?"prefix":T.kind==="postfix"||X.kind==="postfix"?"postfix":T.kind==="variadic"&&X.kind==="variadic"?"variadic":U||G?"prefix":T.kind==="defaultables"||X.kind==="defaultables"?"defaultables":"optionals";if(T.kind==="prefix"&&X.kind==="variadic"&&G){let _=kX({...$,fixedVariants:[],r:Y.map((F)=>({...F,kind:"prefix"}))});if(_.disjoint.length===0)$.fixedVariants.push(_)}else if(X.kind==="prefix"&&T.kind==="variadic"&&U){let _=kX({...$,fixedVariants:[],l:W.map((F)=>({...F,kind:"prefix"}))});if(_.disjoint.length===0)$.fixedVariants.push(_)}let z=j$(T.node,X.node,$.ctx);if(z instanceof f)if(J==="prefix"||J==="postfix")$.disjoint.push(...z.withPrefixKey(J==="prefix"?$.result.length:`-${W.length+1}`,"required")),$.result=[...$.result,{kind:J,node:I.intrinsic.never.internal}];else if(J==="optionals"||J==="defaultables")return $;else return kX({...$,fixedVariants:[],l:W.map((_)=>({..._,kind:"prefix"})),r:W.map((_)=>({..._,kind:"prefix"}))});else if(J==="defaultables"){if(T.kind==="defaultables"&&X.kind==="defaultables"&&T.default!==X.default)L(y_(T.default,X.default));$.result=[...$.result,{kind:J,node:z,default:T.kind==="defaultables"?T.default:X.kind==="defaultables"?X.default:O$(`Unexpected defaultable intersection from ${T.kind} and ${X.kind} elements.`)}]}else $.result=[...$.result,{kind:J,node:z}];let w=$.l.length,H=$.r.length;if(T.kind!=="variadic"||w>=H&&(X.kind==="variadic"||H===1))$.l=W;if(X.kind!=="variadic"||H>=w&&(T.kind==="variadic"||w===1))$.r=Y;return kX($)};var BK=($)=>(T)=>{if(T.props.length||T.index){let W=T.index?.map((Y)=>Y[$])??[];for(let Y of T.props)W.push(Y[$]);if(T.undeclared)W.push(`+ (undeclared): ${T.undeclared}`);let X=`{ ${W.join(", ")} }`;return T.sequence?`${X} & ${T.sequence.description}`:X}return T.sequence?.description??"{}"},cP=BK("description"),uP=BK("expression"),LK=($,T,W)=>{let X=$.required?"required":"optional";if(!T.signature.allows($.key))return null;let Y=o4($.value,T.value,W);if(Y instanceof f)return X==="optional"?W.node("optional",{key:$.key,value:I.intrinsic.never.internal}):Y.withPrefixKey($.key,$.kind);return null},pP=G$({kind:"structure",hasAssociatedError:!1,normalize:($)=>$,applyConfig:($,T)=>{if(!$.undeclared&&T.onUndeclaredKey!=="ignore")return{...$,undeclared:T.onUndeclaredKey};return $},keys:{required:{child:!0,parse:S4("required"),reduceIo:($,T,W)=>{T.required=Q$(T.required,W.map((X)=>X[$]));return}},optional:{child:!0,parse:S4("optional"),reduceIo:($,T,W)=>{if($==="in"){T.optional=W.map((X)=>X.in);return}for(let X of W)T[X.outProp.kind]=Q$(T[X.outProp.kind],X.outProp.out)}},index:{child:!0,parse:S4("index")},sequence:{child:!0,parse:S4("sequence")},undeclared:{parse:($)=>$==="ignore"?void 0:$,reduceIo:($,T,W)=>{if(W!=="delete")return;if($==="in")delete T.undeclared;else T.undeclared="reject"}}},defaults:{description:cP},intersections:{structure:($,T,W)=>{let X={...$.inner},Y={...T.inner},U=new f;if($.undeclared){let z=$.keyof();for(let w of T.requiredKeys)if(!z.allows(w))U.add("presence",I.intrinsic.never.internal,T.propsByKey[w].value,{path:[w]});if(Y.optional)Y.optional=Y.optional.filter((w)=>z.allows(w.key));if(Y.index)Y.index=Y.index.flatMap((w)=>{if(w.signature.extends(z))return w;let H=o4(z,w.signature,W.$);if(H instanceof f)return[];let _=LU(H,w.value,W.$);if(_.required)Y.required=w1(Y.required,_.required);if(_.optional)Y.optional=w1(Y.optional,_.optional);return _.index??[]})}if(T.undeclared){let z=T.keyof();for(let w of $.requiredKeys)if(!z.allows(w))U.add("presence",$.propsByKey[w].value,I.intrinsic.never.internal,{path:[w]});if(X.optional)X.optional=X.optional.filter((w)=>z.allows(w.key));if(X.index)X.index=X.index.flatMap((w)=>{if(w.signature.extends(z))return w;let H=o4(z,w.signature,W.$);if(H instanceof f)return[];let _=LU(H,w.value,W.$);if(_.required)X.required=w1(X.required,_.required);if(_.optional)X.optional=w1(X.optional,_.optional);return _.index??[]})}let G={};if($.undeclared||T.undeclared)G.undeclared=$.undeclared==="reject"||T.undeclared==="reject"?"reject":"delete";let J=mT({kind:"structure",baseInner:G,l:cT(X),r:cT(Y),roots:[],ctx:W});if(J instanceof f)U.push(...J);if(U.length)return U;return J}},reduce:($,T)=>{if($.index){if(!($.required||$.optional))return;let W=!1,X=$.required??[],Y=$.optional??[],U=[...Y];for(let G of $.index){for(let J of X){let z=LK(J,G,T);if(z instanceof f)return z}for(let[J,z]of Y.entries()){let w=LK(z,G,T);if(w instanceof f)return w;if(w===null)continue;U[J]=w,W=!0}}if(W)return T.node("structure",{...$,optional:U},{prereduced:!0})}}});class RK extends F6{impliedBasis=I.intrinsic.object.internal;impliedSiblings=this.children.flatMap(($)=>$.impliedSiblings??[]);props=w1(this.required,this.optional);propsByKey=Y$(this.props,($,T)=>[T.key,T]);propsByKeyReference=d$(this.propsByKey);expression=uP(this);requiredKeys=this.required?.map(($)=>$.key)??[];optionalKeys=this.optional?.map(($)=>$.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let $=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:T}of this.index)$=$.concat(T.branches);return this._keyof=this.$.node("union",$)}map($){return this.$.node("structure",this.props.flatMap($).reduce((T,W)=>{let X=this.propsByKey[W.key];if(v$(W)){if(W.kind!=="required"&&W.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${W.kind})`);return T[W.kind]=Q$(T[W.kind],W),T}let Y=W.kind??X?.kind??"required",U=Y$(W,(G,J)=>(G in LX.implementation.keys)?[G,J]:[]);return T[Y]=Q$(T[Y],this.$.node(Y,U)),T},{}))}assertHasKeys($){let T=$.filter((W)=>!BX(W,this.keyof()));if(T.length)return L(SK(this.expression,T))}get($,...T){let W,X=!1,Y=rP($);if((typeof Y==="string"||typeof Y==="symbol")&&this.propsByKey[Y])W=this.propsByKey[Y].value,X=this.propsByKey[Y].required;if(this.index){for(let G of this.index)if(BX(Y,G.signature))W=W?.and(G.value)??G.value}if(this.sequence&&BX(Y,I.intrinsic.nonNegativeIntegerString))if(o(Y,"root")){if(this.sequence.variadic)W=W?.and(this.sequence.element)??this.sequence.element}else{let G=Number.parseInt(Y);if(G<this.sequence.prevariadic.length){let J=this.sequence.prevariadic[G].node;W=W?.and(J)??J,X||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let J=this.$.node("union",this.sequence.variadicOrPostfix);W=W?.and(J)??J}}if(!W){if(this.sequence?.variadic&&o(Y,"root")&&Y.extends(I.intrinsic.number))return L(iP(Y.expression,this.sequence.expression));return L(SK(this.expression,[Y]))}let U=W.get(...T);return X?U:U.or(I.intrinsic.undefined)}pick(...$){return this.assertHasKeys($),this.$.node("structure",this.filterKeys("pick",$))}omit(...$){return this.assertHasKeys($),this.$.node("structure",this.filterKeys("omit",$))}optionalize(){let{required:$,...T}=this.inner;return this.$.node("structure",{...T,optional:this.props.map((W)=>W.hasKind("required")?this.$.node("optional",W.inner):W)})}require(){let{optional:$,...T}=this.inner;return this.$.node("structure",{...T,required:this.props.map((W)=>W.hasKind("optional")?{key:W.key,value:W.value}:W)})}merge($){let T=this.filterKeys("omit",[$.keyof()]);if($.required)T.required=Q$(T.required,$.required);if($.optional)T.optional=Q$(T.optional,$.optional);if($.index)T.index=Q$(T.index,$.index);if($.sequence)T.sequence=$.sequence;if($.undeclared)T.undeclared=$.undeclared;else delete T.undeclared;return this.$.node("structure",T)}filterKeys($,T){let W=FU(this.inner),X=(Y)=>{let U=T.some((G)=>BX(Y,G));return $==="pick"?U:!U};if(W.required)W.required=W.required.filter((Y)=>X(Y.key));if(W.optional)W.optional=W.optional.filter((Y)=>X(Y.key));if(W.index)W.index=W.index.filter((Y)=>X(Y.signature));return W}traverseAllows=($,T)=>this._traverse("Allows",$,T);traverseApply=($,T)=>this._traverse("Apply",$,T);_traverse=($,T,W)=>{let X=W?.currentErrorCount??0;for(let Y=0;Y<this.props.length;Y++)if($==="Allows"){if(!this.props[Y].traverseAllows(T,W))return!1}else if(this.props[Y].traverseApply(T,W),W.failFast&&W.currentErrorCount>X)return!1;if(this.sequence){if($==="Allows"){if(!this.sequence.traverseAllows(T,W))return!1}else if(this.sequence.traverseApply(T,W),W.failFast&&W.currentErrorCount>X)return!1}if(this.index||this.undeclared==="reject"){let Y=Object.keys(T);Y.push(...Object.getOwnPropertySymbols(T));for(let U=0;U<Y.length;U++){let G=Y[U];if(this.index){for(let J of this.index)if(J.signature.traverseAllows(G,W)){if($==="Allows"){if(!d4(G,()=>J.value.traverseAllows(T[G],W),W))return!1}else if(d4(G,()=>J.value.traverseApply(T[G],W),W),W.failFast&&W.currentErrorCount>X)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(G)){if($==="Allows")return!1;if(W.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[G],meta:this.meta}),W.failFast)return!1}}}if(this.structuralMorph&&W&&!W.hasError())W.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter(($)=>$.hasDefault())??[])}declaresKey=($)=>($ in this.propsByKey)||this.index?.some((T)=>T.signature.allows($))||this.sequence!==void 0&&I.intrinsic.nonNegativeIntegerString.allows($);_compileDeclaresKey($){let T=[];if(this.props.length)T.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let W of this.index)T.push($.invoke(W.signature,{kind:"Allows",arg:"k"}));if(this.sequence)T.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return T.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",oP(this))}structuralMorphRef=this.structuralMorph&&d$(this.structuralMorph);compile($){if($.traversalKind==="Apply")$.initializeErrorCount();for(let T of this.props)if($.check(T),$.traversalKind==="Apply")$.returnIfFailFast();if(this.sequence){if($.check(this.sequence),$.traversalKind==="Apply")$.returnIfFailFast()}if(this.index||this.undeclared==="reject")$.const("keys","Object.keys(data)"),$.line("keys.push(...Object.getOwnPropertySymbols(data))"),$.for("i < keys.length",()=>this.compileExhaustiveEntry($));if($.traversalKind==="Allows")return $.return(!0);if(this.structuralMorphRef)$.if("ctx && !ctx.hasError()",()=>{return $.line("ctx.queueMorphs(["),lP($,this),$.line("])")})}compileExhaustiveEntry($){if($.const("k","keys[i]"),this.index)for(let T of this.index)$.if(`${$.invoke(T.signature,{arg:"k",kind:"Allows"})}`,()=>$.traverseKey("k","data[k]",T.value));if(this.undeclared==="reject")$.if(`!(${this._compileDeclaresKey($)})`,()=>{if($.traversalKind==="Allows")return $.return(!1);return $.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>$.return())});return $}reduceJsonSchema($,T){switch($.type){case"object":return this.reduceObjectJsonSchema($,T);case"array":let W=this.sequence?.reduceJsonSchema($,T)??$;if(this.props.length||this.index)return T.fallback.arrayObject({code:"arrayObject",base:W,object:this.reduceObjectJsonSchema({type:"object"},T)});return W;default:return y$.throwInternalOperandError("structure",$)}}reduceObjectJsonSchema($,T){if(this.props.length){$.properties={};for(let W of this.props){let X=W.value.toJsonSchemaRecurse(T);if(typeof W.key==="symbol"){T.fallback.symbolKey({code:"symbolKey",base:$,key:W.key,value:X,optional:W.optional});continue}if(W.hasDefault()){let Y=typeof W.default==="function"?W.default():W.default;X.default=I.intrinsic.jsonData.allows(Y)?Y:T.fallback.defaultValue({code:"defaultValue",base:X,value:Y})}$.properties[W.key]=X}if(this.requiredKeys.length&&$.properties)$.required=this.requiredKeys.filter((W)=>typeof W==="string"&&(W in $.properties))}if(this.index)for(let W of this.index){let X=W.value.toJsonSchemaRecurse(T);if(W.signature.equals(I.intrinsic.string)){$.additionalProperties=X;continue}for(let Y of W.signature.branches){if(!Y.extends(I.intrinsic.string)){$=T.fallback.symbolKey({code:"symbolKey",base:$,key:null,value:X,optional:!1});continue}let U={type:"string"};if(Y.hasKind("morph"))U=T.fallback.morph({code:"morph",base:Y.in.toJsonSchemaRecurse(T),out:Y.out.toJsonSchemaRecurse(T)});if(!Y.hasKind("intersection"))return O$(`Unexpected index branch kind ${Y.kind}.`);let{pattern:G}=Y.inner;if(G){let J=Object.assign(U,{pattern:G[0].rule});for(let z=1;z<G.length;z++)U=T.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:G[z].rule});$.patternProperties??={},$.patternProperties[J.pattern]=X}}}if(this.undeclared&&!$.additionalProperties)$.additionalProperties=!1;return $}}var i_={},dP=($)=>{let T="";for(let W=0;W<$.defaultable.length;W++)T+=$.defaultable[W].defaultValueMorphRef;if($.sequence?.defaultValueMorphsReference)T+=$.sequence?.defaultValueMorphsReference;if($.undeclared==="delete"){if(T+="delete !(",$.required)for(let W of $.required)T+=W.compiledKey+" | ";if($.optional)for(let W of $.optional)T+=W.compiledKey+" | ";if($.index)for(let W of $.index)T+=W.signature.id+" | ";if($.sequence)if($.sequence.maxLength===null)T+=n.nonNegativeIntegerString.id;else for(let W=0;W<$.sequence.tuple.length;W++)T+=W+" | ";T+=")"}return T},oP=($)=>{let T=dP($);if(!T)return;if(i_[T])return i_[T];let W=(X,Y)=>{for(let U=0;U<$.defaultable.length;U++)if(!($.defaultable[U].key in X))$.defaultable[U].defaultValueMorph(X,Y);if($.sequence?.defaultables)for(let U=X.length-$.sequence.prefixLength;U<$.sequence.defaultables.length;U++)$.sequence.defaultValueMorphs[U](X,Y);if($.undeclared==="delete"){for(let U in X)if(!$.declaresKey(U))delete X[U]}return X};return i_[T]=W},lP=($,T)=>{let X=`(data${T.defaultable.some((Y)=>Y.defaultValueMorph.length===2)||T.sequence?.defaultValueMorphs.some((Y)=>Y.length===2)?", ctx":""})`;return $.block(`${X} => `,(Y)=>{for(let U=0;U<T.defaultable.length;U++){let{serializedKey:G,defaultValueMorphRef:J}=T.defaultable[U];Y.if(`!(${G} in data)`,(z)=>z.line(`${J}${X}`))}if(T.sequence?.defaultables)Y.for(`i < ${T.sequence.defaultables.length}`,(U)=>U.set("data[i]",5),`data.length - ${T.sequence.prefixLength}`);if(T.undeclared==="delete")Y.forIn("data",(U)=>U.if(`!(${T._compileDeclaresKey(U)})`,(G)=>G.line("delete data[k]")));return Y.return("data")})},n_={implementation:pP,Node:RK},rP=($)=>{if(o($,"root")&&$.hasKind("unit"))$=$.unit;if(typeof $==="number")$=`${$}`;return $},iP=($,T)=>`${$} is not allowed as an array index on ${T}. Use the 'nonNegativeIntegerString' keyword instead.`,LU=($,T,W)=>{let[X,Y]=nO($.branches,(G)=>G.hasKind("unit"));if(!X.length)return{index:W.node("index",{signature:$,value:T})};let U={};for(let G of X){let J=W.node("required",{key:G.unit,value:T});U[J.kind]=Q$(U[J.kind],J)}if(Y.length)U.index=W.node("index",{signature:Y,value:T});return U},nP=($)=>o($,"root")?$.expression:U$($),SK=($,T)=>`Key${T.length===1?"":"s"} ${T.map(nP).join(", ")} ${T.length===1?"does":"do"} not exist on ${$}`;var pT={...tV,alias:RX.implementation,domain:NU.implementation,unit:p_.implementation,proto:IX.implementation,union:u_.implementation,morph:m_.implementation,intersection:g_.implementation,divisor:B_.implementation,pattern:j_.implementation,predicate:S_.implementation,required:o_.implementation,optional:LX.implementation,index:d_.implementation,sequence:l_.implementation,structure:n_.implementation};I.defaultConfig=YV(Object.assign(Y$(pT,($,T)=>[$,T.defaults]),{jitless:_V(),clone:JV,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:y$.defaultConfig}));I.resolvedConfig=OX(I.defaultConfig,I.config);var WK={...aV,alias:RX.Node,domain:NU.Node,unit:p_.Node,proto:IX.Node,union:u_.Node,morph:m_.Node,intersection:g_.Node,divisor:B_.Node,pattern:j_.Node,predicate:S_.Node,required:o_.Node,optional:LX.Node,index:d_.Node,sequence:l_.Node,structure:n_.Node};class lT extends U_{get[C4](){return"module"}}var t_=($,T)=>new lT(Y$($,(W,X)=>[W,o(X,"module")?t_(X,T):T.bindReference(X)]));var tP=($)=>I$($)?$:("branches"in $)&&I$($.branches)?$.branches:void 0,aP=($,T)=>L(`Node of kind ${T} is not valid as a ${$} definition`),IK=($)=>`#${$} duplicates public alias ${$}`,a_={};I.ambient??={};var kK,PK="function $",sP=($)=>CK($,vK($)),CK=($,T)=>{let W=T.write(PK,4),X=T.compile()();for(let Y of $){if(Y.precompilation)continue;if(Y.traverseAllows=X[`${Y.id}Allows`].bind(X),Y.isRoot()&&!Y.allowsRequiresContext)Y.allows=Y.traverseAllows;if(Y.traverseApply=X[`${Y.id}Apply`].bind(X),X[`${Y.id}Optimistic`])Y.traverseOptimistic=X[`${Y.id}Optimistic`].bind(X);Y.precompilation=W}},vK=($)=>new HU().return($.reduce((T,W)=>{let X=new DX({kind:"Allows"}).indent();W.compile(X);let Y=X.write(`${W.id}Allows`),U=new DX({kind:"Apply"}).indent();W.compile(U);let G=U.write(`${W.id}Apply`),J=`${T}${Y},
|
|
148
|
+
${G},
|
|
149
|
+
`;if(!W.hasKind("union"))return J;let z=new DX({kind:"Allows",optimistic:!0}).indent();W.compile(z);let w=z.write(`${W.id}Optimistic`);return`${J}${w},
|
|
126
150
|
`},`{
|
|
127
|
-
`)+"}");class H9{config;resolvedConfig;name;get[b1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(W,$){if(this.config=p6(R.config,$),this.resolvedConfig=p6(R.resolvedConfig,$),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(CG).length}`,this.name in CG)A(`A Scope already named ${this.name} already exists`);CG[this.name]=this;let Y=Object.entries(W).map((X)=>this.preparseOwnAliasEntry(...X));for(let[X,G]of Y){let J=X;if(X[0]==="#"){if(J=X.slice(1),J in this.aliases)A(oF(J));this.aliases[J]=G}else{if(J in this.aliases)A(oF(X));this.aliases[J]=G,this.exportedNames.push(J)}if(!d(G,"module")&&!d(G,"generic")&&!p$(G)){let H=this.preparseOwnDefinitionFormat(G,{alias:J});this.resolutions[J]=d(H,"root")?this.bindReference(H):this.createParseContext(H).id}}iF??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[iF.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=R.intrinsic?X0(R.intrinsic,(X,G)=>X.startsWith("json")?[]:[X,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(Y,X)=>new o$(W,X?new sX(Y):Y,$,$,X??null)};units=(W,$)=>{let Y=[];for(let G of W)if(!Y.includes(G))Y.push(G);let X=Y.map((G)=>this.node("unit",{unit:G},$));return this.node("union",X,{...$,prereduced:!0})};lazyResolutions=[];lazilyResolve(W,$){let Y=this.node("alias",{reference:$??"synthetic",resolve:W},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Y);return Y}schema=(W,$)=>this.finalize(this.parseSchema(W,$));parseSchema=(W,$)=>this.node(l6(W),W,$);preparseNode(W,$,Y){let X=typeof W==="string"?W:l6($,W);if(b0($)&&$.kind===X)return $;if(X==="alias"&&!Y?.prereduced){let{reference:H}=a6.implementation.normalize($,this);if(H.startsWith("$")){let T=this.resolveRoot(H.slice(1));$=T,X=T.kind}}else if(X==="union"&&p1($,"object")){let H=JA($);if(H?.length===1)$=H[0],X=l6($)}if(b0($)&&$.kind===X)return $;let J=x8[X].normalize?.($,this)??$;if(b0(J))return J.kind===X?J:HA(X,J.kind);return{...Y,$:this,kind:X,def:J,prefix:Y.alias??X}}bindReference(W){let $;if(b0(W))$=W.$===this?W:new W.constructor(W.attachments,this);else $=W.$===this?W:new o$(W.params,W.bodyDef,W.$,this,W.hkt);if(!this.resolved)Object.assign(this.referencesById,$.referencesById);return $}resolveRoot(W){return this.maybeResolveRoot(W)??A(IG(W))}maybeResolveRoot(W){let $=this.maybeResolve(W);if(d($,"generic"))return;return $}maybeResolveSubalias(W){return kG(this.aliases,W)??kG(this.ambient,W)}get ambient(){return R.ambient}maybeResolve(W){let $=this.resolutions[W];if($){if(typeof $!=="string")return this.bindReference($);let X=x1[$];if(d(X,"root"))return this.resolutions[W]=X;if(d(X,"context")){if(X.phase==="resolving")return this.node("alias",{reference:`$${W}`},{prereduced:!0});if(X.phase==="resolved")return E0(`Unexpected resolved context for was uncached by its scope: ${G0(X)}`);X.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(X.def,X));return X.phase="resolved",x1[G.id]=G,x1[X.id]=G,this.resolutions[W]=G}return E0(`Unexpected nodesById entry for ${$}: ${G0(X)}`)}let Y=this.aliases[W]??this.ambient?.[W];if(!Y)return this.maybeResolveSubalias(W);if(Y=this.normalizeRootScopeValue(Y),d(Y,"generic"))return this.resolutions[W]=this.bindReference(Y);if(d(Y,"module")){if(!Y.root)A(Ww(W));return this.resolutions[W]=this.bindReference(Y.root)}return this.resolutions[W]=this.parse(Y,{alias:W})}createParseContext(W){let $=W.id??FG(W.prefix);return x1[$]=Object.assign(W,{[b1]:"context",$:this,id:$,phase:"unresolved"})}traversal(W){return new CW(W,this.resolvedConfig)}import(...W){return new h8(X0(this.export(...W),($,Y)=>[`#${$}`,Y]))}precompilation;_exportedResolutions;_exports;export(...W){if(!this._exports){this._exports={};for(let Y of this.exportedNames){let X=this.aliases[Y];this._exports[Y]=d(X,"module")?qG(X,this):nF(this.maybeResolve(Y))}for(let Y of this.lazyResolutions)Y.resolution;if(this._exportedResolutions=eF(this,this._exports),this._json=sF(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Y=aF(this.references);this.precompilation=Y.write(rF,4),tF(this.references,Y)}this.resolved=!0}let $=W.length?W:this.exportedNames;return new h8(X0($,(Y,X)=>[X,this._exports[X]]))}resolve(W){return this.export()[W]}node=(W,$,Y={})=>{let X=this.preparseNode(W,$,Y);if(b0(X))return this.bindReference(X);let G=this.createParseContext(X),J=wG(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 Y=this.preparseOwnDefinitionFormat(W,$);if(d(Y,"root"))return this.bindReference(Y);let X=this.createParseContext(Y);x1[X.id]=X;let G=this.bindReference(this.parseOwnDefinitionFormat(W,X));if(G.isCyclic)G=AF(G,X.id);return x1[X.id]=G,G}finalize(W){if(nF(W),!W.precompilation&&!this.resolvedConfig.jitless)TA(W.references);return W}}class jG extends H9{parseOwnDefinitionFormat(W,$){return wG($)}preparseOwnDefinitionFormat(W,$){return this.preparseNode(l6(W),W,$)}preparseOwnAliasEntry(W,$){return[W,$]}normalizeRootScopeValue(W){return W}}var nF=(W)=>{let $=W.references.filter((Y)=>Y.hasKind("alias"));for(let Y of $){Object.assign(Y.referencesById,Y.resolution.referencesById);for(let X of W.references)if(Y.id in X.referencesById)Object.assign(X.referencesById,Y.referencesById)}return W},sF=(W)=>X0(W,($,Y)=>[$,d(Y,"root")||d(Y,"generic")?Y.json:d(Y,"module")?sF(Y):E0(`Unexpected resolution ${G0(Y)}`)]),kG=(W,$)=>{let Y=$.indexOf(".");if(Y===-1)return;let X=$.slice(0,Y),G=W[X];if(G===void 0)return;if(!d(G,"module"))return A(QA(X));let J=$.slice(Y+1),H=G[J];if(H===void 0)return kG(G,J);if(d(H,"root")||d(H,"generic"))return H;if(d(H,"module"))return H.root??A(Ww($));E0(`Unexpected resolution for alias '${$}': ${G0(H)}`)},T9=(W,$)=>new jG(W,$),WY=new jG({});var eF=(W,$)=>{let Y={};for(let X in $){let G=$[X];if(d(G,"module")){let J=eF(W,G),H=X0(J,(T,Q)=>[`${X}.${T}`,Q]);Object.assign(Y,H)}else if(d(G,"root")||d(G,"generic"))Y[X]=G;else E0(`Unexpected scope resolution ${G0(G)}`)}return Y},IG=(W)=>`'${W}' is unresolvable`,QA=(W)=>`'${W}' must reference a module to be accessed using dot syntax`,Ww=(W)=>`Reference to submodule '${W}' must specify an alias`;WY.export();var{schema:N0,node:g8,defineSchema:en,generic:DW}=WY;var PG="^(?:0|[1-9]\\d*)$",_A=new RegExp(PG),Yr=d0(_A);var $w=T9({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();R.intrinsic={...$w};var Yw=T9({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:PG}},{prereducedAliases:!0}).export();Object.assign(R.intrinsic,Yw);var zA=T9({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,...Yw,...zA,emptyStructure:g8("structure",{},{prereduced:!0})};R.intrinsic={...r};var Gw=(W)=>typeof W==="string"&&W[0]==="d"&&(W[1]==="'"||W[1]==='"')&&W.at(-1)===W[1],Xw=(W)=>W.toString()!=="Invalid Date",Jw=(W)=>W.slice(2,-1),fG=(W)=>`'${W}' could not be parsed by the Date constructor`,Hw=(W,$)=>FA(W,$),FA=(W,$)=>{let Y=new Date(W);if(Xw(Y))return Y;let X=hz(W);if(X!==void 0){let G=new Date(X);if(Xw(G))return G}return $?A($===!0?fG(W):$):void 0};var bG=(W,$)=>{let Y=W.scanner.shiftUntil(wA[Qw[$]]);if(W.scanner.lookahead==="")return W.error(DA(Y,$));if(W.scanner.shift(),$==="/"){try{new RegExp(Y)}catch(X){A(String(X))}W.root=W.ctx.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0})}else if(_1($,xG))W.root=W.ctx.$.node("unit",{unit:Y});else{let X=Hw(Y,fG(Y));W.root=W.ctx.$.node("unit",{meta:Y,unit:X})}},xG={"'":1,'"':1},Tw={"/":1,"'":1,'"':1},Qw={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},wA={"'":(W)=>W.lookahead==="'",'"':(W)=>W.lookahead==='"',"/":(W)=>W.lookahead==="/"},UA={'"':"double-quote","'":"single-quote","/":"forward slash"},DA=(W,$)=>`${$}${W} requires a closing ${UA[Qw[$]]}`;var _w=(W)=>`Private type references should not include '#'. Use '${W}' instead.`,Q9="Optional definitions like 'string?' are only valid as properties in an object or tuple",_9="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var zw={">":!0,">=":!0},Fw={"<":!0,"<=":!0};var m8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},ww=(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})`,Dw=(W,$,Y,X)=>`An expression may have at most one left bound (parsed ${W}${m8[$]}, ${Y}${m8[X]})`;var Mw=(W,$,Y)=>Vw(W,$,Y,[]),Vw=(W,$,Y,X)=>{let G=Y.parseUntilFinalizer();if(X.push(G.root),G.finalizer===">"){if(X.length!==$.params.length)return Y.error(vG(W,$.names,X.map((J)=>J.expression)));return X}if(G.finalizer===",")return Vw(W,$,Y,X);return G.error(z9(">"))},vG=(W,$,Y)=>`${W}<${$.join(", ")}> requires exactly ${$.length} args (got ${Y.length}${Y.length===0?"":`: ${Y.join(", ")}`})`;var yG=(W)=>{let $=W.scanner.shiftUntilNextTerminator();if($==="keyof")W.addPrefix("keyof");else W.root=VA(W,$)},MA=(W,$,Y)=>{if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.shift()!=="<")return Y.error(vG(W,$.names,[]));let G=Mw(W,$,Y);return $(...G)},VA=(W,$)=>OA(W,$)??KA(W,$)??W.error($===""?W.scanner.lookahead==="#"?_w(W.shiftedByOne().scanner.shiftUntilNextTerminator()):hG(W):IG($)),OA=(W,$)=>{if(W.ctx.args?.[$]){let X=W.ctx.args[$];if(typeof X!=="string")return X;return W.ctx.$.node("alias",{reference:X},{prereduced:!0})}let Y=W.ctx.$.maybeResolve($);if(d(Y,"root"))return Y;if(Y===void 0)return;if(d(Y,"generic"))return MA($,Y,W);return A(`Unexpected resolution ${G0(Y)}`)},KA=(W,$)=>{let Y=gz($);if(Y!==void 0)return W.ctx.$.node("unit",{unit:Y});let X=pz($);if(X!==void 0)return W.ctx.$.node("unit",{unit:X})},hG=(W)=>{let $=W.previousOperator();return $?gG($,W.scanner.unscanned):EA(W.scanner.unscanned)},gG=(W,$="")=>`Token '${W}' requires a right operand${$?` before '${$}'`:""}`,EA=(W)=>`Expected an expression${W?` before '${W}'`:""}`;var mG=(W)=>W.scanner.lookahead===""?W.error(hG(W)):W.scanner.lookahead==="("?W.shiftedByOne().reduceGroupOpen():W.scanner.lookaheadIsIn(Tw)?bG(W,W.scanner.shift()):W.scanner.lookaheadIsIn(u$)?mG(W.shiftedByOne()):W.scanner.lookahead==="d"?W.scanner.nextLookahead in xG?bG(W,`${W.scanner.shift()}${W.scanner.shift()}`):yG(W):yG(W);class D$ extends l7{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in D$.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...u$};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(W,$)=>W===">"?$[0]==="="?$[1]==="=":$.trimStart()===""||_1($.trimStart()[0],D$.terminatingChars):W==="="?$[0]!=="=":W===","||W==="?"}var Kw=(W,$)=>{let Y=AA(W,$);if(W.root.hasKind("unit")){if(typeof W.root.unit==="number"){W.reduceLeftBound(W.root.unit,Y),W.unsetRoot();return}if(W.root.unit instanceof Date){let X=`d'${W.root.description??W.root.unit.toISOString()}'`;W.unsetRoot(),W.reduceLeftBound(X,Y);return}}return ZA(W,Y)},Ew={"<":1,">":1,"=":1},AA=(W,$)=>W.scanner.lookaheadIs("=")?`${$}${W.scanner.shift()}`:$;var Ow=(W,$,Y,X)=>{if(Y.extends(R.intrinsic.number)){if(typeof $!=="number")return A(pG(W,$,X));return W==="=="?["min","max"]:W[0]===">"?["min"]:["max"]}if(Y.extends(R.intrinsic.lengthBoundable)){if(typeof $!=="number")return A(pG(W,$,X));return W==="=="?["exactLength"]:W[0]===">"?["minLength"]:["maxLength"]}if(Y.extends(R.intrinsic.Date))return W==="=="?["after","before"]:W[0]===">"?["after"]:["before"];return A(TF(Y.expression))},LA=(W)=>({rule:Gw(W.limit)?Jw(W.limit):W.limit,exclusive:W.comparator.length===1}),ZA=(W,$)=>{let Y=W.unsetRoot(),X=W.scanner.location;W.parseOperand();let G=W.unsetRoot(),J=W.scanner.sliceChars(X,W.scanner.location);if(W.root=Y,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return W.error(pG($,J,"right"));let H=G.unit,T=$.length===1,Q=Ow($,typeof H==="number"?H:J,Y,"right");for(let z of Q)W.constrainRoot(z,$==="=="?{rule:H}:{rule:H,exclusive:T});if(!W.branches.leftBound)return;if(!_1($,Fw))return W.error(F9($));let _=Ow(W.branches.leftBound.comparator,W.branches.leftBound.limit,Y,"left");W.constrainRoot(_[0],LA(W.branches.leftBound)),W.branches.leftBound=null},pG=(W,$,Y)=>`Comparator ${Y==="left"?m8[W]:W} must be ${Y==="left"?"preceded":"followed"} by a corresponding literal (was ${$})`;var Aw=(W)=>{W.scanner.shiftUntilNonWhitespace();let $=W.scanner.shiftUntilNextTerminator();W.root=W.root.brand($)};var Zw=(W)=>{let $=W.scanner.shiftUntilNextTerminator(),Y=mz($,{errorOnFail:Lw($)});if(Y===0)W.error(Lw(0));W.root=W.root.constrain("divisor",Y)},Lw=(W)=>`% operator must be followed by a non-zero integer literal (was ${W})`;var uG=(W)=>{let $=W.scanner.shift();return $===""?W.finalize(""):$==="["?W.scanner.shift()==="]"?W.setRoot(W.root.array()):W.error(NA):$==="|"?W.scanner.lookahead===">"?W.shiftedByOne().pushRootToBranch("|>"):W.pushRootToBranch($):$==="&"?W.pushRootToBranch($):$===")"?W.finalizeGroup():D$.lookaheadIsFinalizing($,W.scanner.unscanned)?W.finalize($):_1($,Ew)?Kw(W,$):$==="%"?Zw(W):$==="#"?Aw(W):($ in u$)?uG(W):W.error(w9($))},w9=(W,$="")=>`'${W}' is not allowed here${$&&` (should be ${$})`}`,NA="Missing expected ']'";var Nw=(W)=>{let $=W.unsetRoot();W.parseOperand();let Y=W.unsetRoot();if(!Y.hasKind("unit"))return W.error(RA(Y.expression));let X=Y.unit instanceof Date?()=>new Date(Y.unit):Y.unit;return[$,"=",X]},RA=(W)=>`Default value '${W}' must a literal value`;var cG=(W,$)=>{let Y=$.$.maybeResolveRoot(W);if(Y)return Y;if(W.endsWith("[]")){let J=$.$.maybeResolveRoot(W.slice(0,-2));if(J)return J.array()}let X=new p8(new D$(W),$),G=BA(X);if(X.finalizer===">")A(w9(">"));return G},BA=(W)=>{W.parseOperand();let $=$Y(W).root;if(!$)return E0(`Root was unexpectedly unset after parsing string '${W.scanner.scanned}'`);if(W.finalizer==="=")$=Nw(W);else if(W.finalizer==="?")$=[$,"?"];if(W.scanner.shiftUntilNonWhitespace(),W.scanner.lookahead)A(w9(W.scanner.lookahead));return $},$Y=(W)=>{while(W.finalizer===void 0)SA(W);return W},SA=(W)=>W.hasRoot()?W.parseOperator():W.parseOperand();class p8{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 Y=m8[$];if(!_1(Y,zw))return this.error(F9($));if(this.branches.leftBound)return this.error(Dw(this.branches.leftBound.limit,this.branches.leftBound.comparator,W,Y));this.branches.leftBound={comparator:Y,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():E0(`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 $Y(new p8(this.scanner,this.ctx))}parseOperator(){return uG(this)}parseOperand(){return mG(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 qA="An empty string is not a valid generic parameter name",U9=(W,$,Y)=>{W.shiftUntilNonWhitespace();let X=W.shiftUntilNextTerminator();if(X===""){if(W.lookahead===""&&$.length)return $;return A(qA)}return W.shiftUntilNonWhitespace(),CA(W,X,$,Y)},Rw="extends ",CA=(W,$,Y,X)=>{if(W.shiftUntilNonWhitespace(),W.unscanned.startsWith(Rw))W.jumpForward(Rw.length);else{if(W.lookahead===",")W.shift();return Y.push($),U9(W,Y,X)}let G=$Y(new p8(W,X));return Y.push([$,G.root]),U9(W,Y,X)};class dG extends qW{$;constructor(W){super((...$)=>new YY(W)(...$),{bind:W});this.$=W}in(W){return new YY(this.$,W===void 0?void 0:this.$.parse(W))}at(W,$){return new YY(this.$).at(W,$)}case(W,$){return new YY(this.$).case(W,$)}}class YY extends qW{$;in;key;branches=[];constructor(W,$){super((Y)=>this.caseEntries(Object.entries(Y).map(([X,G])=>X==="default"?[X,G]:[this.$.parse(X),G])));this.$=W,this.in=$}at(W,$){if(this.key)A(jA);if(this.branches.length)A(kA);return this.key=W,$?this.match($):this}case(W,$){return this.caseEntry(this.$.parse(W),$)}caseEntry(W,$){let X=(this.key?this.$.parse({[this.key]:W}):W).pipe($);return this.branches.push(X),this}match(W){return this(W)}strings(W){return this.caseEntries(Object.entries(W).map(([$,Y])=>$==="default"?[$,Y]:[this.$.node("unit",{unit:$}),Y]))}caseEntries(W){for(let $=0;$<W.length;$++){let[Y,X]=W[$];if(Y==="default"){if($!==W.length-1)A("default may only be specified as the last key of a switch definition");return this.default(X)}if(typeof X!=="function")return A(`Value for case "${Y}" must be a function (was ${Q1(X)})`);this.caseEntry(Y,X)}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:Bw};let Y=this.$.node("union",$);if(!this.in)return this.$.finalize(Y);let X=this.in.pipe(Y);if(W==="never"||W==="assert")X=X.configureReferences({onFail:Bw},"self");return this.$.finalize(X)}}var Bw=(W)=>W.throw(),kA="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",jA="At most one key matcher may be specified per expression";var D9=(W,$)=>{if(k0(W)){if(W[1]==="=")return[$.$.parseOwnDefinitionFormat(W[0],$),"=",W[2]];if(W[1]==="?")return[$.$.parseOwnDefinitionFormat(W[0],$),"?"]}return M9(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 Y,X={},G=C2(W);for(let[H,T]of G){let Q=fA(H);if(Q.kind==="spread"){if(!cW(X))return A(PA);let O=$.$.parseOwnDefinitionFormat(T,$);if(O.equals(r.object))continue;if(!O.hasKind("intersection")||!O.basis?.equals(r.object))return A(bA(O.expression));Y=O.structure;continue}if(Q.kind==="undeclared"){if(T!=="reject"&&T!=="delete"&&T!=="ignore")A(IA(T));X.undeclared=T;continue}let _=D9(T,$),z=Q;if(Q.kind==="required"){if(!k0(_))lG(X,"required",{key:Q.normalized,value:_},$);else lG(X,"optional",_[1]==="="?{key:Q.normalized,value:_[0],default:_[2]}:{key:Q.normalized,value:_[0]},$);continue}if(k0(_)){if(_[1]==="?")A(Sw);if(_[1]==="=")A(qw)}if(Q.kind==="optional"){lG(X,"optional",{key:Q.normalized,value:_},$);continue}let F=$.$.parseOwnDefinitionFormat(z.normalized,$),w=J9(F,_,$.$);if(w.index)X.index=D0(X.index,w.index);if(w.required)X.required=D0(X.required,w.required)}let J=$.$.node("structure",X);return $.$.parseSchema({domain:"object",structure:Y?.merge(J)??J})},lG=(W,$,Y,X)=>{W[$]=D0(W[$],X.$.node($,Y))},IA=(W)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${G0(W)})`,PA="Spread operator may only be used as the first key in an object",fA=(W)=>typeof W==="symbol"?{kind:"required",normalized:W}:W.at(-1)==="?"?W.at(-2)===b6?{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]===b6&&W[1]==="["&&W.at(-1)==="]"?{kind:"required",normalized:W.slice(1)}:W==="..."?{kind:"spread"}:W==="+"?{kind:"undeclared"}:{kind:"required",normalized:W==="\\..."?"...":W==="\\+"?"+":W},bA=(W)=>`Spread operand must resolve to an object literal type (was ${W})`;var jw=(W,$)=>dA(W)?bw[W[0]](W,$):uA(W)?fw[W[1]](W,$):null,xA=(W,$)=>$.$.parseOwnDefinitionFormat(W[1],$).keyof(),oG=(W,$)=>{if(W[2]===void 0)return A(gG(W[1],""));let Y=$.$.parseOwnDefinitionFormat(W[0],$),X=$.$.parseOwnDefinitionFormat(W[2],$);if(W[1]==="|")return $.$.node("union",{branches:[Y,X]});let G=W[1]==="&"?l1(Y,X,$.$):d6(Y,X,$.$);if(G instanceof v)return G.throw();return G},vA=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).array(),yA=(W,$)=>{if(typeof W[2]!=="function")return A(Iw("=>",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).pipe(W[2])},Iw=(W,$)=>`${W===":"?"Narrow":"Morph"} expression requires a function following '${W}' (was ${typeof $})`,hA=(W,$)=>{if(typeof W[2]!=="function")return A(Iw(":",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).constrain("predicate",W[2])},gA=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).configureReferences(W[2],"shallow"),Pw=(W)=>W,mA=Pw({"[]":vA,"?":()=>A(Q9)}),pA=Pw({"|":oG,"&":oG,":":hA,"=>":yA,"|>":oG,"@":gA,"=":()=>A(_9)}),fw={...mA,...pA},uA=(W)=>fw[W[1]]!==void 0,cA=(W)=>W,bw=cA({keyof:xA,instanceof:(W,$)=>{if(typeof W[1]!=="function")return A(kw(P6(W[1])));let Y=W.slice(1).map((X)=>typeof X==="function"?$.$.node("proto",{proto:X}):A(kw(P6(X))));return Y.length===1?Y[0]:$.$.node("union",{branches:Y})},"===":(W,$)=>$.$.units(W.slice(1))}),dA=(W)=>bw[W[0]]!==void 0,kw=(W)=>`Expected a constructor following 'instanceof' operator (was ${W})`;var yw=(W,$)=>{let Y=[{}],X=0;while(X<W.length){let G=!1;if(W[X]==="..."&&X<W.length-1)G=!0,X++;let J=D9(W[X],$),[H,T,Q]=!k0(J)?[J]:J;if(X++,G){if(!H.extends(R.intrinsic.Array))return A(iA(H.expression));Y=Y.flatMap((_)=>H.distribute((z)=>oA(nX(_),z)))}else Y=Y.map((_)=>{if(T==="?")return hw(_,H);if(T==="=")return lA(_,H,Q);return iG(_,H)})}return $.$.parseSchema(Y.map((G)=>cW(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},iG=(W,$)=>{if(W.defaultables||W.optionals)return A(W.variadic?RG:nA);if(W.variadic)W.postfix=D0(W.postfix,$);else W.prefix=D0(W.prefix,$);return W},hw=(W,$)=>{if(W.variadic)return A(gw);return W.optionals=D0(W.optionals,$),W},lA=(W,$,Y)=>{if(W.variadic)return A(gw);if(W.optionals)return A(rA);return W.defaultables=D0(W.defaultables,[[$,Y]]),W},xw=(W,$)=>{if(W.postfix)A(vw);if(W.variadic){if(!W.variadic.equals($))A(vw)}else W.variadic=$.internal;return W},oA=(W,$)=>{let Y=$.select({method:"find",kind:"sequence"});if(!Y)return xw(W,R.intrinsic.unknown);if(Y.prefix)for(let X of Y.prefix)iG(W,X);if(Y.optionals)for(let X of Y.optionals)hw(W,X);if(Y.variadic)xw(W,Y.variadic);if(Y.postfix)for(let X of Y.postfix)iG(W,X);return W},iA=(W)=>`Spread element must be an array (was ${W})`,vw="A tuple may have at most one variadic element",nA="A required element may not follow an optional element",gw="An optional element may not follow a variadic element";var rA="A defaultable element may not follow an optional element without a default";var tA={},M9=(W,$)=>{if(typeof W==="string"){if($.args&&Object.keys($.args).some((X)=>W.includes(X)))return cG(W,$);let Y=tA[$.$.name]??={};return Y[W]??=cG(W,$)}return p1(W,"object")?aA(W,$):A(nG(Q1(W)))},aA=(W,$)=>{let Y=I6(W);switch(Y){case void 0:if(d(W,"root"))return W;return Cw(W,$);case"Array":return sA(W,$);case"RegExp":return $.$.node("intersection",{domain:"string",pattern:W},{prereduced:!0});case"Function":{let X=p$(W)?W():W;if(d(X,"root"))return X;return A(nG("Function"))}default:return A(nG(Y??G0(W)))}},sA=(W,$)=>jw(W,$)??yw(W,$),nG=(W)=>`Type definitions must be strings or objects (was ${W})`;class rG 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((...Y)=>{if(Y.length===1)return W.parse(Y[0]);if(Y.length===2&&typeof Y[0]==="string"&&Y[0][0]==="<"&&Y[0].at(-1)===">"){let X=Y[0].slice(1,-1),G=W.parseGenericParams(X,{});return new o$(G,Y[1],W,W,null)}return W.parse(Y)},{bind:W,attach:$})}}var u8=R;class V9 extends H9{get ambientAttachments(){if(!u8.typeAttachments)return;return this.cacheGetter("ambientAttachments",X0(u8.typeAttachments,(W,$)=>[W,this.bindReference($)]))}preparseOwnAliasEntry(W,$){let Y=W.indexOf("<");if(Y===-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)!==">")A("'>' must be the last character of a generic declaration in a scope");let X=W.slice(0,Y),G=W.slice(Y+1,-1);return[X,()=>{let J=this.parseGenericParams(G,{alias:X});return GF(J,$,this)}]}parseGenericParams(W,$){return U9(new D$(W),[],this.createParseContext({...$,def:W,prefix:"generic"}))}normalizeRootScopeValue(W){if(p$(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 X=M9(W,$);if(k0(X)){if(X[1]==="=")return A(_9);if(X[1]==="?")return A(Q9)}return X}unit=(W)=>this.units([W]);valueOf=(W)=>this.units(Rz(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(($,Y)=>$.and(this.parse(Y)),this.intrinsic.unknown);merge=(...W)=>W.reduce(($,Y)=>$.merge(this.parse(Y)),this.intrinsic.object);pipe=(...W)=>this.intrinsic.unknown.pipe(...W);match=new dG(this);declare=()=>({type:this.type});define(W){return W}type=new rG(this);static scope=(W,$={})=>new V9(W,$);static module=(W,$={})=>this.scope(W,$).export()}var tG=Object.assign(V9.scope,{define:(W)=>W}),_0=V9;class mw extends R1{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var eA=DW(["base",r.object],["props",r.object])((W)=>W.base.merge(W.props),mw),pw=_0.module({Key:r.key,Merge:eA});class uw extends R1{}var WL=DW("element")((W)=>{let $=W.element.exclude(r.Array),Y=$.array();return $.rawOr(Y).pipe(m$).distribute((X)=>X.assertHasKind("morph").declareOut(Y),N0)},uw),cw=_0.module({root:r.Array,readonly:"root",index:r.nonNegativeIntegerString,liftFrom:WL},{name:"Array"});var aG=N0(["string",j2.FileConstructor]),$L=aG.rawOr(aG.array()),dw=N0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:$L}}),lw=_0.module({root:["instanceof",FormData],value:aG,parsed:dw,parse:N0({in:FormData,morphs:(W)=>{let $={};for(let[Y,X]of W)if(Y in $){let G=$[Y];if(typeof G==="string"||G instanceof j2.FileConstructor)$[Y]=[G,X];else G.push(X)}else $[Y]=X;return $},declaredOut:dw})},{name:"FormData"});var ow=_0.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 YL={Boolean:1,Number:1,String:1},iw=_0.module({...X0({...y7,...g7},(W,$)=>(W in YL)?[]:[W,["instanceof",$]]),Array:cw,TypedArray:ow,FormData:lw});var XL=N0({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"}),GL=N0({domain:"number",divisor:1}),O9=_0.module({root:r.number,integer:GL,epoch:XL,safe:N0({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,$,Y)=>{let X={domain:"string",pattern:{rule:W.source,flags:W.flags,meta:$}};if(Y)X.meta={format:Y};return g8("intersection",X)},nw=g0(x6,"a well-formed integer string"),HU=_0.module({root:nw,parse:N0({in:nw,morphs:(W,$)=>{let Y=Number.parseInt(W);return Number.isSafeInteger(Y)?Y:$.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:r.integer})},{name:"string.integer"}),JL=g0(/^[\dA-Fa-f]+$/,"hex characters only"),HL=_0.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"),TL=_0.module({root:N0({in:"string",morphs:(W)=>W.charAt(0).toUpperCase()+W.slice(1),declaredOut:rw}),preformatted:rw},{name:"string.capitalize"}),QL=(W)=>{let $=W.replaceAll(/[ -]+/g,""),Y=0,X,G,J=!1;for(let H=$.length-1;H>=0;H--){if(X=$.substring(H,H+1),G=Number.parseInt(X,10),J)G*=2,Y+=G>=10?G%10+1:G;else Y+=G;J=!J}return!!(Y%10===0?$:!1)},_L=/^(?: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}))$/,zL=N0({domain:"string",pattern:{meta:"a credit card number",rule:_L.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 wL=(W)=>!Number.isNaN(new Date(W).valueOf()),tw=N0({domain:"string",predicate:{meta:"a parsable date",predicate:wL}}).assertHasKind("intersection"),aw=HU.root.internal.narrow((W,$)=>{let Y=Number.parseInt(W),X=O9.epoch(Y);if(X instanceof c1)return $.errors.merge(X),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),UL=_0.module({root:aw,parse:N0({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"),DL=_0.module({root:sw,parse:N0({in:sw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.iso"}),ML=_0.module({root:tw,parse:N0({declaredIn:tw,in:"string",morphs:(W,$)=>{let Y=new Date(W);if(Number.isNaN(Y.valueOf()))return $.error("a parsable date");return Y},declaredOut:r.Date}),iso:DL,epoch:UL},{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])",i$=`(${ew}[.]){3}${ew}`,OL=new RegExp(`^${i$}$`),s0="(?:[0-9a-fA-F]{1,4})",KL=new RegExp(`^((?:${s0}:){7}(?:${s0}|:)|(?:${s0}:){6}(?:${i$}|:${s0}|:)|(?:${s0}:){5}(?::${i$}|(:${s0}){1,2}|:)|(?:${s0}:){4}(?:(:${s0}){0,1}:${i$}|(:${s0}){1,3}|:)|(?:${s0}:){3}(?:(:${s0}){0,2}:${i$}|(:${s0}){1,4}|:)|(?:${s0}:){2}(?:(:${s0}){0,3}:${i$}|(:${s0}){1,5}|:)|(?:${s0}:){1}(?:(:${s0}){0,4}:${i$}|(:${s0}){1,6}|:)|(?::((?::${s0}){0,5}:${i$}|(?::${s0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),EL=_0.module({root:["v4 | v6","@","an IP address"],v4:g0(OL,"an IPv4 address","ipv4"),v6:g0(KL,"an IPv6 address","ipv6")},{name:"string.ip"}),c8="a JSON string",TU=(W)=>{if(!(W instanceof SyntaxError))throw W;return`must be ${c8} (${W})`},AL=N0({meta:c8,domain:"string",predicate:{meta:c8,predicate:(W,$)=>{try{return JSON.parse(W),!0}catch(Y){return $.reject({code:"predicate",expected:c8,problem:TU(Y)})}}}}),LL=(W,$)=>{if(W.length===0)return $.error({code:"predicate",expected:c8,actual:"empty"});try{return JSON.parse(W)}catch(Y){return $.error({code:"predicate",expected:c8,problem:TU(Y)})}},ZL=_0.module({root:AL,parse:N0({meta:"safe JSON string parser",in:"string",morphs:LL,declaredOut:r.jsonObject})},{name:"string.json"}),WU=g0(/^[a-z]*$/,"only lowercase letters"),NL=_0.module({root:N0({in:"string",morphs:(W)=>W.toLowerCase(),declaredOut:WU}),preformatted:WU},{name:"string.lower"}),QU=["NFC","NFD","NFKC","NFKD"],XY=X0(QU,(W,$)=>[$,N0({domain:"string",predicate:(Y)=>Y.normalize($)===Y,meta:`${$}-normalized unicode`})]),K9=X0(QU,(W,$)=>[$,N0({in:"string",morphs:(Y)=>Y.normalize($),declaredOut:XY[$]})]),RL=_0.module({root:K9.NFC,preformatted:XY.NFC},{name:"string.normalize.NFC"}),BL=_0.module({root:K9.NFD,preformatted:XY.NFD},{name:"string.normalize.NFD"}),SL=_0.module({root:K9.NFKC,preformatted:XY.NFKC},{name:"string.normalize.NFKC"}),qL=_0.module({root:K9.NFKD,preformatted:XY.NFKD},{name:"string.normalize.NFKD"}),CL=_0.module({root:"NFC",NFC:RL,NFD:BL,NFKC:SL,NFKD:qL},{name:"string.normalize"}),$U=g0(lX,"a well-formed numeric string"),kL=_0.module({root:$U,parse:N0({in:$U,morphs:(W)=>Number.parseFloat(W),declaredOut:r.number})},{name:"string.numeric"}),YU="a regex pattern",jL=N0({domain:"string",predicate:{meta:YU,predicate:(W,$)=>{try{return new RegExp(W),!0}catch(Y){return $.reject({code:"predicate",expected:YU,problem:String(Y)})}}},meta:{format:"regex"}}),IL=/^(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-]+)*))?$/,PL=g0(IL,"a semantic version (see https://semver.org/)"),XU=g0(/^\S.*\S$|^\S?$/,"trimmed"),fL=_0.module({root:N0({in:"string",morphs:(W)=>W.trim(),declaredOut:XU}),preformatted:XU},{name:"string.trim"}),GU=g0(/^[A-Z]*$/,"only uppercase letters"),bL=_0.module({root:N0({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=N0({domain:"string",predicate:{meta:"a URL string",predicate:xL},meta:{format:"uri"}}),vL=_0.module({root:JU,parse:N0({declaredIn:JU,in:"string",morphs:(W,$)=>{try{return new URL(W)}catch{return $.error("a URL string")}},declaredOut:N0(URL)})},{name:"string.url"}),yL=_0.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"}),_U=_0.module({root:r.string,alpha:g0(/^[A-Za-z]*$/,"only letters"),alphanumeric:g0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:JL,base64:HL,capitalize:TL,creditCard:zL,date:ML,digits:g0(/^\d*$/,"only digits 0-9"),email:VL,integer:HU,ip:EL,json:ZL,lower:NL,normalize:CL,numeric:kL,regex:jL,semver:PL,trim:fL,upper:bL,url:vL,uuid:yL},{name:"string"});var zU=_0.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}),FU=_0.module({root:r.unknown,any:r.unknown},{name:"unknown"}),hL=_0.module({root:r.jsonObject,stringify:g8("morph",{in:r.jsonObject,morphs:(W)=>JSON.stringify(W),declaredOut:r.string})},{name:"object.json"}),wU=_0.module({root:r.object,json:hL},{name:"object"});class UU extends R1{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var gL=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 mL=DW(["T",r.object],["K",r.key])((W)=>W.T.pick(W.K),DU);class MU extends R1{description='omit a set of properties from an object like `Omit(User, "age")`'}var pL=DW(["T",r.object],["K",r.key])((W)=>W.T.omit(W.K),MU);class VU extends R1{description="make all named properties of an object optional like `Partial(User)`"}var uL=DW(["T",r.object])((W)=>W.T.partial(),VU);class OU extends R1{description="make all named properties of an object required like `Required(User)`"}var cL=DW(["T",r.object])((W)=>W.T.required(),OU);class KU extends R1{description='exclude branches of a union like `Exclude("boolean", "true")`'}var dL=DW("T","U")((W)=>W.T.exclude(W.U),KU);class EU extends R1{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var lL=DW("T","U")((W)=>W.T.extract(W.U),EU),AU=_0.module({Exclude:dL,Extract:lL,Omit:pL,Partial:uL,Pick:mL,Record:gL,Required:cL});var n$=tG({...zU,...AU,...iw,...pw,string:_U,number:O9,object:wU,unknown:FU},{prereducedAliases:!0,name:"ark"}),z1=n$.export();Object.assign(u8.ambient,z1);u8.typeAttachments={string:z1.string.root,number:z1.number.root,bigint:z1.bigint,boolean:z1.boolean,symbol:z1.symbol,undefined:z1.undefined,null:z1.null,object:z1.object.root,unknown:z1.unknown.root,false:z1.false,true:z1.true,never:z1.never,arrayIndex:z1.Array.index,Key:z1.Key,Record:z1.Record,Array:z1.Array.root,Date:z1.Date};var jW=Object.assign(n$.type,u8.typeAttachments),oL=n$.match,iL=n$.generic,Rs=n$.schema,nL=n$.define,rL=n$.declare;var tL="__vite_start_time"in globalThis,aL=typeof window!=="undefined",us="vitest"in globalThis,M$=jW("string"),LU=jW('"true" | "false" | undefined'),V$=b7({isServer:!tL&&!aL,server:{CI:jW("string | undefined").pipe(Boolean),POSTGRES_USER:M$,POSTGRES_PASSWORD:M$,POSTGRES_DATABASE:M$,POSTGRES_HOST:M$,POSTGRES_PORT:M$.pipe((W)=>Number.parseInt(W,10)),BACKEND_PORT:M$.pipe((W)=>Number.parseInt(W,10)),RUN_WORKERS_FROM_SOURCE:LU.pipe((W)=>W==="true"),FRONTEND_PORT:M$.pipe((W)=>Number.parseInt(W,10)),FRONTEND_ORIGINS:M$.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:M$,VITE_DEV_FRONTEND_HOST:jW("string | undefined"),VITE_DEV_HTTPS:LU.pipe((W)=>W==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var eG={};vD(eG,{users:()=>f2,untrackedUserColumnNames:()=>sL,twoFactorMethod:()=>SU,trackedUserColumnName:()=>eL,trackableUserColumnNames:()=>RU,signInHistory:()=>$Z,role:()=>NU,players:()=>sG,passwordResetAttempts:()=>YZ,games:()=>E9,banishedIps:()=>A9,accountActions:()=>WZ,accountAction:()=>BU});function ZU(W){return M`lower(${W})`}var NU=Q6("role",["admin","user"]),f2=y$("users",{id:_W().primaryKey().defaultRandom(),username:P1({length:16}).notNull(),emailOffered:P1({length:254}).notNull(),emailVerified:P1({length:254}),password:P1({length:254}),createdAt:BW({withTimezone:!0}).notNull().defaultNow(),createdIp:P1({length:45}).notNull(),isActive:D6().notNull().default(!1),verifiedAt:BW({withTimezone:!0}),userRole:NU().default("user")},(W)=>[k7("usernameUniqueIndex").on(ZU(W.username)),k7("emailVerifiedUniqueIndex").on(ZU(W.emailVerified))]),sL=["id","createdAt","createdIp","isActive","verifiedAt"],RU=["username","emailOffered","emailVerified","password","userRole"],eL=Q6("trackedUserColumnName",RU),BU=Q6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),WZ=y$("accountActions",{userId:_W().references(()=>f2.id).primaryKey(),action:BU().notNull(),code:P1({length:254}).notNull(),wrongCodeCount:M6().notNull().default(0),expiresAt:BW({withTimezone:!0}).notNull()}),E9=y$("games",{id:_W().primaryKey().defaultRandom()}),sG=y$("players",{userId:_W().notNull().references(()=>f2.id,{onDelete:"cascade"}),gameId:_W().notNull().references(()=>E9.id,{onDelete:"cascade"}),score:M6().notNull()},(W)=>[U_({name:"players_userId_gameId_pk",columns:[W.userId,W.gameId]})]),$Z=y$("signInHistory",{id:_W().primaryKey().defaultRandom(),userId:_W().references(()=>f2.id,{onDelete:"cascade"}),signInTime:BW({withTimezone:!0}).notNull().defaultNow(),ipAddress:P1({length:45}).notNull(),userAgent:P1({length:1024}),successful:D6().notNull().default(!1)}),SU=Q6("twoFactorMethod",["email","phone"]),YZ=y$("passwordResetAttempts",{id:_W().primaryKey().defaultRandom(),userId:_W().notNull().references(()=>f2.id,{onDelete:"cascade"}),requestedIp:P1({length:45}).notNull(),requestedAt:BW({withTimezone:!0}).notNull().defaultNow(),succeededIp:P1({length:45}),succeededAt:BW({withTimezone:!0}),verificationMethod:SU().notNull()}),A9=y$("banishedIps",{ip:P1({length:45}).primaryKey(),reason:P1({length:2048}).notNull(),banishedAt:BW({withTimezone:!0}).notNull().defaultNow(),banishedUntil:BW({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class WJ{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(XZ.resolve(__dirname,"notify_update.sql"));let W=[w1(f2),w1(E9),w1(sG)];await this.sql`SELECT create_notify_triggers(${this.sql.array(W)})`,await this.sql.listen("table_update",($)=>{let Y=$.split(","),X=Y[0],G=Y[1],J=`${X}("${G}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(W=!1,$={host:V$.POSTGRES_HOST,port:V$.POSTGRES_PORT,user:V$.POSTGRES_USER,password:V$.POSTGRES_PASSWORD,database:V$.POSTGRES_DATABASE}){this.options=$,this.sql=Z8($),this.drizzle=cX(this.sql,{schema:eG,logger:W})}observe(W,$){if(!this.observers.has(W))this.observers.set(W,new Z0);this.observers.get(W).subscribe("SINGLETON",$)}}import{resolve as HZ}from"path";import{existsSync as $J,mkdirSync as qU,readFileSync as GZ,readdirSync as CU,rmSync as kU,statSync as jU,writeFileSync as JZ}from"fs";import{resolve as YJ}from"path";var IU=class{rootDir;get initialized(){return $J(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 $=YJ(this.rootDir,W);if($J($))return GZ($,"utf-8");return null}setItem(W,$){this.initialize();let Y=YJ(this.rootDir,W);JZ(Y,$)}removeItem(W){let $=YJ(this.rootDir,W);if($J($))this.initialize(),kU($)}key(W){return CU(this.rootDir).sort((X,G)=>{let J=jU(X);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 XJ=new IU({path:HZ(process.cwd(),"storage")});import*as L9 from"fs";import*as PU from"readline";function TZ(W){let Y=W.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(X,G,J,H,T)=>{let _={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}-${_}-${G}T${T}`});return new Date(Y)}async function fU(W,$="/var/log/nginx/access.log",Y=new Date){let X=new Map;if(!L9.existsSync($))return W.error(`Log file not found: ${$}`),X;let G=L9.createReadStream($),J=PU.createInterface({input:G,crlfDelay:Number.POSITIVE_INFINITY}),H=new Date(Y.getTime()-3600000);return J.on("line",(T)=>{let Q=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,_=T.match(Q);if(_?.groups){let z=_.groups.ip,F=_.groups.dateTime,w=TZ(F);if(!Number.isNaN(w.getTime())){if(w>=H&&w<=Y){let O=X.get(z);if(!O)O=[],X.set(z,O);O.push(T)}}else W.error(`Failed to parse date: ${F}`)}}),new Promise((T,Q)=>{J.on("error",(_)=>{Q(_)}),J.on("close",()=>{T(X)})})}function bU(W){return W.toJsonSchema()}var QZ=["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
|
|
151
|
+
`)+"}");class SU{config;resolvedConfig;name;get[C4](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor($,T){if(this.config=OX(I.config,T),this.resolvedConfig=OX(I.resolvedConfig,T),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(a_).length}`,this.name in a_)L(`A Scope already named ${this.name} already exists`);a_[this.name]=this;let W=Object.entries($).map((X)=>this.preparseOwnAliasEntry(...X));for(let[X,Y]of W){let U=X;if(X[0]==="#"){if(U=X.slice(1),U in this.aliases)L(IK(U));this.aliases[U]=Y}else{if(U in this.aliases)L(IK(X));this.aliases[U]=Y,this.exportedNames.push(U)}if(!o(Y,"module")&&!o(Y,"generic")&&!c1(Y)){let G=this.preparseOwnDefinitionFormat(Y,{alias:U});this.resolutions[U]=o(G,"root")?this.bindReference(G):this.createParseContext(G).id}}kK??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[kK.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=I.intrinsic?Y$(I.intrinsic,(X,Y)=>X.startsWith("json")?[]:[X,this.bindReference(Y)]):{}}cacheGetter($,T){return Object.defineProperty(this,$,{value:T}),T}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema($){return $}generic=(...$)=>{let T=this;return(W,X)=>new l1($,X?new OU(W):W,T,T,X??null)};units=($,T)=>{let W=[];for(let Y of $)if(!W.includes(Y))W.push(Y);let X=W.map((Y)=>this.node("unit",{unit:Y},T));return this.node("union",X,{...T,prereduced:!0})};lazyResolutions=[];lazilyResolve($,T){let W=this.node("alias",{reference:T??"synthetic",resolve:$},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(W);return W}schema=($,T)=>this.finalize(this.parseSchema($,T));parseSchema=($,T)=>this.node(MX($),$,T);preparseNode($,T,W){let X=typeof $==="string"?$:MX(T,$);if(v$(T)&&T.kind===X)return T;if(X==="alias"&&!W?.prereduced){let{reference:G}=RX.implementation.normalize(T,this);if(G.startsWith("$")){let J=this.resolveRoot(G.slice(1));T=J,X=J.kind}}else if(X==="union"&&c4(T,"object")){let G=tP(T);if(G?.length===1)T=G[0],X=MX(T)}if(v$(T)&&T.kind===X)return T;let U=pT[X].normalize?.(T,this)??T;if(v$(U))return U.kind===X?U:aP(X,U.kind);return{...W,$:this,kind:X,def:U,prefix:W.alias??X}}bindReference($){let T;if(v$($))T=$.$===this?$:new $.constructor($.attachments,this);else T=$.$===this?$:new l1($.params,$.bodyDef,$.$,this,$.hkt);if(!this.resolved)Object.assign(this.referencesById,T.referencesById);return T}resolveRoot($){return this.maybeResolveRoot($)??L($5($))}maybeResolveRoot($){let T=this.maybeResolve($);if(o(T,"generic"))return;return T}maybeResolveSubalias($){return s_(this.aliases,$)??s_(this.ambient,$)}get ambient(){return I.ambient}maybeResolve($){let T=this.resolutions[$];if(T){if(typeof T!=="string")return this.bindReference(T);let X=v4[T];if(o(X,"root"))return this.resolutions[$]=X;if(o(X,"context")){if(X.phase==="resolving")return this.node("alias",{reference:`$${$}`},{prereduced:!0});if(X.phase==="resolved")return O$(`Unexpected resolved context for was uncached by its scope: ${U$(X)}`);X.phase="resolving";let Y=this.bindReference(this.parseOwnDefinitionFormat(X.def,X));return X.phase="resolved",v4[Y.id]=Y,v4[X.id]=Y,this.resolutions[$]=Y}return O$(`Unexpected nodesById entry for ${T}: ${U$(X)}`)}let W=this.aliases[$]??this.ambient?.[$];if(!W)return this.maybeResolveSubalias($);if(W=this.normalizeRootScopeValue(W),o(W,"generic"))return this.resolutions[$]=this.bindReference(W);if(o(W,"module")){if(!W.root)L(bK($));return this.resolutions[$]=this.bindReference(W.root)}return this.resolutions[$]=this.parse(W,{alias:$})}createParseContext($){let T=$.id??x_($.prefix);return v4[T]=Object.assign($,{[C4]:"context",$:this,id:T,phase:"unresolved"})}traversal($){return new B6($,this.resolvedConfig)}import(...$){return new lT(Y$(this.export(...$),(T,W)=>[`#${T}`,W]))}precompilation;_exportedResolutions;_exports;export(...$){if(!this._exports){this._exports={};for(let W of this.exportedNames){let X=this.aliases[W];this._exports[W]=o(X,"module")?t_(X,this):qK(this.maybeResolve(W))}for(let W of this.lazyResolutions)W.resolution;if(this._exportedResolutions=xK(this,this._exports),this._json=jK(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let W=vK(this.references);this.precompilation=W.write(PK,4),CK(this.references,W)}this.resolved=!0}let T=$.length?$:this.exportedNames;return new lT(Y$(T,(W,X)=>[X,this._exports[X]]))}resolve($){return this.export()[$]}node=($,T,W={})=>{let X=this.preparseNode($,T,W);if(v$(X))return this.bindReference(X);let Y=this.createParseContext(X),U=b_(Y),G=this.bindReference(U);return v4[Y.id]=G};parse=($,T={})=>this.finalize(this.parseDefinition($,T));parseDefinition($,T={}){if(o($,"root"))return this.bindReference($);let W=this.preparseOwnDefinitionFormat($,T);if(o(W,"root"))return this.bindReference(W);let X=this.createParseContext(W);v4[X.id]=X;let Y=this.bindReference(this.parseOwnDefinitionFormat($,X));if(Y.isCyclic)Y=TK(Y,X.id);return v4[X.id]=Y,Y}finalize($){if(qK($),!$.precompilation&&!this.resolvedConfig.jitless)sP($.references);return $}}class e_ extends SU{parseOwnDefinitionFormat($,T){return b_(T)}preparseOwnDefinitionFormat($,T){return this.preparseNode(MX($),$,T)}preparseOwnAliasEntry($,T){return[$,T]}normalizeRootScopeValue($){return $}}var qK=($)=>{let T=$.references.filter((W)=>W.hasKind("alias"));for(let W of T){Object.assign(W.referencesById,W.resolution.referencesById);for(let X of $.references)if(W.id in X.referencesById)Object.assign(X.referencesById,W.referencesById)}return $},jK=($)=>Y$($,(T,W)=>[T,o(W,"root")||o(W,"generic")?W.json:o(W,"module")?jK(W):O$(`Unexpected resolution ${U$(W)}`)]),s_=($,T)=>{let W=T.indexOf(".");if(W===-1)return;let X=T.slice(0,W),Y=$[X];if(Y===void 0)return;if(!o(Y,"module"))return L(eP(X));let U=T.slice(W+1),G=Y[U];if(G===void 0)return s_(Y,U);if(o(G,"root")||o(G,"generic"))return G;if(o(G,"module"))return G.root??L(bK(T));O$(`Unexpected resolution for alias '${T}': ${U$(G)}`)},BU=($,T)=>new e_($,T),qX=new e_({});var xK=($,T)=>{let W={};for(let X in T){let Y=T[X];if(o(Y,"module")){let U=xK($,Y),G=Y$(U,(J,z)=>[`${X}.${J}`,z]);Object.assign(W,G)}else if(o(Y,"root")||o(Y,"generic"))W[X]=Y;else O$(`Unexpected scope resolution ${U$(Y)}`)}return W},$5=($)=>`'${$}' is unresolvable`,eP=($)=>`'${$}' must reference a module to be accessed using dot syntax`,bK=($)=>`Reference to submodule '${$}' must specify an alias`;qX.export();var{schema:E$,node:rT,defineSchema:R0$,generic:Z6}=qX;var T5="^(?:0|[1-9]\\d*)$",$C=new RegExp(T5),q0$=d$($C);var fK=BU({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();I.intrinsic={...fK};var yK=BU({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:T5}},{prereducedAliases:!0}).export();Object.assign(I.intrinsic,yK);var TC=BU({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),n={...fK,...yK,...TC,emptyStructure:rT("structure",{},{prereduced:!0})};I.intrinsic={...n};var gK=($)=>typeof $==="string"&&$[0]==="d"&&($[1]==="'"||$[1]==='"')&&$.at(-1)===$[1],hK=($)=>$.toString()!=="Invalid Date",mK=($)=>$.slice(2,-1),W5=($)=>`'${$}' could not be parsed by the Date constructor`,cK=($,T)=>WC($,T),WC=($,T)=>{let W=new Date($);if(hK(W))return W;let X=EV($);if(X!==void 0){let Y=new Date(X);if(hK(Y))return Y}return T?L(T===!0?W5($):T):void 0};var X5=($,T)=>{let W=$.scanner.shiftUntil(XC[pK[T]]);if($.scanner.lookahead==="")return $.error(UC(W,T));if($.scanner.shift(),T==="/"){try{new RegExp(W)}catch(X){L(String(X))}$.root=$.ctx.$.node("intersection",{domain:"string",pattern:W},{prereduced:!0})}else if(z4(T,Y5))$.root=$.ctx.$.node("unit",{unit:W});else{let X=cK(W,W5(W));$.root=$.ctx.$.node("unit",{meta:W,unit:X})}},Y5={"'":1,'"':1},uK={"/":1,"'":1,'"':1},pK={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},XC={"'":($)=>$.lookahead==="'",'"':($)=>$.lookahead==='"',"/":($)=>$.lookahead==="/"},YC={'"':"double-quote","'":"single-quote","/":"forward slash"},UC=($,T)=>`${T}${$} requires a closing ${YC[pK[T]]}`;var dK=($)=>`Private type references should not include '#'. Use '${$}' instead.`,RU="Optional definitions like 'string?' are only valid as properties in an object or tuple",IU="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var oK={">":!0,">=":!0},lK={"<":!0,"<=":!0};var iT={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},rK=($)=>`Unmatched )${$===""?"":` before ${$}`}`,kU=($)=>`Missing ${$}`,iK=($,T)=>`Left bounds are only valid when paired with right bounds (try ...${T}${$})`,qU=($)=>`Left-bounded expressions must specify their limits using < or <= (was ${$})`,nK=($,T,W,X)=>`An expression may have at most one left bound (parsed ${$}${iT[T]}, ${W}${iT[X]})`;var tK=($,T,W)=>aK($,T,W,[]),aK=($,T,W,X)=>{let Y=W.parseUntilFinalizer();if(X.push(Y.root),Y.finalizer===">"){if(X.length!==T.params.length)return W.error(U5($,T.names,X.map((U)=>U.expression)));return X}if(Y.finalizer===",")return aK($,T,W,X);return Y.error(kU(">"))},U5=($,T,W)=>`${$}<${T.join(", ")}> requires exactly ${T.length} args (got ${W.length}${W.length===0?"":`: ${W.join(", ")}`})`;var G5=($)=>{let T=$.scanner.shiftUntilNextTerminator();if(T==="keyof")$.addPrefix("keyof");else $.root=JC($,T)},GC=($,T,W)=>{if(W.scanner.shiftUntilNonWhitespace(),W.scanner.shift()!=="<")return W.error(U5($,T.names,[]));let Y=tK($,T,W);return T(...Y)},JC=($,T)=>wC($,T)??zC($,T)??$.error(T===""?$.scanner.lookahead==="#"?dK($.shiftedByOne().scanner.shiftUntilNextTerminator()):J5($):$5(T)),wC=($,T)=>{if($.ctx.args?.[T]){let X=$.ctx.args[T];if(typeof X!=="string")return X;return $.ctx.$.node("alias",{reference:X},{prereduced:!0})}let W=$.ctx.$.maybeResolve(T);if(o(W,"root"))return W;if(W===void 0)return;if(o(W,"generic"))return GC(T,W,$);return L(`Unexpected resolution ${U$(W)}`)},zC=($,T)=>{let W=MV(T);if(W!==void 0)return $.ctx.$.node("unit",{unit:W});let X=NV(T);if(X!==void 0)return $.ctx.$.node("unit",{unit:X})},J5=($)=>{let T=$.previousOperator();return T?w5(T,$.scanner.unscanned):_C($.scanner.unscanned)},w5=($,T="")=>`Token '${$}' requires a right operand${T?` before '${T}'`:""}`,_C=($)=>`Expected an expression${$?` before '${$}'`:""}`;var z5=($)=>$.scanner.lookahead===""?$.error(J5($)):$.scanner.lookahead==="("?$.shiftedByOne().reduceGroupOpen():$.scanner.lookaheadIsIn(uK)?X5($,$.scanner.shift()):$.scanner.lookaheadIsIn(u1)?z5($.shiftedByOne()):$.scanner.lookahead==="d"?$.scanner.nextLookahead in Y5?X5($,`${$.scanner.shift()}${$.scanner.shift()}`):G5($):G5($);class Z1 extends Z_{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in Z1.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...u1};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=($,T)=>$===">"?T[0]==="="?T[1]==="=":T.trimStart()===""||z4(T.trimStart()[0],Z1.terminatingChars):$==="="?T[0]!=="=":$===","||$==="?"}var eK=($,T)=>{let W=HC($,T);if($.root.hasKind("unit")){if(typeof $.root.unit==="number"){$.reduceLeftBound($.root.unit,W),$.unsetRoot();return}if($.root.unit instanceof Date){let X=`d'${$.root.description??$.root.unit.toISOString()}'`;$.unsetRoot(),$.reduceLeftBound(X,W);return}}return QC($,W)},$E={"<":1,">":1,"=":1},HC=($,T)=>$.scanner.lookaheadIs("=")?`${T}${$.scanner.shift()}`:T;var sK=($,T,W,X)=>{if(W.extends(I.intrinsic.number)){if(typeof T!=="number")return L(_5($,T,X));return $==="=="?["min","max"]:$[0]===">"?["min"]:["max"]}if(W.extends(I.intrinsic.lengthBoundable)){if(typeof T!=="number")return L(_5($,T,X));return $==="=="?["exactLength"]:$[0]===">"?["minLength"]:["maxLength"]}if(W.extends(I.intrinsic.Date))return $==="=="?["after","before"]:$[0]===">"?["after"]:["before"];return L(uV(W.expression))},FC=($)=>({rule:gK($.limit)?mK($.limit):$.limit,exclusive:$.comparator.length===1}),QC=($,T)=>{let W=$.unsetRoot(),X=$.scanner.location;$.parseOperand();let Y=$.unsetRoot(),U=$.scanner.sliceChars(X,$.scanner.location);if($.root=W,!Y.hasKind("unit")||typeof Y.unit!=="number"&&!(Y.unit instanceof Date))return $.error(_5(T,U,"right"));let G=Y.unit,J=T.length===1,z=sK(T,typeof G==="number"?G:U,W,"right");for(let H of z)$.constrainRoot(H,T==="=="?{rule:G}:{rule:G,exclusive:J});if(!$.branches.leftBound)return;if(!z4(T,lK))return $.error(qU(T));let w=sK($.branches.leftBound.comparator,$.branches.leftBound.limit,W,"left");$.constrainRoot(w[0],FC($.branches.leftBound)),$.branches.leftBound=null},_5=($,T,W)=>`Comparator ${W==="left"?iT[$]:$} must be ${W==="left"?"preceded":"followed"} by a corresponding literal (was ${T})`;var TE=($)=>{$.scanner.shiftUntilNonWhitespace();let T=$.scanner.shiftUntilNextTerminator();$.root=$.root.brand(T)};var XE=($)=>{let T=$.scanner.shiftUntilNextTerminator(),W=AV(T,{errorOnFail:WE(T)});if(W===0)$.error(WE(0));$.root=$.root.constrain("divisor",W)},WE=($)=>`% operator must be followed by a non-zero integer literal (was ${$})`;var H5=($)=>{let T=$.scanner.shift();return T===""?$.finalize(""):T==="["?$.scanner.shift()==="]"?$.setRoot($.root.array()):$.error(ZC):T==="|"?$.scanner.lookahead===">"?$.shiftedByOne().pushRootToBranch("|>"):$.pushRootToBranch(T):T==="&"?$.pushRootToBranch(T):T===")"?$.finalizeGroup():Z1.lookaheadIsFinalizing(T,$.scanner.unscanned)?$.finalize(T):z4(T,$E)?eK($,T):T==="%"?XE($):T==="#"?TE($):(T in u1)?H5($):$.error(PU(T))},PU=($,T="")=>`'${$}' is not allowed here${T&&` (should be ${T})`}`,ZC="Missing expected ']'";var YE=($)=>{let T=$.unsetRoot();$.parseOperand();let W=$.unsetRoot();if(!W.hasKind("unit"))return $.error(DC(W.expression));let X=W.unit instanceof Date?()=>new Date(W.unit):W.unit;return[T,"=",X]},DC=($)=>`Default value '${$}' must a literal value`;var F5=($,T)=>{let W=T.$.maybeResolveRoot($);if(W)return W;if($.endsWith("[]")){let U=T.$.maybeResolveRoot($.slice(0,-2));if(U)return U.array()}let X=new nT(new Z1($),T),Y=OC(X);if(X.finalizer===">")L(PU(">"));return Y},OC=($)=>{$.parseOperand();let T=PX($).root;if(!T)return O$(`Root was unexpectedly unset after parsing string '${$.scanner.scanned}'`);if($.finalizer==="=")T=YE($);else if($.finalizer==="?")T=[T,"?"];if($.scanner.shiftUntilNonWhitespace(),$.scanner.lookahead)L(PU($.scanner.lookahead));return T},PX=($)=>{while($.finalizer===void 0)VC($);return $},VC=($)=>$.hasRoot()?$.parseOperator():$.parseOperand();class nT{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor($,T){this.scanner=$,this.ctx=T}error($){return L($)}hasRoot(){return this.root!==void 0}setRoot($){this.root=$}unsetRoot(){let $=this.root;return this.root=void 0,$}constrainRoot(...$){this.root=this.root.constrain($[0],$[1])}finalize($){if(this.groups.length)return this.error(kU(")"));this.finalizeBranches(),this.finalizer=$}reduceLeftBound($,T){let W=iT[T];if(!z4(W,oK))return this.error(qU(T));if(this.branches.leftBound)return this.error(nK(this.branches.leftBound.limit,this.branches.leftBound.comparator,$,W));this.branches.leftBound={comparator:W,limit:$}}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 $=this.groups.pop();if(!$)return this.error(rK(this.scanner.unscanned));this.branches=$}addPrefix($){this.branches.prefixes.push($)}applyPrefixes(){while(this.branches.prefixes.length){let $=this.branches.prefixes.pop();this.root=$==="keyof"?this.root.keyof():O$(`Unexpected prefix '${$}'`)}}pushRootToBranch($){this.assertRangeUnset(),this.applyPrefixes();let T=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(T)??T,$==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,$==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return PX(new nT(this.scanner,this.ctx))}parseOperator(){return H5(this)}parseOperand(){return z5(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(iK(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 KC="An empty string is not a valid generic parameter name",CU=($,T,W)=>{$.shiftUntilNonWhitespace();let X=$.shiftUntilNextTerminator();if(X===""){if($.lookahead===""&&T.length)return T;return L(KC)}return $.shiftUntilNonWhitespace(),EC($,X,T,W)},UE="extends ",EC=($,T,W,X)=>{if($.shiftUntilNonWhitespace(),$.unscanned.startsWith(UE))$.jumpForward(UE.length);else{if($.lookahead===",")$.shift();return W.push(T),CU($,W,X)}let Y=PX(new nT($,X));return W.push([T,Y.root]),CU($,W,X)};class Q5 extends S6{$;constructor($){super((...T)=>new CX($)(...T),{bind:$});this.$=$}in($){return new CX(this.$,$===void 0?void 0:this.$.parse($))}at($,T){return new CX(this.$).at($,T)}case($,T){return new CX(this.$).case($,T)}}class CX extends S6{$;in;key;branches=[];constructor($,T){super((W)=>this.caseEntries(Object.entries(W).map(([X,Y])=>X==="default"?[X,Y]:[this.$.parse(X),Y])));this.$=$,this.in=T}at($,T){if(this.key)L(AC);if(this.branches.length)L(MC);return this.key=$,T?this.match(T):this}case($,T){return this.caseEntry(this.$.parse($),T)}caseEntry($,T){let X=(this.key?this.$.parse({[this.key]:$}):$).pipe(T);return this.branches.push(X),this}match($){return this($)}strings($){return this.caseEntries(Object.entries($).map(([T,W])=>T==="default"?[T,W]:[this.$.node("unit",{unit:T}),W]))}caseEntries($){for(let T=0;T<$.length;T++){let[W,X]=$[T];if(W==="default"){if(T!==$.length-1)L("default may only be specified as the last key of a switch definition");return this.default(X)}if(typeof X!=="function")return L(`Value for case "${W}" must be a function (was ${w4(X)})`);this.caseEntry(W,X)}return this}default($){if(typeof $==="function")this.case(n.unknown,$);let T={branches:this.branches,ordered:!0};if($==="never"||$==="assert")T.meta={onFail:GE};let W=this.$.node("union",T);if(!this.in)return this.$.finalize(W);let X=this.in.pipe(W);if($==="never"||$==="assert")X=X.configureReferences({onFail:GE},"self");return this.$.finalize(X)}}var GE=($)=>$.throw(),MC="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",AC="At most one key matcher may be specified per expression";var vU=($,T)=>{if(I$($)){if($[1]==="=")return[T.$.parseOwnDefinitionFormat($[0],T),"=",$[2]];if($[1]==="?")return[T.$.parseOwnDefinitionFormat($[0],T),"?"]}return jU($,T)},JE="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",wE="Only required keys may specify default values, e.g. { value: 'number = 0' }";var zE=($,T)=>{let W,X={},Y=j0($);for(let[G,J]of Y){let z=SC(G);if(z.kind==="spread"){if(!m6(X))return L(LC);let D=T.$.parseOwnDefinitionFormat(J,T);if(D.equals(n.object))continue;if(!D.hasKind("intersection")||!D.basis?.equals(n.object))return L(BC(D.expression));W=D.structure;continue}if(z.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")L(NC(J));X.undeclared=J;continue}let w=vU(J,T),H=z;if(z.kind==="required"){if(!I$(w))Z5(X,"required",{key:z.normalized,value:w},T);else Z5(X,"optional",w[1]==="="?{key:z.normalized,value:w[0],default:w[2]}:{key:z.normalized,value:w[0]},T);continue}if(I$(w)){if(w[1]==="?")L(JE);if(w[1]==="=")L(wE)}if(z.kind==="optional"){Z5(X,"optional",{key:z.normalized,value:w},T);continue}let _=T.$.parseOwnDefinitionFormat(H.normalized,T),F=LU(_,w,T.$);if(F.index)X.index=Q$(X.index,F.index);if(F.required)X.required=Q$(X.required,F.required)}let U=T.$.node("structure",X);return T.$.parseSchema({domain:"object",structure:W?.merge(U)??U})},Z5=($,T,W,X)=>{$[T]=Q$($[T],X.$.node(T,W))},NC=($)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${U$($)})`,LC="Spread operator may only be used as the first key in an object",SC=($)=>typeof $==="symbol"?{kind:"required",normalized:$}:$.at(-1)==="?"?$.at(-2)===zX?{kind:"required",normalized:`${$.slice(0,-2)}?`}:{kind:"optional",normalized:$.slice(0,-1)}:$[0]==="["&&$.at(-1)==="]"?{kind:"index",normalized:$.slice(1,-1)}:$[0]===zX&&$[1]==="["&&$.at(-1)==="]"?{kind:"required",normalized:$.slice(1)}:$==="..."?{kind:"spread"}:$==="+"?{kind:"undeclared"}:{kind:"required",normalized:$==="\\..."?"...":$==="\\+"?"+":$},BC=($)=>`Spread operand must resolve to an object literal type (was ${$})`;var HE=($,T)=>bC($)?DE[$[0]]($,T):jC($)?ZE[$[1]]($,T):null,RC=($,T)=>T.$.parseOwnDefinitionFormat($[1],T).keyof(),D5=($,T)=>{if($[2]===void 0)return L(w5($[1],""));let W=T.$.parseOwnDefinitionFormat($[0],T),X=T.$.parseOwnDefinitionFormat($[2],T);if($[1]==="|")return T.$.node("union",{branches:[W,X]});let Y=$[1]==="&"?o4(W,X,T.$):EX(W,X,T.$);if(Y instanceof f)return Y.throw();return Y},IC=($,T)=>T.$.parseOwnDefinitionFormat($[0],T).array(),kC=($,T)=>{if(typeof $[2]!=="function")return L(FE("=>",$[2]));return T.$.parseOwnDefinitionFormat($[0],T).pipe($[2])},FE=($,T)=>`${$===":"?"Narrow":"Morph"} expression requires a function following '${$}' (was ${typeof T})`,qC=($,T)=>{if(typeof $[2]!=="function")return L(FE(":",$[2]));return T.$.parseOwnDefinitionFormat($[0],T).constrain("predicate",$[2])},PC=($,T)=>T.$.parseOwnDefinitionFormat($[0],T).configureReferences($[2],"shallow"),QE=($)=>$,CC=QE({"[]":IC,"?":()=>L(RU)}),vC=QE({"|":D5,"&":D5,":":qC,"=>":kC,"|>":D5,"@":PC,"=":()=>L(IU)}),ZE={...CC,...vC},jC=($)=>ZE[$[1]]!==void 0,xC=($)=>$,DE=xC({keyof:RC,instanceof:($,T)=>{if(typeof $[1]!=="function")return L(_E(JX($[1])));let W=$.slice(1).map((X)=>typeof X==="function"?T.$.node("proto",{proto:X}):L(_E(JX(X))));return W.length===1?W[0]:T.$.node("union",{branches:W})},"===":($,T)=>T.$.units($.slice(1))}),bC=($)=>DE[$[0]]!==void 0,_E=($)=>`Expected a constructor following 'instanceof' operator (was ${$})`;var KE=($,T)=>{let W=[{}],X=0;while(X<$.length){let Y=!1;if($[X]==="..."&&X<$.length-1)Y=!0,X++;let U=vU($[X],T),[G,J,z]=!I$(U)?[U]:U;if(X++,Y){if(!G.extends(I.intrinsic.Array))return L(hC(G.expression));W=W.flatMap((w)=>G.distribute((H)=>yC(FU(w),H)))}else W=W.map((w)=>{if(J==="?")return EE(w,G);if(J==="=")return fC(w,G,z);return O5(w,G)})}return T.$.parseSchema(W.map((Y)=>m6(Y)?{proto:Array,exactLength:0}:{proto:Array,sequence:Y}))},O5=($,T)=>{if($.defaultables||$.optionals)return L($.variadic?r_:gC);if($.variadic)$.postfix=Q$($.postfix,T);else $.prefix=Q$($.prefix,T);return $},EE=($,T)=>{if($.variadic)return L(ME);return $.optionals=Q$($.optionals,T),$},fC=($,T,W)=>{if($.variadic)return L(ME);if($.optionals)return L(mC);return $.defaultables=Q$($.defaultables,[[T,W]]),$},OE=($,T)=>{if($.postfix)L(VE);if($.variadic){if(!$.variadic.equals(T))L(VE)}else $.variadic=T.internal;return $},yC=($,T)=>{let W=T.select({method:"find",kind:"sequence"});if(!W)return OE($,I.intrinsic.unknown);if(W.prefix)for(let X of W.prefix)O5($,X);if(W.optionals)for(let X of W.optionals)EE($,X);if(W.variadic)OE($,W.variadic);if(W.postfix)for(let X of W.postfix)O5($,X);return $},hC=($)=>`Spread element must be an array (was ${$})`,VE="A tuple may have at most one variadic element",gC="A required element may not follow an optional element",ME="An optional element may not follow a variadic element";var mC="A defaultable element may not follow an optional element without a default";var cC={},jU=($,T)=>{if(typeof $==="string"){if(T.args&&Object.keys(T.args).some((X)=>$.includes(X)))return F5($,T);let W=cC[T.$.name]??={};return W[$]??=F5($,T)}return c4($,"object")?uC($,T):L(V5(w4($)))},uC=($,T)=>{let W=GX($);switch(W){case void 0:if(o($,"root"))return $;return zE($,T);case"Array":return pC($,T);case"RegExp":return T.$.node("intersection",{domain:"string",pattern:$},{prereduced:!0});case"Function":{let X=c1($)?$():$;if(o(X,"root"))return X;return L(V5("Function"))}default:return L(V5(W??U$($)))}},pC=($,T)=>HE($,T)??KE($,T),V5=($)=>`Type definitions must be strings or objects (was ${$})`;class K5 extends S6{constructor($){let T=Object.assign({errors:p4,hkt:L4,$,raw:$.parse,module:$.constructor.module,scope:$.constructor.scope,define:$.define,match:$.match,generic:$.generic,schema:$.schema,keywords:$.ambient,unit:$.unit,enumerated:$.enumerated,instanceOf:$.instanceOf,valueOf:$.valueOf,or:$.or,and:$.and,merge:$.merge,pipe:$.pipe},$.ambientAttachments);super((...W)=>{if(W.length===1)return $.parse(W[0]);if(W.length===2&&typeof W[0]==="string"&&W[0][0]==="<"&&W[0].at(-1)===">"){let X=W[0].slice(1,-1),Y=$.parseGenericParams(X,{});return new l1(Y,W[1],$,$,null)}return $.parse(W)},{bind:$,attach:T})}}var tT=I;class xU extends SU{get ambientAttachments(){if(!tT.typeAttachments)return;return this.cacheGetter("ambientAttachments",Y$(tT.typeAttachments,($,T)=>[$,this.bindReference(T)]))}preparseOwnAliasEntry($,T){let W=$.indexOf("<");if(W===-1){if(o(T,"module")||o(T,"generic"))return[$,T];let U=this.name==="ark"?$:$==="root"?this.name:`${this.name}.${$}`,G=this.resolvedConfig.keywords?.[U];if(G)T=[T,"@",G];return[$,T]}if($.at(-1)!==">")L("'>' must be the last character of a generic declaration in a scope");let X=$.slice(0,W),Y=$.slice(W+1,-1);return[X,()=>{let U=this.parseGenericParams(Y,{alias:X});return gV(U,T,this)}]}parseGenericParams($,T){return CU(new Z1($),[],this.createParseContext({...T,def:$,prefix:"generic"}))}normalizeRootScopeValue($){if(c1($)&&!o($,"generic"))return $();return $}preparseOwnDefinitionFormat($,T){return{...T,def:$,prefix:T.alias??"type"}}parseOwnDefinitionFormat($,T){if(!(T.alias&&(T.alias in this.aliases))&&!T.args)T.args={this:T.id};let X=jU($,T);if(I$(X)){if(X[1]==="=")return L(IU);if(X[1]==="?")return L(RU)}return X}unit=($)=>this.units([$]);valueOf=($)=>this.units(UV($));enumerated=(...$)=>this.units($);instanceOf=($)=>this.node("proto",{proto:$},{prereduced:!0});or=(...$)=>this.schema($.map((T)=>this.parse(T)));and=(...$)=>$.reduce((T,W)=>T.and(this.parse(W)),this.intrinsic.unknown);merge=(...$)=>$.reduce((T,W)=>T.merge(this.parse(W)),this.intrinsic.object);pipe=(...$)=>this.intrinsic.unknown.pipe(...$);match=new Q5(this);declare=()=>({type:this.type});define($){return $}type=new K5(this);static scope=($,T={})=>new xU($,T);static module=($,T={})=>this.scope($,T).export()}var E5=Object.assign(xU.scope,{define:($)=>$}),_$=xU;class AE extends L4{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var dC=Z6(["base",n.object],["props",n.object])(($)=>$.base.merge($.props),AE),NE=_$.module({Key:n.key,Merge:dC});class LE extends L4{}var oC=Z6("element")(($)=>{let T=$.element.exclude(n.Array),W=T.array();return T.rawOr(W).pipe(m1).distribute((X)=>X.assertHasKind("morph").declareOut(W),E$)},LE),SE=_$.module({root:n.Array,readonly:"root",index:n.nonNegativeIntegerString,liftFrom:oC},{name:"Array"});var M5=E$(["string",b0.FileConstructor]),lC=M5.rawOr(M5.array()),BE=E$({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:lC}}),RE=_$.module({root:["instanceof",FormData],value:M5,parsed:BE,parse:E$({in:FormData,morphs:($)=>{let T={};for(let[W,X]of $)if(W in T){let Y=T[W];if(typeof Y==="string"||Y instanceof b0.FileConstructor)T[W]=[Y,X];else Y.push(X)}else T[W]=X;return T},declaredOut:BE})},{name:"FormData"});var IE=_$.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 rC={Boolean:1,Number:1,String:1},kE=_$.module({...Y$({...G_,...w_},($,T)=>($ in rC)?[]:[$,["instanceof",T]]),Array:SE,TypedArray:IE,FormData:RE});var iC=E$({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"}),nC=E$({domain:"number",divisor:1}),bU=_$.module({root:n.number,integer:nC,epoch:iC,safe:E$({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 h$=($,T,W)=>{let X={domain:"string",pattern:{rule:$.source,flags:$.flags,meta:T}};if(W)X.meta={format:W};return rT("intersection",X)},qE=h$(_X,"a well-formed integer string"),cE=_$.module({root:qE,parse:E$({in:qE,morphs:($,T)=>{let W=Number.parseInt($);return Number.isSafeInteger(W)?W:T.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:n.integer})},{name:"string.integer"}),tC=h$(/^[\dA-Fa-f]+$/,"hex characters only"),aC=_$.module({root:h$(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:h$(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),PE=h$(/^[A-Z].*$/,"capitalized"),sC=_$.module({root:E$({in:"string",morphs:($)=>$.charAt(0).toUpperCase()+$.slice(1),declaredOut:PE}),preformatted:PE},{name:"string.capitalize"}),eC=($)=>{let T=$.replaceAll(/[ -]+/g,""),W=0,X,Y,U=!1;for(let G=T.length-1;G>=0;G--){if(X=T.substring(G,G+1),Y=Number.parseInt(X,10),U)Y*=2,W+=Y>=10?Y%10+1:Y;else W+=Y;U=!U}return!!(W%10===0?T:!1)},$v=/^(?: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}))$/,Tv=E$({domain:"string",pattern:{meta:"a credit card number",rule:$v.source},predicate:{meta:"a credit card number",predicate:eC}});var Wv=/^([+-]?\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 Xv=($)=>!Number.isNaN(new Date($).valueOf()),CE=E$({domain:"string",predicate:{meta:"a parsable date",predicate:Xv}}).assertHasKind("intersection"),vE=cE.root.internal.narrow(($,T)=>{let W=Number.parseInt($),X=bU.epoch(W);if(X instanceof p4)return T.errors.merge(X),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),Yv=_$.module({root:vE,parse:E$({in:vE,morphs:($)=>new Date($),declaredOut:n.Date})},{name:"string.date.epoch"}),jE=h$(Wv,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),Uv=_$.module({root:jE,parse:E$({in:jE,morphs:($)=>new Date($),declaredOut:n.Date})},{name:"string.date.iso"}),Gv=_$.module({root:CE,parse:E$({declaredIn:CE,in:"string",morphs:($,T)=>{let W=new Date($);if(Number.isNaN(W.valueOf()))return T.error("a parsable date");return W},declaredOut:n.Date}),iso:Uv,epoch:Yv},{name:"string.date"}),Jv=h$(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),xE="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",r1=`(${xE}[.]){3}${xE}`,wv=new RegExp(`^${r1}$`),s$="(?:[0-9a-fA-F]{1,4})",zv=new RegExp(`^((?:${s$}:){7}(?:${s$}|:)|(?:${s$}:){6}(?:${r1}|:${s$}|:)|(?:${s$}:){5}(?::${r1}|(:${s$}){1,2}|:)|(?:${s$}:){4}(?:(:${s$}){0,1}:${r1}|(:${s$}){1,3}|:)|(?:${s$}:){3}(?:(:${s$}){0,2}:${r1}|(:${s$}){1,4}|:)|(?:${s$}:){2}(?:(:${s$}){0,3}:${r1}|(:${s$}){1,5}|:)|(?:${s$}:){1}(?:(:${s$}){0,4}:${r1}|(:${s$}){1,6}|:)|(?::((?::${s$}){0,5}:${r1}|(?::${s$}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),_v=_$.module({root:["v4 | v6","@","an IP address"],v4:h$(wv,"an IPv4 address","ipv4"),v6:h$(zv,"an IPv6 address","ipv6")},{name:"string.ip"}),aT="a JSON string",uE=($)=>{if(!($ instanceof SyntaxError))throw $;return`must be ${aT} (${$})`},Hv=E$({meta:aT,domain:"string",predicate:{meta:aT,predicate:($,T)=>{try{return JSON.parse($),!0}catch(W){return T.reject({code:"predicate",expected:aT,problem:uE(W)})}}}}),Fv=($,T)=>{if($.length===0)return T.error({code:"predicate",expected:aT,actual:"empty"});try{return JSON.parse($)}catch(W){return T.error({code:"predicate",expected:aT,problem:uE(W)})}},Qv=_$.module({root:Hv,parse:E$({meta:"safe JSON string parser",in:"string",morphs:Fv,declaredOut:n.jsonObject})},{name:"string.json"}),bE=h$(/^[a-z]*$/,"only lowercase letters"),Zv=_$.module({root:E$({in:"string",morphs:($)=>$.toLowerCase(),declaredOut:bE}),preformatted:bE},{name:"string.lower"}),pE=["NFC","NFD","NFKC","NFKD"],vX=Y$(pE,($,T)=>[T,E$({domain:"string",predicate:(W)=>W.normalize(T)===W,meta:`${T}-normalized unicode`})]),fU=Y$(pE,($,T)=>[T,E$({in:"string",morphs:(W)=>W.normalize(T),declaredOut:vX[T]})]),Dv=_$.module({root:fU.NFC,preformatted:vX.NFC},{name:"string.normalize.NFC"}),Ov=_$.module({root:fU.NFD,preformatted:vX.NFD},{name:"string.normalize.NFD"}),Vv=_$.module({root:fU.NFKC,preformatted:vX.NFKC},{name:"string.normalize.NFKC"}),Kv=_$.module({root:fU.NFKD,preformatted:vX.NFKD},{name:"string.normalize.NFKD"}),Ev=_$.module({root:"NFC",NFC:Dv,NFD:Ov,NFKC:Vv,NFKD:Kv},{name:"string.normalize"}),fE=h$(zU,"a well-formed numeric string"),Mv=_$.module({root:fE,parse:E$({in:fE,morphs:($)=>Number.parseFloat($),declaredOut:n.number})},{name:"string.numeric"}),yE="a regex pattern",Av=E$({domain:"string",predicate:{meta:yE,predicate:($,T)=>{try{return new RegExp($),!0}catch(W){return T.reject({code:"predicate",expected:yE,problem:String(W)})}}},meta:{format:"regex"}}),Nv=/^(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-]+)*))?$/,Lv=h$(Nv,"a semantic version (see https://semver.org/)"),hE=h$(/^\S.*\S$|^\S?$/,"trimmed"),Sv=_$.module({root:E$({in:"string",morphs:($)=>$.trim(),declaredOut:hE}),preformatted:hE},{name:"string.trim"}),gE=h$(/^[A-Z]*$/,"only uppercase letters"),Bv=_$.module({root:E$({in:"string",morphs:($)=>$.toUpperCase(),declaredOut:gE}),preformatted:gE},{name:"string.upper"}),Rv=($)=>{if(URL.canParse)return URL.canParse($);try{return new URL($),!0}catch{return!1}},mE=E$({domain:"string",predicate:{meta:"a URL string",predicate:Rv},meta:{format:"uri"}}),Iv=_$.module({root:mE,parse:E$({declaredIn:mE,in:"string",morphs:($,T)=>{try{return new URL($)}catch{return T.error("a URL string")}},declaredOut:E$(URL)})},{name:"string.url"}),kv=_$.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:h$(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:h$(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:h$(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:h$(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:h$(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:h$(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:h$(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:h$(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),dE=_$.module({root:n.string,alpha:h$(/^[A-Za-z]*$/,"only letters"),alphanumeric:h$(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:tC,base64:aC,capitalize:sC,creditCard:Tv,date:Gv,digits:h$(/^\d*$/,"only digits 0-9"),email:Jv,integer:cE,ip:_v,json:Qv,lower:Zv,normalize:Ev,numeric:Mv,regex:Av,semver:Lv,trim:Sv,upper:Bv,url:Iv,uuid:kv},{name:"string"});var oE=_$.module({bigint:n.bigint,boolean:n.boolean,false:n.false,never:n.never,null:n.null,number:n.number,object:n.object,string:n.string,symbol:n.symbol,true:n.true,unknown:n.unknown,undefined:n.undefined}),lE=_$.module({root:n.unknown,any:n.unknown},{name:"unknown"}),qv=_$.module({root:n.jsonObject,stringify:rT("morph",{in:n.jsonObject,morphs:($)=>JSON.stringify($),declaredOut:n.string})},{name:"object.json"}),rE=_$.module({root:n.object,json:qv},{name:"object"});class iE extends L4{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var Pv=Z6(["K",n.key],"V")(($)=>({domain:"object",index:{signature:$.K,value:$.V}}),iE);class nE extends L4{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var Cv=Z6(["T",n.object],["K",n.key])(($)=>$.T.pick($.K),nE);class tE extends L4{description='omit a set of properties from an object like `Omit(User, "age")`'}var vv=Z6(["T",n.object],["K",n.key])(($)=>$.T.omit($.K),tE);class aE extends L4{description="make all named properties of an object optional like `Partial(User)`"}var jv=Z6(["T",n.object])(($)=>$.T.partial(),aE);class sE extends L4{description="make all named properties of an object required like `Required(User)`"}var xv=Z6(["T",n.object])(($)=>$.T.required(),sE);class eE extends L4{description='exclude branches of a union like `Exclude("boolean", "true")`'}var bv=Z6("T","U")(($)=>$.T.exclude($.U),eE);class $M extends L4{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var fv=Z6("T","U")(($)=>$.T.extract($.U),$M),TM=_$.module({Exclude:bv,Extract:fv,Omit:vv,Partial:jv,Pick:Cv,Record:Pv,Required:xv});var i1=E5({...oE,...TM,...kE,...NE,string:dE,number:bU,object:rE,unknown:lE},{prereducedAliases:!0,name:"ark"}),_4=i1.export();Object.assign(tT.ambient,_4);tT.typeAttachments={string:_4.string.root,number:_4.number.root,bigint:_4.bigint,boolean:_4.boolean,symbol:_4.symbol,undefined:_4.undefined,null:_4.null,object:_4.object.root,unknown:_4.unknown.root,false:_4.false,true:_4.true,never:_4.never,arrayIndex:_4.Array.index,Key:_4.Key,Record:_4.Record,Array:_4.Array.root,Date:_4.Date};var I6=Object.assign(i1.type,tT.typeAttachments),yv=i1.match,hv=i1.generic,a2$=i1.schema,gv=i1.define,mv=i1.declare;var cv="__vite_start_time"in globalThis,uv=typeof window!=="undefined",DX$="vitest"in globalThis,D1=I6("string"),WM=I6('"true" | "false" | undefined'),O1=X_({isServer:!cv&&!uv,server:{CI:I6("string | undefined").pipe(Boolean),POSTGRES_USER:D1,POSTGRES_PASSWORD:D1,POSTGRES_DATABASE:D1,POSTGRES_HOST:D1,POSTGRES_PORT:D1.pipe(($)=>Number.parseInt($,10)),BACKEND_PORT:D1.pipe(($)=>Number.parseInt($,10)),RUN_WORKERS_FROM_SOURCE:WM.pipe(($)=>$==="true"),FRONTEND_PORT:D1.pipe(($)=>Number.parseInt($,10)),FRONTEND_ORIGINS:D1.pipe.try(($)=>JSON.parse($),I6("string[]")),API_KEY_OPENAI:I6("string | undefined"),API_KEY_RESEND:I6("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:D1,VITE_DEV_FRONTEND_HOST:I6("string | undefined"),VITE_DEV_HTTPS:WM.pipe(($)=>$==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var N5={};M1(N5,{users:()=>h0,untrackedUserColumnNames:()=>pv,twoFactorMethod:()=>JM,trackedUserColumnName:()=>dv,trackableUserColumnNames:()=>UM,signInHistory:()=>lv,role:()=>YM,players:()=>A5,passwordResetAttempts:()=>rv,games:()=>yU,banishedIps:()=>hU,accountActions:()=>ov,accountAction:()=>GM});function XM($){return O`lower(${$})`}var YM=y2("role",["admin","user"]),h0=y1("users",{id:z6().primaryKey().defaultRandom(),username:q4({length:16}).notNull(),emailOffered:q4({length:254}).notNull(),emailVerified:q4({length:254}),password:q4({length:254}),createdAt:N6({withTimezone:!0}).notNull().defaultNow(),createdIp:q4({length:45}).notNull(),isActive:p2().notNull().default(!1),verifiedAt:N6({withTimezone:!0}),userRole:YM().default("user")},($)=>[s7("usernameUniqueIndex").on(XM($.username)),s7("emailVerifiedUniqueIndex").on(XM($.emailVerified))]),pv=["id","createdAt","createdIp","isActive","verifiedAt"],UM=["username","emailOffered","emailVerified","password","userRole"],dv=y2("trackedUserColumnName",UM),GM=y2("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),ov=y1("accountActions",{userId:z6().references(()=>h0.id).primaryKey(),action:GM().notNull(),code:q4({length:254}).notNull(),wrongCodeCount:d2().notNull().default(0),expiresAt:N6({withTimezone:!0}).notNull()}),yU=y1("games",{id:z6().primaryKey().defaultRandom()}),A5=y1("players",{userId:z6().notNull().references(()=>h0.id,{onDelete:"cascade"}),gameId:z6().notNull().references(()=>yU.id,{onDelete:"cascade"}),score:d2().notNull()},($)=>[iD({name:"players_userId_gameId_pk",columns:[$.userId,$.gameId]})]),lv=y1("signInHistory",{id:z6().primaryKey().defaultRandom(),userId:z6().references(()=>h0.id,{onDelete:"cascade"}),signInTime:N6({withTimezone:!0}).notNull().defaultNow(),ipAddress:q4({length:45}).notNull(),userAgent:q4({length:1024}),successful:p2().notNull().default(!1)}),JM=y2("twoFactorMethod",["email","phone"]),rv=y1("passwordResetAttempts",{id:z6().primaryKey().defaultRandom(),userId:z6().notNull().references(()=>h0.id,{onDelete:"cascade"}),requestedIp:q4({length:45}).notNull(),requestedAt:N6({withTimezone:!0}).notNull().defaultNow(),succeededIp:q4({length:45}),succeededAt:N6({withTimezone:!0}),verificationMethod:JM().notNull()}),hU=y1("banishedIps",{ip:q4({length:45}).primaryKey(),reason:q4({length:2048}).notNull(),banishedAt:N6({withTimezone:!0}).notNull().defaultNow(),banishedUntil:N6({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class L5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(iv.resolve(__dirname,"notify_update.sql"));let $=[F4(h0),F4(yU),F4(A5)];await this.sql`SELECT create_notify_triggers(${this.sql.array($)})`,await this.sql.listen("table_update",(T)=>{let W=T.split(","),X=W[0],Y=W[1],U=`${X}("${Y}")`;if(this.observers.has(U))this.observers.get(U).next(U)})}constructor($=!1,T={host:O1.POSTGRES_HOST,port:O1.POSTGRES_PORT,user:O1.POSTGRES_USER,password:O1.POSTGRES_PASSWORD,database:O1.POSTGRES_DATABASE}){this.options=T,this.sql=PT(T),this.drizzle=JU(this.sql,{schema:N5,logger:$})}observe($,T){if(!this.observers.has($))this.observers.set($,new K$);this.observers.get($).subscribe("SINGLETON",T)}}import{resolve as av}from"path";import{existsSync as S5,mkdirSync as wM,readFileSync as nv,readdirSync as zM,rmSync as _M,statSync as HM,writeFileSync as tv}from"fs";import{resolve as B5}from"path";var FM=class{rootDir;get initialized(){return S5(this.rootDir)}initialize(){if(!this.initialized)wM(this.rootDir,{recursive:!0})}constructor($){if(this.rootDir=$.path,$.eagerInit)this.initialize()}getItem($){let T=B5(this.rootDir,$);if(S5(T))return nv(T,"utf-8");return null}setItem($,T){this.initialize();let W=B5(this.rootDir,$);tv(W,T)}removeItem($){let T=B5(this.rootDir,$);if(S5(T))this.initialize(),_M(T)}key($){return zM(this.rootDir).sort((X,Y)=>{let U=HM(X);return HM(Y).ctimeMs-U.ctimeMs})[$]??null}clear(){_M(this.rootDir,{recursive:!0}),wM(this.rootDir,{recursive:!0})}get length(){return zM(this.rootDir).length}};var R5=new FM({path:av(process.cwd(),"storage")});import*as gU from"fs";import*as QM from"readline";function sv($){let W=$.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(X,Y,U,G,J)=>{let w={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[U];return`${G}-${w}-${Y}T${J}`});return new Date(W)}async function ZM($,T="/var/log/nginx/access.log",W=new Date){let X=new Map;if(!gU.existsSync(T))return $.error(`Log file not found: ${T}`),X;let Y=gU.createReadStream(T),U=QM.createInterface({input:Y,crlfDelay:Number.POSITIVE_INFINITY}),G=new Date(W.getTime()-3600000);return U.on("line",(J)=>{let z=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,w=J.match(z);if(w?.groups){let H=w.groups.ip,_=w.groups.dateTime,F=sv(_);if(!Number.isNaN(F.getTime())){if(F>=G&&F<=W){let D=X.get(H);if(!D)D=[],X.set(H,D);D.push(J)}}else $.error(`Failed to parse date: ${_}`)}}),new Promise((J,z)=>{U.on("error",(w)=>{z(w)}),U.on("close",()=>{J(X)})})}function DM($){return $.toJsonSchema()}var ev=["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(`
|
|
152
|
+
`);function OM($){return ev+$.join(`
|
|
129
153
|
|
|
130
|
-
`)}var
|
|
131
|
-
`));let
|
|
132
|
-
`),
|
|
133
|
-
`);else
|
|
134
|
-
`);
|
|
135
|
-
`);break}}let
|
|
154
|
+
`)}var VM={schema:I6([{shouldBanIp:"false"},"|",{shouldBanIp:"true",veryConciseReason:"string"}]),toJsonSchema:DM,fallback:{shouldBanIp:!1}};var Tj=[".env","php"];async function KM({generator:$,logFilePath:T,logger:W,now:X=new Date}){let Y=$.usdBudget,U=new L5({logQuery(N,k){W.info("\uD83D\uDCDD query",N,k)}}),G=await ZM(W,T,X),J=[],z=$.from(VM),w=0,H=0;for(let[N,k]of G){W.info(`\uD83D\uDD0D ruling on ${N}. logs:`),W.info(k.map((x)=>` ${x}`).join(`
|
|
155
|
+
`));let y=!1;for(let x of Tj)if(k.some((m)=>m.includes(x))){J.push({ip:N,reason:`Always ban ${x}`}),W.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${N}--always ban ${x}
|
|
156
|
+
`),y=!0;break}if(y)continue;if($.usdBudget>$.usdMinimum){let x=OM(k),m=await z(x);if(m.shouldBanIp)J.push({ip:N,reason:m.veryConciseReason}),W.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${N}--${m.veryConciseReason}
|
|
157
|
+
`);else H++,W.info(` \uD83D\uDD4A\uFE0F not banning ${N}
|
|
158
|
+
`);w++}else{W.warn("\uD83D\uDCB0 insufficient funds to process all logs"),W.warn(`\uD83D\uDCB0 got through ${w}/${G.size} ips
|
|
159
|
+
`);break}}let _=J.length;if(J.length>0)await U.drizzle.insert(hU).values(J).onConflictDoNothing();let F=[],D=R5.getItem("lastTribunalProcessedDate"),V=new Date(D??"1970-01-01");try{F.push(...await U.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:d8(hU.banishedAt,V)}))}catch(N){W.error(N)}try{if(process.env.EXPERIMENTAL_BAN_IPS)await Promise.all(F.map((N)=>new Promise((k,y)=>$j(`iptables -D INPUT -s ${N.ip} -j DROP`).on("exit",(x)=>{if(x===0)W.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${N.ip}`),k();else y(new Error(`iptables exited with code ${x}`))}))));else W.info("\uD83E\uDDD1\u200D\u2696\uFE0F skipping iptables update")}catch(N){if(N instanceof Error)W.error(N.message);else{let k=qQ(N);W.error("iptables exited with error",k)}}R5.setItem("lastTribunalProcessedDate",X.toISOString()),W.info(`\u2728 banned ${_} ips, didn't ban ${H} ips`);let E=Y-$.usdBudget,R=E.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),P=Y.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),A=Math.round(E/Y*100);W.info(`\uD83D\uDCB8 spent ${R}, ${A}% of ${P} budget`)}var V1=new XG;Object.assign(console,V1.logger,{log:V1.logger.info});process.on("SIGINT",()=>{V1.logger.info("\u2757 received SIGINT; exiting gracefully"),mU()});process.on("SIGTERM",()=>{V1.logger.info("\u2757 received SIGTERM; exiting gracefully"),mU()});process.on("exit",()=>{V1.logger.info("\u2757 received exit; exiting gracefully"),mU()});V1.logger.info("\uD83D\uDEEB tribunal worker ready");var Wj=new kQ({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:O1.API_KEY_OPENAI,cachingMode:"off",logger:V1.logger});if(O1.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 KM({generator:Wj,logFilePath:"/var/log/nginx/access.log",logger:V1.logger});mU();function mU(){V1.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
|