tempest.games 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,76 +1,65 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var MX=Object.create;var{getPrototypeOf:OX,defineProperty:kf,getOwnPropertyNames:XX}=Object;var YX=Object.prototype.hasOwnProperty;var bH=(T,o,F)=>{F=T!=null?MX(OX(T)):{};let A=o||!T||!T.__esModule?kf(F,"default",{value:T,enumerable:!0}):F;for(let y of XX(T))if(!YX.call(A,y))kf(A,y,{get:()=>T[y],enumerable:!0});return A};var qH=(T,o)=>()=>(o||T((o={exports:{}}).exports,o),o.exports);var ZX=(T,o)=>{for(var F in o)kf(T,F,{get:o[F],enumerable:!0,configurable:!0,set:(A)=>o[F]=()=>A})};var vH=(T,o)=>()=>(T&&(o=T(T=0)),o);var PH=import.meta.require;import{join as pH,normalize as jH,resolve as w4}from"path";var KF=(T)=>Array.isArray(T)?T:[T],j_=(T,o)=>{let F=[[],[]];for(let A of T)if(o(A))F[0].push(A);else F[1].push(A);return F},sy=Array,yF=(T,o)=>T.includes(o),x_=(T,o=0)=>[...new Array(T)].map((F,A)=>A+o),yT=(T,o,F)=>{if(T===void 0)return o===void 0?[]:Array.isArray(o)?o:[o];if(F?.prepend)if(Array.isArray(o))T.unshift(...o);else T.unshift(o);else if(Array.isArray(o))T.push(...o);else T.push(o);return T},SF=(T,o)=>{if(o===void 0||o===null)return T??[];if(T===void 0||T===null)return KF(o);return T.concat(o)},b_=(...T)=>T.reduce(SF,[]),so=(T,o,F)=>{if(T===void 0)return Array.isArray(o)?o:[o];let A=F?.isEqual??((y,S)=>y===S);for(let y of KF(o))if(!T.some((S)=>A(S,y)))T.push(y);return T},q_=(T,o)=>T.reduce((F,A)=>{let y=A[o];return F[y]=yT(F[y],A),F},{}),fF=(T,o,F)=>T.length===o.length&&T.every(F?.isEqual?(A,y)=>F.isEqual(A,o[y]):(A,y)=>A===o[y]);var Yo=(T,o)=>tT(T)===o,tT=(T)=>{let o=typeof T;return o==="object"?T===null?"null":"object":o==="function"?"object":o},Zo={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},v_={...Zo,function:"a function"};class P_ extends Error{}var $T=(T)=>qF(T,P_),qF=(T,o=Error)=>{throw new o(T)};class tA extends Error{name="ParseError"}var G=(T)=>qF(T,tA),to=(T)=>` ${T}`;var d=(T,o)=>{let F={},A=Array.isArray(T),y=!1;for(let[S,f]of Object.entries(T).entries()){let $=A?o(S,f[1]):o(...f,S);y||=typeof $[0]==="number";let _=Array.isArray($[0])||$.length===0?$:[$];for(let[J,R]of _)if(typeof J==="object")F[J.group]=yT(F[J.group],R);else F[J]=R}return y?Object.values(F):F};var Bf=Object.entries;var hT=(T,o)=>(T in o),yA=(T,o)=>(o in T);class Nf{constructor(T){Object.assign(this,T)}}var m_=class{};class hA extends m_{}var HX=(T,o)=>{let F={},A={},y;for(y in T)if(y in o)F[y]=T[y];else A[y]=T[y];return[F,A]};var t_=(T,o)=>HX(T,o)[1],ao=(T)=>Object.keys(T).length===0,vF=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((o)=>[o,T[o]])],h_=(T,o)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(o)),g_=(T)=>{let o=Object.keys(T).sort(),F={};for(let A=0;A<o.length;A++)F[o[A]]=T[o[A]];return F};var Vo=to("represents an uninitialized value"),n_=(T)=>Object.values(T).filter((o)=>{if(typeof o==="number")return!0;return typeof T[o]!=="number"});var pf={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},jf=globalThis.File??Blob,xf={ArrayBuffer,Blob,File:jf,FormData,Headers,Request,Response,URL},GX={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},PF={...pf,...xf,...GX,String,Number,Boolean},gA=(T)=>{let o=Object.getPrototypeOf(T);while(o?.constructor&&(!hT(o.constructor.name,PF)||!(T instanceof PF[o.constructor.name])))o=Object.getPrototypeOf(o);let F=o?.constructor?.name;if(F===void 0||F==="Object")return;return F},nA=(T)=>typeof T==="object"&&T!==null?gA(T)??"object":tT(T);var HT=Array.isArray,wX={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"},EX={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"},KX={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"},u_={...wX,...EX,...KX},uA=(T)=>{let o=Object(T).name??null;return o&&hT(o,PF)&&PF[o]===T?o:null};var bf=(T,o)=>{let F=T.prototype;while(F!==null){if(F===o.prototype)return!0;F=Object.getPrototypeOf(F)}return!1};var c_=(T)=>i_(T,new Map),i_=(T,o)=>{if(typeof T!=="object"||T===null)return T;if(o?.has(T))return o.get(T);let F=uA(T.constructor);if(F==="Date")return new Date(T.getTime());if(F&&F!=="Array")return T;let A=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),y=Object.getOwnPropertyDescriptors(T);if(o){o.set(T,A);for(let S in y){let f=y[S];if("get"in f||"set"in f)continue;f.value=i_(f.value,o)}}return Object.defineProperties(A,y),A};var UX=(T)=>{let o=Vo;return()=>o===Vo?o=T():o},UF=(T)=>typeof T==="function"&&T.length===0;var d_=class extends Function{constructor(...T){let o=T.slice(0,-1),F=T.at(-1);try{super(...o,F)}catch(A){return $T(`Encountered an unexpected error while compiling your definition:
4
- Message: ${A}
3
+ var x5=Object.create;var{getPrototypeOf:b5,defineProperty:l1,getOwnPropertyNames:h5}=Object;var p5=Object.prototype.hasOwnProperty;var _O=(T,F,_)=>{_=T!=null?x5(b5(T)):{};let W=F||!T||!T.__esModule?l1(_,"default",{value:T,enumerable:!0}):_;for(let J of h5(T))if(!p5.call(W,J))l1(W,J,{get:()=>T[J],enumerable:!0});return W};var WO=(T,F)=>()=>(F||T((F={exports:{}}).exports,F),F.exports);var g5=(T,F)=>{for(var _ in F)l1(T,_,{get:F[_],enumerable:!0,configurable:!0,set:(W)=>F[_]=()=>W})};var JO=(T,F)=>()=>(T&&(F=T(T=0)),F);var $O=import.meta.require;import{join as eH,normalize as TO,resolve as uA}from"path";var _F=(T)=>Array.isArray(T)?T:[T],jJ=(T,F)=>{let _=[[],[]];for(let W of T)if(F(W))_[0].push(W);else _[1].push(W);return _},KW=Array,u0=(T,F)=>T.includes(F),yJ=(T,F=0)=>[...new Array(T)].map((_,W)=>W+F),r=(T,F,_)=>{if(T===void 0)return F===void 0?[]:Array.isArray(F)?F:[F];if(_?.prepend)if(Array.isArray(F))T.unshift(...F);else T.unshift(F);else if(Array.isArray(F))T.push(...F);else T.push(F);return T},c0=(T,F)=>{if(F===void 0||F===null)return T??[];if(T===void 0||T===null)return _F(F);return T.concat(F)},PJ=(...T)=>T.reduce(c0,[]),x0=(T,F,_)=>{if(T===void 0)return Array.isArray(F)?F:[F];let W=_?.isEqual??((J,$)=>J===$);for(let J of _F(F))if(!T.some(($)=>W($,J)))T.push(J);return T},vJ=(T,F)=>T.reduce((_,W)=>{let J=W[F];return _[J]=r(_[J],W),_},{}),d0=(T,F,_)=>T.length===F.length&&T.every(_?.isEqual?(W,J)=>_.isEqual(W,F[J]):(W,J)=>W===F[J]);var eT=(T,F)=>fT(T)===F,fT=(T)=>{let F=typeof T;return F==="object"?T===null?"null":"object":F==="function"?"object":F},T0={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},xJ={...T0,function:"a function"};class bJ extends Error{}var a=(T)=>RF(T,bJ),RF=(T,F=Error)=>{throw new F(T)};class U_ extends Error{name="ParseError"}var z=(T)=>RF(T,U_),C0=(T)=>` ${T}`;var m=(T,F)=>{let _={},W=Array.isArray(T),J=!1;for(let[$,Y]of Object.entries(T).entries()){let Z=W?F($,Y[1]):F(...Y,$);J||=typeof Z[0]==="number";let A=Array.isArray(Z[0])||Z.length===0?Z:[Z];for(let[X,O]of A)if(typeof X==="object")_[X.group]=r(_[X.group],O);else _[X]=O}return J?Object.values(_):_};var i1=Object.entries;var qT=(T,F)=>(T in F),PF=(T,F)=>(F in T);class t1{constructor(T){Object.assign(this,T)}}var hJ=class{};class M_ extends hJ{}var m5=(T,F)=>{let _={},W={},J;for(J in T)if(J in F)_[J]=T[J];else W[J]=T[J];return[_,W]};var pJ=(T,F)=>m5(T,F)[1],b0=(T)=>Object.keys(T).length===0,wF=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((F)=>[F,T[F]])],gJ=(T,F)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(F)),mJ=(T)=>{let F=Object.keys(T).sort(),_={};for(let W=0;W<F.length;W++)_[F[W]]=T[F[W]];return _};var H0=C0("represents an uninitialized value"),oJ=(T)=>Object.values(T).filter((F)=>{if(typeof F==="number")return!0;return typeof T[F]!=="number"});var n1={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},r1=globalThis.File??Blob,s1={ArrayBuffer,Blob,File:r1,FormData,Headers,Request,Response,URL},o5={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},KF={...n1,...s1,...o5,String,Number,Boolean},Q_=(T)=>{let F=Object.getPrototypeOf(T);while(F?.constructor&&(!qT(F.constructor.name,KF)||!(T instanceof KF[F.constructor.name])))F=Object.getPrototypeOf(F);let _=F?.constructor?.name;if(_===void 0||_==="Object")return;return _},z_=(T)=>typeof T==="object"&&T!==null?Q_(T)??"object":fT(T);var YT=Array.isArray,u5={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"},c5={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"},d5={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"},uJ={...u5,...c5,...d5},E_=(T)=>{let F=Object(T).name??null;return F&&qT(F,KF)&&KF[F]===T?F:null};var a1=(T,F)=>{let _=T.prototype;while(_!==null){if(_===F.prototype)return!0;_=Object.getPrototypeOf(_)}return!1};var cJ=(T)=>dJ(T,new Map),dJ=(T,F)=>{if(typeof T!=="object"||T===null)return T;if(F?.has(T))return F.get(T);let _=E_(T.constructor);if(_==="Date")return new Date(T.getTime());if(_&&_!=="Array")return T;let W=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),J=Object.getOwnPropertyDescriptors(T);if(F){F.set(T,W);for(let $ in J){let Y=J[$];if("get"in Y||"set"in Y)continue;Y.value=dJ(Y.value,F)}}return Object.defineProperties(W,J),W};var l5=(T)=>{let F=H0;return()=>F===H0?F=T():F},WF=(T)=>typeof T==="function"&&T.length===0;var lJ=class extends Function{constructor(...T){let F=T.slice(0,-1),_=T.at(-1);try{super(...F,_)}catch(W){return a(`Encountered an unexpected error while compiling your definition:
4
+ Message: ${W}
5
5
  Source: (${T.slice(0,-1)}) => {
6
6
  ${T.at(-1)}
7
- }`)}}};class ho{constructor(T,...[o]){return Object.assign(Object.setPrototypeOf(T.bind(o?.bind??this),this.constructor.prototype),o?.attach)}}var r_=UX(()=>{try{return new Function("return false")()}catch{return!0}});var f5=to("brand");var l_=to("arkInferred");var _5=to("args");class yo{constructor(){}}var zX=()=>{try{return((new Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},QX=globalThis.process?.env??{},s_={fileName:zX,env:QX};var a_=(T)=>T[0].toUpperCase()+T.slice(1);var qf=(T)=>new RegExp(VX(T),typeof T==="string"?"":T.flags);var VX=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var $F={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},cA="\\",zF={" ":1,"\n":1,"\t":1};var DX=/^-0\.?0*$/.source,T0=/[1-9]\d*/.source,LX=/\.\d+/.source,CX=/\.\d*[1-9]/.source,o0=(T)=>qf($F.negativeLookahead(DX)+$F.nonCapturingGroup("-?"+$F.nonCapturingGroup($F.nonCapturingGroup("0|"+T0)+$F.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),e_=o0({decimalPattern:CX,allowDecimalOnly:!1}),IX=e_.test.bind(e_),ay=o0({decimalPattern:LX,allowDecimalOnly:!0}),Z5=ay.test.bind(ay),kX=/^-?\d*\.?\d*$/,BX=(T)=>T.length!==0&&kX.test(T),iA=qf($F.negativeLookahead("^-0$")+"-?"+$F.nonCapturingGroup($F.nonCapturingGroup("0|"+T0))),NX=iA.test.bind(iA),vf=/^-?\d+$/,pX=vf.test.bind(vf),F0={number:"a number",bigint:"a bigint",integer:"an integer"},A0=(T,o)=>`'${T}' was parsed as ${F0[o]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,jX=(T,o)=>o==="number"?IX(T):NX(T),xX=(T,o)=>o==="number"?Number(T):Number.parseInt(T),bX=(T,o)=>o==="number"?BX(T):pX(T),y0=(T,o)=>Pf(T,"number",o),S0=(T,o)=>Pf(T,"number",{...o,strict:!0}),f0=(T,o)=>Pf(T,"integer",o),Pf=(T,o,F)=>{let A=xX(T,o);if(!Number.isNaN(A)){if(bX(T,o)){if(F?.strict)return jX(T,o)?A:G(A0(T,o));return A}}return F?.errorOnFail?G(F?.errorOnFail===!0?`Failed to parse ${F0[o]} from '${T}'`:F?.errorOnFail):void 0},$0=(T)=>{if(T[T.length-1]!=="n")return;let o=T.slice(0,-1),F;try{F=BigInt(o)}catch{return}if(iA.test(o))return F;if(vf.test(o))return G(A0(T,"bigint"))};var qX="0.46.0",vX={version:qX,filename:s_.fileName(),FileConstructor:jf},mF=vX,J0=new Map,mf=Object.create(null),dA=(T)=>{let o=J0.get(T);if(o)return o;let F=PX(T);if(mf[F])F=`${F}${mf[F]++}`;else mf[F]=1;return mF[F]=T,J0.set(T,F),F},QF=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),PX=(T)=>{switch(typeof T){case"object":{if(T===null)break;let o=gA(T)??"object";return o[0].toLowerCase()+o.slice(1)}case"function":return QF(T.name)?T.name:"fn";case"symbol":return T.description&&QF(T.description)?T.description:"symbol"}return $T(`Unexpected attempt to register serializable value of type ${tT(T)}`)};var rA=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var _0=(T,o={})=>lA(T,{onUndefined:"$ark.undefined",onBigInt:(F)=>`$ark.bigint-${F}`,...o},[]);var r=(T,o)=>{switch(tT(T)){case"object":let F=T,A=F.constructor.name;return A==="Object"||A==="Array"?o?.quoteKeys===!1?ey(F,o?.indent??0,""):JSON.stringify(lA(F,SA,[]),null,o?.indent):ey(F,o?.indent??0,"");case"symbol":return SA.onSymbol(T);default:return rA(T)}},ey=(T,o,F)=>{if(typeof T==="function")return SA.onFunction(T);if(typeof T!=="object"||T===null)return rA(T);let A=F+" ".repeat(o);if(Array.isArray(T)){if(T.length===0)return"[]";let S=T.map((f)=>ey(f,o,A)).join(`,
9
- `+A);return o?`[
10
- ${A}${S}
11
- ${F}]`:`[${S}]`}let y=T.constructor.name;if(y==="Object"){let S=vF(T).map(([f,$])=>{let _=typeof f==="symbol"?SA.onSymbol(f):QF(f)?f:JSON.stringify(f),J=ey($,o,A);return`${A}${_}: ${J}`});if(S.length===0)return"{}";return o?`{
12
- ${S.join(`,
7
+ }`)}}};class k0{constructor(T,...[F]){return Object.assign(Object.setPrototypeOf(T.bind(F?.bind??this),this.constructor.prototype),F?.attach)}}var iJ=l5(()=>{try{return new Function("return false")()}catch{return!0}});var NO=C0("brand");var tJ=C0("arkInferred");var BO=C0("args");class uT{constructor(){}}var i5=()=>{try{return((new Error().stack?.split(`
8
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},t5=globalThis.process?.env??{},nJ={fileName:i5,env:t5};var rJ=(T)=>T[0].toUpperCase()+T.slice(1);var e1=(T)=>new RegExp(n5(T),typeof T==="string"?"":T.flags);var n5=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var l0={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},R_="\\",JF={" ":1,"\n":1,"\t":1};var r5=/^-0\.?0*$/.source,aJ=/[1-9]\d*/.source,s5=/\.\d+/.source,a5=/\.\d*[1-9]/.source,eJ=(T)=>e1(l0.negativeLookahead(r5)+l0.nonCapturingGroup("-?"+l0.nonCapturingGroup(l0.nonCapturingGroup("0|"+aJ)+l0.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),sJ=eJ({decimalPattern:a5,allowDecimalOnly:!1}),e5=sJ.test.bind(sJ),VW=eJ({decimalPattern:s5,allowDecimalOnly:!0}),xO=VW.test.bind(VW),TG=/^-?\d*\.?\d*$/,FG=(T)=>T.length!==0&&TG.test(T),w_=e1(l0.negativeLookahead("^-0$")+"-?"+l0.nonCapturingGroup(l0.nonCapturingGroup("0|"+aJ))),_G=w_.test.bind(w_),T2=/^-?\d+$/,WG=T2.test.bind(T2),T8={number:"a number",bigint:"a bigint",integer:"an integer"},F8=(T,F)=>`'${T}' was parsed as ${T8[F]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,JG=(T,F)=>F==="number"?e5(T):_G(T),$G=(T,F)=>F==="number"?Number(T):Number.parseInt(T),YG=(T,F)=>F==="number"?FG(T):WG(T),_8=(T,F)=>F2(T,"number",F),W8=(T,F)=>F2(T,"number",{...F,strict:!0}),J8=(T,F)=>F2(T,"integer",F),F2=(T,F,_)=>{let W=$G(T,F);if(!Number.isNaN(W)){if(YG(T,F)){if(_?.strict)return JG(T,F)?W:z(F8(T,F));return W}}return _?.errorOnFail?z(_?.errorOnFail===!0?`Failed to parse ${T8[F]} from '${T}'`:_?.errorOnFail):void 0},$8=(T)=>{if(T[T.length-1]!=="n")return;let F=T.slice(0,-1),_;try{_=BigInt(F)}catch{return}if(w_.test(F))return _;if(T2.test(F))return z(F8(T,"bigint"))};var ZG="0.46.0",XG={version:ZG,filename:nJ.fileName(),FileConstructor:r1},VF=XG,Y8=new Map,_2=Object.create(null),K_=(T)=>{let F=Y8.get(T);if(F)return F;let _=AG(T);if(_2[_])_=`${_}${_2[_]++}`;else _2[_]=1;return VF[_]=T,Y8.set(T,_),_},$F=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),AG=(T)=>{switch(typeof T){case"object":{if(T===null)break;let F=Q_(T)??"object";return F[0].toLowerCase()+F.slice(1)}case"function":return $F(T.name)?T.name:"fn";case"symbol":return T.description&&$F(T.description)?T.description:"symbol"}return a(`Unexpected attempt to register serializable value of type ${fT(T)}`)};var V_=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var Z8=(T,F={})=>D_(T,{onUndefined:"$ark.undefined",onBigInt:(_)=>`$ark.bigint-${_}`,...F},[]);var o=(T,F)=>{switch(fT(T)){case"object":let _=T,W=_.constructor.name;return W==="Object"||W==="Array"?F?.quoteKeys===!1?DW(_,F?.indent??0,""):JSON.stringify(D_(_,vF,[]),null,F?.indent):DW(_,F?.indent??0,"");case"symbol":return vF.onSymbol(T);default:return V_(T)}},DW=(T,F,_)=>{if(typeof T==="function")return vF.onFunction(T);if(typeof T!=="object"||T===null)return V_(T);let W=_+" ".repeat(F);if(Array.isArray(T)){if(T.length===0)return"[]";let $=T.map((Y)=>DW(Y,F,W)).join(`,
9
+ `+W);return F?`[
10
+ ${W}${$}
11
+ ${_}]`:`[${$}]`}let J=T.constructor.name;if(J==="Object"){let $=wF(T).map(([Y,Z])=>{let A=typeof Y==="symbol"?vF.onSymbol(Y):$F(Y)?Y:JSON.stringify(Y),X=DW(Z,F,W);return`${W}${A}: ${X}`});if($.length===0)return"{}";return F?`{
12
+ ${$.join(`,
13
13
  `)}
14
- ${F}}`:`{${S.join(", ")}}`}if(T instanceof Date)return tF(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return y},SA={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${dA(T)})`,onFunction:(T)=>`Function(${dA(T)})`},lA=(T,o,F)=>{switch(tT(T)){case"object":{let A=T;if("toJSON"in A&&typeof A.toJSON==="function")return A.toJSON();if(typeof A==="function")return SA.onFunction(A);if(F.includes(A))return"(cycle)";let y=[...F,A];if(Array.isArray(A))return A.map((f)=>lA(f,o,y));if(A instanceof Date)return A.toDateString();let S={};for(let f in A)S[f]=lA(A[f],o,y);for(let f of Object.getOwnPropertySymbols(A))S[o.onSymbol?.(f)??f.toString()]=lA(A[f],o,y);return S}case"symbol":return SA.onSymbol(T);case"bigint":return o.onBigInt?.(T)??`${T}n`;case"undefined":return o.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},tF=(T)=>{let o=T.getFullYear(),F=T.getMonth(),A=T.getDate(),y=T.getHours(),S=T.getMinutes(),f=T.getSeconds(),$=T.getMilliseconds();if(F===0&&A===1&&y===0&&S===0&&f===0&&$===0)return`${o}`;let _=`${mX[F]} ${A}, ${o}`;if(y===0&&S===0&&f===0&&$===0)return _;let J=T.toLocaleTimeString(),R=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(R)J=J.slice(0,-R.length);if($)J+=`.${hX($,3)}`;else if(tX.test(J))J=J.slice(0,-3);return`${J+R}, ${_}`},mX=["January","February","March","April","May","June","July","August","September","October","November","December"],tX=/:\d\d:00$/,hX=(T,o)=>String(T).padStart(o,"0");var R0=(T,o,...[F])=>{let A=F?.stringifySymbol??r,y=T;switch(typeof o){case"string":y=QF(o)?T===""?o:`${T}.${o}`:`${T}[${JSON.stringify(o)}]`;break;case"number":y=`${T}[${o}]`;break;case"symbol":y=`${T}[${A(o)}]`;break;default:if(F?.stringifyNonKey)y=`${T}[${F.stringifyNonKey(o)}]`;else G(`${r(o)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return y},JF=(T,...o)=>T.reduce((F,A)=>R0(F,A,...o),"");class sA extends sy{cache={};constructor(...T){super();this.push(...T)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let T=0;T<this.length;T++)this.cache.json.push(typeof this[T]==="symbol"?r(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=JF(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",o=[T];for(let F of this)T=R0(T,F),o.push(T);return this.cache.stringifyAncestors=o}}class tf{chars;i;def;constructor(T){this.def=T,this.chars=[...T],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(T){let o="";while(this.lookahead){if(T(this,o))if(o[o.length-1]===cA)o=o.slice(0,-1);else break;o+=this.shift()}return o}shiftUntilLookahead(T){return typeof T==="string"?this.shiftUntil((o)=>o.lookahead===T):this.shiftUntil((o)=>(o.lookahead in T))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in zF))}jumpToIndex(T){this.i=T<0?this.length+T:T}jumpForward(T){this.i+=T}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,o){return this.chars.slice(T,o).join("")}lookaheadIs(T){return this.lookahead===T}lookaheadIsIn(T){return this.lookahead in T}}var t5=to("implementedTraits");var hf="$ark",gX=2;while(hf in globalThis)hf=`$ark${gX++}`;var W0=hf;globalThis[W0]=mF;var K=mF,nX=(T)=>`${W0}.${T}`,BT=(T)=>nX(dA(T));class TS extends hA{argNames;body="";constructor(...T){super();this.argNames=T;for(let o of T){if(o in this)throw new Error(`Arg name '${o}' would overwrite an existing property on FunctionBody`);this[o]=o}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(T,o=!1){return gf(T,o)}index(T,o=!1){return M0(`${T}`,o)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
15
- `,this}const(T,o){return this.line(`const ${T} = ${o}`),this}let(T,o){return this.line(`let ${T} = ${o}`)}set(T,o){return this.line(`${T} = ${o}`)}if(T,o){return this.block(`if (${T})`,o)}elseIf(T,o){return this.block(`else if (${T})`,o)}else(T){return this.block("else",T)}for(T,o,F=0){return this.block(`for (let i = ${F}; ${T}; i++)`,o)}forIn(T,o){return this.block(`for (const k in ${T})`,o)}block(T,o,F=""){return this.line(`${T} {`),this.indent(),o(this),this.dedent(),this.line(`}${F}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",o=0){return`${T}(${this.argNames.join(", ")}) { ${o?this.body.split(`
16
- `).map((F)=>" ".repeat(o)+`${F}`).join(`
17
- `):this.body} }`}compile(){return new d_(...this.argNames,this.body)}}var _F=(T)=>Yo(T,"object")||typeof T==="symbol"?BT(T):rA(T),gf=(T,o=!1)=>{if(typeof T==="string"&&QF(T))return`${o?"?":""}.${T}`;return M0(uX(T),o)},uX=(T)=>typeof T==="symbol"?BT(T):JSON.stringify(T),M0=(T,o=!1)=>`${o?"?.":""}[${T}]`;class aA extends TS{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,o){let F=o?.arg??this.data,A=typeof T==="string"?!0:this.requiresContextFor(T),y=typeof T==="string"?T:T.id;if(A)return`${this.referenceToId(y,o)}(${F}, ${this.ctx})`;return`${this.referenceToId(y,o)}(${F})`}referenceToId(T,o){let F=o?.kind??this.traversalKind,A=`this.${T}${F}`;return o?.bind?`${A}.bind(${o?.bind})`:A}requiresContextFor(T){return this.traversalKind==="Apply"||T.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,o,F){let A=this.requiresContextFor(F);if(A)this.line(`${this.ctx}.path.push(${T})`);if(this.check(F,{arg:o}),A)this.line(`${this.ctx}.path.pop()`);return this}check(T,o){return this.traversalKind==="Allows"?this.if(`!${this.invoke(T,o)}`,()=>this.return(!1)):this.line(this.invoke(T,o))}}var oS=(T)=>d(T,(o,F)=>[o,HT(F)?[...F]:F]),_o=to("arkKind"),P=(T,o)=>T?.[_o]===o,UT=(T)=>P(T,"root")||P(T,"constraint");var O0=["unit","proto","domain"],fA=["required","optional","index","sequence"],nf=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],FS=[...nf,...fA,"structure","predicate"],$A=["alias","union","morph","unit","intersection","proto","domain"],cX=[...$A,...FS],AS=d(FS,(T,o)=>[o,1]),X0=d([...fA,"undeclared"],(T,o)=>[o,1]),Y0=d(cX,(T,o)=>[o,T]),JA=(T)=>typeof T==="string"&&(T in Y0);var _A=(T)=>Y0[T],yS=(T)=>$A.slice(_A(T)+1),QG=[...yS("union"),"alias"],VG=[...yS("morph"),"alias"],ko=(T)=>{if(typeof T==="string"||typeof T==="boolean"||T===null)return T;if(typeof T==="number"){if(Number.isNaN(T))return"NaN";if(T===Number.POSITIVE_INFINITY)return"Infinity";if(T===Number.NEGATIVE_INFINITY)return"-Infinity";return T}return _F(T)},VF=(T)=>{let o="{ ";for(let[F,A]of Object.entries(T))o+=`${F}: ${_F(A)}, `;return o+" }"},l=(T)=>{let o=T;if(o.hasAssociatedError)o.defaults.expected??=(F)=>("description"in F)?F.description:o.defaults.description(F),o.defaults.actual??=(F)=>r(F),o.defaults.problem??=(F)=>`must be ${F.expected}${F.actual?` (was ${F.actual})`:""}`,o.defaults.message??=(F)=>{if(F.path.length===0)return F.problem;let A=`${F.propString} ${F.problem}`;if(A[0]==="[")return`value at ${A}`;return A};return o};class Z0 extends Error{name="ToJsonSchemaError";code;context;constructor(T,o){super(r(o,{quoteKeys:!1,indent:4}));this.code=T,this.context=o}hasCode(T){return this.code===T}}var iX={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(T)=>LT.throw("arrayObject",T),arrayPostfix:(T)=>LT.throw("arrayPostfix",T),defaultValue:(T)=>LT.throw("defaultValue",T),domain:(T)=>LT.throw("domain",T),morph:(T)=>LT.throw("morph",T),patternIntersection:(T)=>LT.throw("patternIntersection",T),predicate:(T)=>LT.throw("predicate",T),proto:(T)=>LT.throw("proto",T),symbolKey:(T)=>LT.throw("symbolKey",T),unit:(T)=>LT.throw("unit",T),date:(T)=>LT.throw("date",T)}},LT={Error:Z0,throw:(...T)=>{throw new LT.Error(...T)},throwInternalOperandError:(T,o)=>$T(`Unexpected JSON Schema input for ${T}: ${r(o)}`),defaultConfig:iX};K.config??={};var eA=(T,o)=>{if(!o)return T;let F={...T},A;for(A in o){let y={...T.keywords};if(A==="keywords"){for(let S in o[A]){let f=o.keywords[S];if(f===void 0)continue;y[S]=typeof f==="string"?{description:f}:f}F.keywords=y}else if(A==="toJsonSchema")F[A]=uf(T.toJsonSchema,o.toJsonSchema);else if(JA(A))F[A]={...T[A],...o[A]};else F[A]=o[A]}return F},uf=(T,o)=>{if(!T)return o??{};if(!o)return T;let F={...T},A;for(A in o)if(A==="fallback")F.fallback=dX(T.fallback,o.fallback);else F[A]=o[A];return F},dX=(T,o)=>{T=H0(T),o=H0(o);let F={},A;for(A in LT.defaultConfig.fallback)F[A]=o[A]??o.default??T[A]??T.default??LT.defaultConfig.fallback[A];return F},H0=(T)=>typeof T==="function"?{default:T}:T??{};class DF extends hA{[_o]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:o,...F},A){super();this.input=F,this.ctx=A,h_(this,F);let y=A.data;if(F.code==="union")F.errors=F.errors.flatMap((f)=>{let $=f.hasCode("union")?f.errors:[f];if(!T&&!o)return $;return $.map((_)=>_.transform((J)=>({...J,path:b_(T,J.path,o)})))});this.nodeConfig=A.config[this.code];let S=[...F.path??A.path];if(o)S.push(...o);if(T)S.unshift(...T);this.path=new sA(...S),this.data="data"in F?F.data:y}transform(T){return new DF(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return JF(this.path)}get expected(){if(this.input.expected)return this.input.expected;let T=this.meta?.expected??this.nodeConfig.expected;return typeof T==="function"?T(this.input):T}get actual(){if(this.input.actual)return this.input.actual;let T=this.meta?.actual??this.nodeConfig.actual;return typeof T==="function"?T(this.data):T}get problem(){if(this.input.problem)return this.input.problem;let T=this.meta?.problem??this.nodeConfig.problem;return typeof T==="function"?T(this):T}get message(){if(this.input.message)return this.input.message;let T=this.meta?.message??this.nodeConfig.message;return typeof T==="function"?T(this):T}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 Ho extends sy{[_o]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return d(this.byPath,(T,o)=>[T,o.flat])}get flatProblemsByPath(){return d(this.byPath,(T,o)=>[T,o.flat.map((F)=>F.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new cf(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let o=new Ho(this.ctx);for(let F of this)o.add(T(F));return o}merge(T){for(let o of T){if(this.includes(o))continue;this._add(new DF({...o,path:[...this.ctx.path,...o.path]},this.ctx))}}affectsPath(T){if(this.length===0)return!1;return T.stringifyAncestors().some((o)=>(o in this.byPath))||T.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((T)=>T.toJSON())]}toString(){return this.join(`
18
- `)}_add(T){let o=this.byPath[T.propString];if(o){if(o.hasCode("union")&&o.errors.length===0)return;let F=T.hasCode("union")&&T.errors.length===0?T:new DF({code:"intersection",errors:o.hasCode("intersection")?[...o.errors,T]:[o,T]},this.ctx),A=this.indexOf(o);this.mutable[A===-1?this.length:A]=F,this.byPath[T.propString]=F,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){for(let o of T.path.stringifyAncestors())this.byAncestorPath[o]=yT(this.byAncestorPath[o],T)}}class cf extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
19
- `+T.map((o)=>` \u2022 ${rX(o)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var rX=(T)=>T.toString().split(`
14
+ ${_}}`:`{${$.join(", ")}}`}if(T instanceof Date)return DF(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return J},vF={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${K_(T)})`,onFunction:(T)=>`Function(${K_(T)})`},D_=(T,F,_)=>{switch(fT(T)){case"object":{let W=T;if("toJSON"in W&&typeof W.toJSON==="function")return W.toJSON();if(typeof W==="function")return vF.onFunction(W);if(_.includes(W))return"(cycle)";let J=[..._,W];if(Array.isArray(W))return W.map((Y)=>D_(Y,F,J));if(W instanceof Date)return W.toDateString();let $={};for(let Y in W)$[Y]=D_(W[Y],F,J);for(let Y of Object.getOwnPropertySymbols(W))$[F.onSymbol?.(Y)??Y.toString()]=D_(W[Y],F,J);return $}case"symbol":return vF.onSymbol(T);case"bigint":return F.onBigInt?.(T)??`${T}n`;case"undefined":return F.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},DF=(T)=>{let F=T.getFullYear(),_=T.getMonth(),W=T.getDate(),J=T.getHours(),$=T.getMinutes(),Y=T.getSeconds(),Z=T.getMilliseconds();if(_===0&&W===1&&J===0&&$===0&&Y===0&&Z===0)return`${F}`;let A=`${GG[_]} ${W}, ${F}`;if(J===0&&$===0&&Y===0&&Z===0)return A;let X=T.toLocaleTimeString(),O=X.endsWith(" AM")||X.endsWith(" PM")?X.slice(-3):"";if(O)X=X.slice(0,-O.length);if(Z)X+=`.${OG(Z,3)}`;else if(HG.test(X))X=X.slice(0,-3);return`${X+O}, ${A}`},GG=["January","February","March","April","May","June","July","August","September","October","November","December"],HG=/:\d\d:00$/,OG=(T,F)=>String(T).padStart(F,"0");var X8=(T,F,...[_])=>{let W=_?.stringifySymbol??o,J=T;switch(typeof F){case"string":J=$F(F)?T===""?F:`${T}.${F}`:`${T}[${JSON.stringify(F)}]`;break;case"number":J=`${T}[${F}]`;break;case"symbol":J=`${T}[${W(F)}]`;break;default:if(_?.stringifyNonKey)J=`${T}[${_.stringifyNonKey(F)}]`;else z(`${o(F)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return J},i0=(T,...F)=>T.reduce((_,W)=>X8(_,W,...F),"");class L_ extends KW{cache={};constructor(...T){super();this.push(...T)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let T=0;T<this.length;T++)this.cache.json.push(typeof this[T]==="symbol"?o(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=i0(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",F=[T];for(let _ of this)T=X8(T,_),F.push(T);return this.cache.stringifyAncestors=F}}class W2{chars;i;def;constructor(T){this.def=T,this.chars=[...T],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(T){let F="";while(this.lookahead){if(T(this,F))if(F[F.length-1]===R_)F=F.slice(0,-1);else break;F+=this.shift()}return F}shiftUntilLookahead(T){return typeof T==="string"?this.shiftUntil((F)=>F.lookahead===T):this.shiftUntil((F)=>(F.lookahead in T))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in JF))}jumpToIndex(T){this.i=T<0?this.length+T:T}jumpForward(T){this.i+=T}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,F){return this.chars.slice(T,F).join("")}lookaheadIs(T){return this.lookahead===T}lookaheadIsIn(T){return this.lookahead in T}}var ZU=C0("implementedTraits");var J2="$ark",UG=2;while(J2 in globalThis)J2=`$ark${UG++}`;var A8=J2;globalThis[A8]=VF;var w=VF,MG=(T)=>`${A8}.${T}`,VT=(T)=>MG(K_(T));class LW extends M_{argNames;body="";constructor(...T){super();this.argNames=T;for(let F of T){if(F in this)throw new Error(`Arg name '${F}' would overwrite an existing property on FunctionBody`);this[F]=F}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(T,F=!1){return $2(T,F)}index(T,F=!1){return G8(`${T}`,F)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
15
+ `,this}const(T,F){return this.line(`const ${T} = ${F}`),this}let(T,F){return this.line(`let ${T} = ${F}`)}set(T,F){return this.line(`${T} = ${F}`)}if(T,F){return this.block(`if (${T})`,F)}elseIf(T,F){return this.block(`else if (${T})`,F)}else(T){return this.block("else",T)}for(T,F,_=0){return this.block(`for (let i = ${_}; ${T}; i++)`,F)}forIn(T,F){return this.block(`for (const k in ${T})`,F)}block(T,F,_=""){return this.line(`${T} {`),this.indent(),F(this),this.dedent(),this.line(`}${_}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",F=0){return`${T}(${this.argNames.join(", ")}) { ${F?this.body.split(`
16
+ `).map((_)=>" ".repeat(F)+`${_}`).join(`
17
+ `):this.body} }`}compile(){return new lJ(...this.argNames,this.body)}}var t0=(T)=>eT(T,"object")||typeof T==="symbol"?VT(T):V_(T),$2=(T,F=!1)=>{if(typeof T==="string"&&$F(T))return`${F?"?":""}.${T}`;return G8(QG(T),F)},QG=(T)=>typeof T==="symbol"?VT(T):JSON.stringify(T),G8=(T,F=!1)=>`${F?"?.":""}[${T}]`;class S_ extends LW{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,F){let _=F?.arg??this.data,W=typeof T==="string"?!0:this.requiresContextFor(T),J=typeof T==="string"?T:T.id;if(W)return`${this.referenceToId(J,F)}(${_}, ${this.ctx})`;return`${this.referenceToId(J,F)}(${_})`}referenceToId(T,F){let _=F?.kind??this.traversalKind,W=`this.${T}${_}`;return F?.bind?`${W}.bind(${F?.bind})`:W}requiresContextFor(T){return this.traversalKind==="Apply"||T.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,F,_){let W=this.requiresContextFor(_);if(W)this.line(`${this.ctx}.path.push(${T})`);if(this.check(_,{arg:F}),W)this.line(`${this.ctx}.path.pop()`);return this}check(T,F){return this.traversalKind==="Allows"?this.if(`!${this.invoke(T,F)}`,()=>this.return(!1)):this.line(this.invoke(T,F))}}var SW=(T)=>m(T,(F,_)=>[F,YT(_)?[..._]:_]),iT=C0("arkKind"),q=(T,F)=>T?.[iT]===F,OT=(T)=>q(T,"root")||q(T,"constraint");var H8=["unit","proto","domain"],xF=["required","optional","index","sequence"],Y2=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],IW=[...Y2,...xF,"structure","predicate"],bF=["alias","union","morph","unit","intersection","proto","domain"],zG=[...bF,...IW],NW=m(IW,(T,F)=>[F,1]),O8=m([...xF,"undeclared"],(T,F)=>[F,1]),U8=m(zG,(T,F)=>[F,T]),hF=(T)=>typeof T==="string"&&(T in U8);var pF=(T)=>U8[T],CW=(T)=>bF.slice(pF(T)+1),cU=[...CW("union"),"alias"],dU=[...CW("morph"),"alias"],E0=(T)=>{if(typeof T==="string"||typeof T==="boolean"||T===null)return T;if(typeof T==="number"){if(Number.isNaN(T))return"NaN";if(T===Number.POSITIVE_INFINITY)return"Infinity";if(T===Number.NEGATIVE_INFINITY)return"-Infinity";return T}return t0(T)},YF=(T)=>{let F="{ ";for(let[_,W]of Object.entries(T))F+=`${_}: ${t0(W)}, `;return F+" }"},c=(T)=>{let F=T;if(F.hasAssociatedError)F.defaults.expected??=(_)=>("description"in _)?_.description:F.defaults.description(_),F.defaults.actual??=(_)=>o(_),F.defaults.problem??=(_)=>`must be ${_.expected}${_.actual?` (was ${_.actual})`:""}`,F.defaults.message??=(_)=>{if(_.path.length===0)return _.problem;let W=`${_.propString} ${_.problem}`;if(W[0]==="[")return`value at ${W}`;return W};return F};class M8 extends Error{name="ToJsonSchemaError";code;context;constructor(T,F){super(o(F,{quoteKeys:!1,indent:4}));this.code=T,this.context=F}hasCode(T){return this.code===T}}var EG={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(T)=>ET.throw("arrayObject",T),arrayPostfix:(T)=>ET.throw("arrayPostfix",T),defaultValue:(T)=>ET.throw("defaultValue",T),domain:(T)=>ET.throw("domain",T),morph:(T)=>ET.throw("morph",T),patternIntersection:(T)=>ET.throw("patternIntersection",T),predicate:(T)=>ET.throw("predicate",T),proto:(T)=>ET.throw("proto",T),symbolKey:(T)=>ET.throw("symbolKey",T),unit:(T)=>ET.throw("unit",T),date:(T)=>ET.throw("date",T)}},ET={Error:M8,throw:(...T)=>{throw new ET.Error(...T)},throwInternalOperandError:(T,F)=>a(`Unexpected JSON Schema input for ${T}: ${o(F)}`),defaultConfig:EG};w.config??={};var I_=(T,F)=>{if(!F)return T;let _={...T},W;for(W in F){let J={...T.keywords};if(W==="keywords"){for(let $ in F[W]){let Y=F.keywords[$];if(Y===void 0)continue;J[$]=typeof Y==="string"?{description:Y}:Y}_.keywords=J}else if(W==="toJsonSchema")_[W]=Z2(T.toJsonSchema,F.toJsonSchema);else if(hF(W))_[W]={...T[W],...F[W]};else _[W]=F[W]}return _},Z2=(T,F)=>{if(!T)return F??{};if(!F)return T;let _={...T},W;for(W in F)if(W==="fallback")_.fallback=RG(T.fallback,F.fallback);else _[W]=F[W];return _},RG=(T,F)=>{T=Q8(T),F=Q8(F);let _={},W;for(W in ET.defaultConfig.fallback)_[W]=F[W]??F.default??T[W]??T.default??ET.defaultConfig.fallback[W];return _},Q8=(T)=>typeof T==="function"?{default:T}:T??{};class ZF extends M_{[iT]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:F,..._},W){super();this.input=_,this.ctx=W,gJ(this,_);let J=W.data;if(_.code==="union")_.errors=_.errors.flatMap((Y)=>{let Z=Y.hasCode("union")?Y.errors:[Y];if(!T&&!F)return Z;return Z.map((A)=>A.transform((X)=>({...X,path:PJ(T,X.path,F)})))});this.nodeConfig=W.config[this.code];let $=[..._.path??W.path];if(F)$.push(...F);if(T)$.unshift(...T);this.path=new L_(...$),this.data="data"in _?_.data:J}transform(T){return new ZF(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return i0(this.path)}get expected(){if(this.input.expected)return this.input.expected;let T=this.meta?.expected??this.nodeConfig.expected;return typeof T==="function"?T(this.input):T}get actual(){if(this.input.actual)return this.input.actual;let T=this.meta?.actual??this.nodeConfig.actual;return typeof T==="function"?T(this.data):T}get problem(){if(this.input.problem)return this.input.problem;let T=this.meta?.problem??this.nodeConfig.problem;return typeof T==="function"?T(this):T}get message(){if(this.input.message)return this.input.message;let T=this.meta?.message??this.nodeConfig.message;return typeof T==="function"?T(this):T}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 F0 extends KW{[iT]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return m(this.byPath,(T,F)=>[T,F.flat])}get flatProblemsByPath(){return m(this.byPath,(T,F)=>[T,F.flat.map((_)=>_.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new X2(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let F=new F0(this.ctx);for(let _ of this)F.add(T(_));return F}merge(T){for(let F of T){if(this.includes(F))continue;this._add(new ZF({...F,path:[...this.ctx.path,...F.path]},this.ctx))}}affectsPath(T){if(this.length===0)return!1;return T.stringifyAncestors().some((F)=>(F in this.byPath))||T.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((T)=>T.toJSON())]}toString(){return this.join(`
18
+ `)}_add(T){let F=this.byPath[T.propString];if(F){if(F.hasCode("union")&&F.errors.length===0)return;let _=T.hasCode("union")&&T.errors.length===0?T:new ZF({code:"intersection",errors:F.hasCode("intersection")?[...F.errors,T]:[F,T]},this.ctx),W=this.indexOf(F);this.mutable[W===-1?this.length:W]=_,this.byPath[T.propString]=_,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){for(let F of T.path.stringifyAncestors())this.byAncestorPath[F]=r(this.byAncestorPath[F],T)}}class X2 extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
19
+ `+T.map((F)=>` \u2022 ${wG(F)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var wG=(T)=>T.toString().split(`
21
21
  `).join(`
22
- `);class go{path=[];errors=new Ho(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,o){this.root=T,this.config=o}get data(){let T=this.root;for(let o of this.path)T=T?.[o];return T}get propString(){return JF(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let o=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(o)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let o={path:new sA(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(o);else this.queuedMorphs.push(o)}finalize(T){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 T?T(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(T){return this.errorFromContext(T)}errorFromContext(T){let o=new DF(T,this);if(this.currentBranch)this.currentBranch.error=o;else this.errors.add(o);return o}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:o,morphs:F}of T){if(this.errors.affectsPath(o))continue;this.applyMorphsAtPath(o,F)}}}applyMorphsAtPath(T,o){let F=T.at(-1),A;if(F!==void 0){A=this.root;for(let y=0;y<T.length-1;y++)A=A[T[y]]}this.path=[...T];for(let y of o){let S=UT(y),f=y(A===void 0?this.root:A[F],this);if(f instanceof DF){this.errors.add(f);break}if(f instanceof Ho){if(!S)this.errors.merge(f);break}if(A===void 0)this.root=f;else A[F]=f;this.applyQueuedMorphs()}}}var Go=(T,o,F)=>{if(!F)return o();F.path.push(T);let A=o();return F.path.pop(),A};class oy extends ho{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,o){super((A,y,S=this.onFail)=>{if(y)return this.traverseApply(A,y),y.hasError()?y.errors:y.data;return this.rootApply(A,S)},{attach:T});this.attachments=T,this.$=o,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((A,y)=>eX(A,y.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let A=0;A<this.children.length;A++){if(this.includesTransform||=this.children[A].includesTransform,this.includesContextualPredicate||=this.children[A].includesContextualPredicate,this.isCyclic||=this.children[A].isCyclic,!F){let y=this.children[A].flatRefs;for(let S=0;S<y.length;S++){let f=y[S];if(!this.flatRefs.some(($)=>w0($,f))){this.flatRefs.push(f);for(let $ of f.node.branches)if($.hasKind("morph")||$.hasKind("intersection")&&$.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:f.path,propString:f.propString,node:$})}}}Object.assign(this.referencesById,this.children[A].referencesById)}this.flatRefs.sort((A,y)=>A.path.length>y.path.length?1:A.path.length<y.path.length?-1:A.propString>y.propString?1:A.propString<y.propString?-1:A.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((A)=>A.length===1||A.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((A)=>A.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(A)=>this.traverseAllows(A,new go(A,this.$.resolvedConfig)):(A)=>this.traverseAllows(A)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(o,F)=>{if(this.allows(o))return o;let A=new go(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(F)};case"contextual":return(o,F)=>{let A=new go(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(o,F)=>{if(this.allows(o))return this.contextFreeMorph(T&&(typeof o==="object"&&o!==null||typeof o==="function")?T(o):o);let A=new go(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,$T(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=aX(this.metaJson);cacheGetter(T,o){return Object.defineProperty(this,T,{value:o}),o}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=_A(this.kind);precompilation;assert=(T,o)=>this(T,o,(F)=>F.throw());traverse(T,o){return this(T,o,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let o={};for(let[F,A]of this.innerEntries){let y=this.impl.keys[F];if(y.reduceIo)y.reduceIo(T,o,A);else if(y.child){let S=A;o[F]=HT(S)?S.map((f)=>f[T]):S[T]}else o[F]=A}return this.$.node(this.kind,o)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let o=UT(T)?T:this.$.parseDefinition(T);return this.innerHash===o.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)qF(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!yF(T,this.kind))qF(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return yF(O0,this.kind)}isConstraint(){return yF(FS,this.kind)}isStructural(){return yF(fA,this.kind)}isRefinement(){return yF(nf,this.kind)}isRoot(){return yF($A,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let o=Ty.normalize(T);return this._select(o)}_select(T){let o=Ty.applyBoundary[T.boundary??"references"](this);if(T.kind)o=o.filter((F)=>F.kind===T.kind);if(T.where)o=o.filter(T.where);return Ty.applyMethod[T.method??"filter"](o,this,T)}transform(T,o){return this._transform(T,this._createTransformContext(o))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,o){let F=o.bindScope??this.$;if(o.seen[this.id])return this.$.lazilyResolve(o.seen[this.id]);if(o.shouldTransform?.(this,o)===!1)return this;let A;if(o.seen[this.id]=()=>A,this.hasKind("structure")&&this.undeclared!==o.undeclaredKeyHandling)o={...o,undeclaredKeyHandling:this.undeclared};let y=d(this.inner,(J,R)=>{if(!this.impl.keys[J].child)return[J,R];let O=R;if(!HT(O)){let H=O._transform(T,o);return H?[J,H]:[]}if(O.length===0)return[J,R];let Y=O.flatMap((H)=>{return H._transform(T,o)??[]});return Y.length?[J,Y]:[]});delete o.seen[this.id];let S=Object.assign(y,{meta:this.meta}),f=o.selected&&!o.selected.includes(this)?S:T(this.kind,S,o);if(f===null)return null;if(UT(f))return A=f;let $=Object.keys(f);if(($.length===0||$.length===1&&$[0]==="meta")&&!ao(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in f))return o.undeclaredKeyHandling?{...f,value:K.intrinsic.unknown}:null;if(this.kind==="morph")f.in??=K.intrinsic.unknown;return A=F.node(this.kind,f,o.parseOptions)}configureReferences(T,o="references"){let F=Ty.normalize(o),A=typeof T==="string"?($,_)=>({..._,meta:{..._.meta,description:T}}):typeof T==="function"?($,_)=>({..._,meta:T(_.meta)}):($,_)=>({..._,meta:{..._.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,A(this.kind,{...this.inner,meta:this.meta}));let y=this._select(F),S=y&&KF(y),f=F.boundary==="child"?($,_)=>_.root.children.includes($):F.boundary==="shallow"?($)=>$.kind!=="structure":()=>!0;return this.$.finalize(this.transform(A,{shouldTransform:f,selected:S}))}}var Ty={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,o,F)=>{if(T.length===0)qF(G0(o,F));return T},find:(T)=>T[0],assertFind:(T,o,F)=>{if(T.length===0)qF(G0(o,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?hT(T,Ty.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},G0=(T,o)=>`${T} had no references matching ${r(o)}.`,lX=(T)=>JF(T,{stringifyNonKey:(o)=>o.expression}),sX=/"(\$ark\.[^"]+)"/g,aX=(T)=>JSON.stringify(T).replaceAll(sX,"$1"),no=(T,o)=>({path:T,node:o,propString:lX(T)}),w0=(T,o)=>T.propString===o.propString&&T.node.equals(o.node),df=(T,o)=>so(T,o,{isEqual:w0}),eX=(T,o)=>so(T,o,{isEqual:(F,A)=>F.equals(A)});class k extends Array{static init(T,o,F,A){return new k({kind:T,l:o,r:F,path:A?.path??[],optional:A?.optional??!1})}add(T,o,F,A){return this.push({kind:T,l:o,r:F,path:A?.path??[],optional:A?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:o,r:F}=this[0],A=JF(T);return lf(`Intersection${A&&` at ${A}`} of ${E0(o,F)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:T,l:o,r:F})=>`${T}: ${E0(o,F)}`).join(`
24
- \u2022 `)}`}throw(){return G(this.describeReasons())}invert(){let T=this.map((o)=>({...o,l:o.r,r:o.l}));if(!(T instanceof k))return new k(...T);return T}withPrefixKey(T,o){return this.map((F)=>({...F,path:[T,...F.path],optional:F.optional||o==="optional"}))}toNeverIfDisjoint(){return K.intrinsic.never}}var E0=(T,o)=>`${rf(T)} and ${rf(o)}`,rf=(T)=>UT(T)?T.expression:HT(T)?T.map(rf).join(" | ")||"never":String(T),lf=(T)=>`${T} results in an unsatisfiable type`;var RA={},wo=(T,o,F)=>zT(T,o,{$:F,invert:!1,pipe:!1}),Fy=(T,o,F)=>zT(T,o,{$:F,invert:!1,pipe:!0}),zT=(T,o,F)=>{let A=F.pipe?"|>":"&",y=`${T.hash}${A}${o.hash}`;if(RA[y]!==void 0)return RA[y];if(!F.pipe){let $=`${o.hash}${A}${T.hash}`;if(RA[$]!==void 0){let _=RA[$],J=_ instanceof k?_.invert():_;return RA[y]=J,J}}let S=!F.pipe||!T.includesTransform&&!o.includesTransform;if(S&&T.equals(o))return T;let f=S?sf(T,o,F):T.hasKindIn(...$A)?T8(T,o,F):sf(T,o,F);if(UT(f)){if(T.equals(f))f=T;else if(o.equals(f))f=o}return RA[y]=f,f},sf=(T,o,F)=>{let A=T.precedence<o.precedence?T.kind:o.kind,y=T.impl.intersections[o.kind]??o.impl.intersections[T.kind];if(y===void 0)return null;else if(A===T.kind)return y(T,o,F);else{let S=y(o,T,{...F,invert:!F.invert});if(S instanceof k)S=S.invert();return S}},T8=(T,o,F)=>T.includesTransform||o.includesTransform?F.invert?K0(o,T,F):K0(T,o,F):sf(T,o,F),K0=(T,o,F)=>T.distribute((A)=>o8(A,o,F),(A)=>{let y=A.filter(UT);if(y.length===0)return k.init("union",T.branches,o.branches);if(y.length<T.branches.length||!T.branches.every(($,_)=>$.in.equals(y[_].in)))return F.$.parseSchema(y);let S;if(y.length===1){let $=y[0];if(!S)return $;return F.$.node("morph",{...$.inner,in:$.in.configure(S,"self")})}let f={branches:y};if(S)f.meta=S;return F.$.parseSchema(f)}),o8=(T,o,F)=>{if(T.hasKind("morph")){let y=[...T.morphs];if(T.lastMorphIfNode){let S=zT(T.lastMorphIfNode,o,F);if(S instanceof k)return S;y[y.length-1]=S}else y.push(o);return F.$.node("morph",{morphs:y,in:T.inner.in})}if(o.hasKind("morph")){let y=zT(T,o.in,F);if(y instanceof k)return y;return F.$.node("morph",{morphs:[o],in:y})}return F.$.node("morph",{morphs:[o],in:T})};class Bo extends oy{constructor(T,o){super(T,o);Object.defineProperty(this,_o,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return wo(this,T,this.$)}}class RF extends Bo{traverseApply=(T,o)=>{if(!this.traverseAllows(T,o))o.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return VF(this.errorContext)}}var So=(T)=>(o,F)=>{if(HT(o)){if(o.length===0)return;let y=o.map((S)=>F.$.node(T,S));if(T==="predicate")return y;return y.sort((S,f)=>S.hash<f.hash?-1:1)}let A=F.$.node(T,o);return A.hasOpenIntersection()?[A]:A},WA=(T)=>{let o=T.r.shift();if(!o){let A=T.l.length===0&&T.kind==="structure"?K.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,F8(T.l)),{prereduced:!0});for(let y of T.roots){if(A instanceof k)return A;A=zT(y,A,T.ctx)}return A}let F=!1;for(let A=0;A<T.l.length;A++){let y=zT(T.l[A],o,T.ctx);if(y===null)continue;if(y instanceof k)return y;if(!F){if(y.isRoot())return T.roots.push(y),T.l.splice(A),WA(T);T.l[A]=y,F=!0}else if(!T.l.includes(y))return $T(`Unexpectedly encountered multiple distinct intersection results for refinement ${y}`)}if(!F)T.l.push(o);if(T.kind==="intersection"){if(o.impliedSiblings)for(let A of o.impliedSiblings)so(T.r,A)}return WA(T)},MA=(T)=>{return Object.entries(T).flatMap(([F,A])=>(F in AS)?A:[]).sort((F,A)=>F.precedence<A.precedence?-1:F.precedence>A.precedence?1:F.kind==="predicate"&&A.kind==="predicate"?0:F.hash<A.hash?-1:1)},F8=(T)=>{let o={};for(let F of T)if(F.hasOpenIntersection())o[F.kind]=yT(o[F.kind],F);else{if(o[F.kind])return $T(`Unexpected intersection of closed refinements of kind ${F.kind}`);o[F.kind]=F}return o},U0=(...T)=>G(z0(...T)),z0=(T,o,F)=>{let A=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(o).defaultShortDescription;return`${a_(T)} operand must be ${o.description} (was ${A})`};var Q0=(T,o,F)=>new LF(T,o,F,F,null);class SS extends ho{}class LF extends ho{[_o]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,o,F,A,y){super((...S)=>{let f=d(this.names,($,_)=>{let J=this.arg$.parse(S[$]);if(!J.extends(this.constraints[$]))G(A8(_,this.constraints[$].expression,J.expression));return[_,J]});if(this.defIsLazy()){let $=this.bodyDef(f);return this.$.parse($)}return this.$.parse(o,{args:f})});this.paramDefs=T,this.bodyDef=o,this.$=F,this.arg$=A,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 SS}cacheGetter(T,o){return Object.defineProperty(this,T,{value:o}),o}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:_0(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,K.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var A8=(T,o,F)=>`${T} must be assignable to ${o} (was ${F})`;var y8=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class V0 extends Bo{serializedPredicate=BT(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=VF(this.errorContext);traverseApply=(T,o)=>{if(!this.predicate(T,o.external)&&!o.hasError())o.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,o){return o.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var af={implementation:y8,Node:V0};var S8=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:G(f8(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,o,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*o.rule/$8(T.rule,o.rule))})},obviatesBasisDescription:!0});class D0 extends RF{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=K.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var ef={implementation:S8,Node:D0};var f8=(T)=>`divisor must be an integer (was ${T})`,$8=(T,o)=>{let F,A=T,y=o;while(y!==0)F=y,y=A%y,A=F;return A};class Do extends RF{boundOperandKind=W8[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=M8(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${J8[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?O8(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var J8={"<":">=","<=":">",">":"<=",">=":"<"},_8={min:"max",minLength:"maxLength",after:"before"},fS={parse:(T)=>T||void 0},$S=(T)=>(o)=>{if(typeof o==="number")return{rule:o};let{exclusive:F,...A}=o;return F?{...A,rule:T==="minLength"?A.rule+1:A.rule-1}:A},JS=(T)=>(o)=>{if(typeof o==="number"||typeof o==="string"||o instanceof Date)return{rule:o};let{exclusive:F,...A}=o;if(!F)return A;let y=typeof A.rule==="number"?A.rule:typeof A.rule==="string"?new Date(A.rule).valueOf():A.rule.valueOf();return F?{...A,rule:T==="after"?y+1:y-1}:A},_S=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,R8=(T,o)=>`${T} bound must be a positive integer (was ${o})`,OA=(T)=>(o)=>{if(!Number.isInteger(o)||o<0)G(R8(T,o));return o},W8={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},M8=(T,o)=>`${hT(T,_8)?">":"<"}${o?"":"="}`,O8=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),L0=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var X8=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_S,serialize:(T)=>T.toISOString()}},normalize:JS("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:tF},intersections:{after:(T,o)=>T.isStricterThan(o)?T:o}});class C0 extends Do{impliedBasis=K.intrinsic.Date.internal;collapsibleLimitString=tF(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,o){return o.fallback.date({code:"date",base:T,after:this.rule})}}var T$={implementation:X8,Node:C0};var Y8=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_S,serialize:(T)=>T.toISOString()}},normalize:JS("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:tF},intersections:{before:(T,o)=>T.isStricterThan(o)?T:o,after:(T,o,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)}});class I0 extends Do{collapsibleLimitString=tF(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=K.intrinsic.Date.internal;reduceJsonSchema(T,o){return o.fallback.date({code:"date",base:T,before:this.rule})}}var o$={implementation:Y8,Node:I0};var Z8=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:OA("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,o,F)=>k.init("unit",F.$.node("unit",{unit:T.rule}),F.$.node("unit",{unit:o.rule}),{path:["length"]}),minLength:(T,o)=>T.rule>=o.rule?T:k.init("range",T,o),maxLength:(T,o)=>T.rule<=o.rule?T:k.init("range",T,o)}});class k0 extends RF{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=K.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return LT.throwInternalOperandError("exactLength",T)}}}var F$={implementation:Z8,Node:k0};var H8=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:fS},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,o)=>T.isStricterThan(o)?T:o,min:(T,o,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)},obviatesBasisDescription:!0});class B0 extends Do{impliedBasis=K.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var A$={implementation:H8,Node:B0};var G8=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:OA("maxLength")}},reduce:(T,o)=>T.rule===0?o.node("exactLength",T):void 0,normalize:$S("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,o)=>T.isStricterThan(o)?T:o,minLength:(T,o,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("exactLength",{rule:T.rule}):null:k.init("range",T,o)}});class N0 extends Do{impliedBasis=K.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return LT.throwInternalOperandError("maxLength",T)}}}var y$={implementation:G8,Node:N0};var w8=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:fS},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,o)=>T.isStricterThan(o)?T:o},obviatesBasisDescription:!0});class p0 extends Do{impliedBasis=K.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var S$={implementation:w8,Node:p0};var E8=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:OA("minLength")}},reduce:(T)=>T.rule===0?K.intrinsic.unknown:void 0,normalize:$S("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,o)=>T.isStricterThan(o)?T:o}});class j0 extends Do{impliedBasis=K.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return LT.throwInternalOperandError("minLength",T)}}}var f$={implementation:E8,Node:j0};var x0={min:S$.implementation,max:A$.implementation,minLength:f$.implementation,maxLength:y$.implementation,exactLength:F$.implementation,after:T$.implementation,before:o$.implementation},b0={min:S$.Node,max:A$.Node,minLength:f$.Node,maxLength:y$.Node,exactLength:F$.Node,after:T$.Node,before:o$.Node};var K8=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class q0 extends RF{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=K.intrinsic.string.internal;reduceJsonSchema(T,o){if(T.pattern)return o.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var $$={implementation:K8,Node:q0};var Ay=(T,o)=>{let F=U8(T);if(o&&!o.includes(F))return G(`Root of kind ${F} should be one of ${o}`);return F},U8=(T)=>{if(P(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in Zo)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return G(v0(T));if("morphs"in T)return"morph";if("branches"in T||HT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let o=Object.keys(T);if(o.length===0||o.some((F)=>(F in AS)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return G(v0(T))},v0=(T)=>`${r(T)} is not a valid type schema`,P0={},z8=(T)=>HT(T)?T.map((o)=>o.collapsibleJson):T.collapsibleJson,Ro={};K.nodesByRegisteredId=Ro;var J$=(T)=>{return P0[T]??=0,`${T}${++P0[T]}`},_$=(T)=>{let o=XA[T.kind],F=o.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,A={},{meta:y,...S}=F,f=y===void 0?{}:typeof y==="string"?{description:y}:y,$=Bf(S).sort(([J],[R])=>JA(J)?JA(R)?_A(J)-_A(R):1:JA(R)?-1:J<R?-1:1).filter(([J,R])=>{if(J.startsWith("meta.")){let O=J.slice(5);return f[O]=R,!1}return!0});for(let J of $){let R=J[0],O=o.keys[R];if(!O)return G(`Key ${R} is not valid on ${T.kind} schema`);let Y=O.parse?O.parse(J[1],T):J[1];if(Y!==Vo&&(Y!==void 0||O.preserveUndefined))A[R]=Y}if(o.reduce&&!T.prereduced){let J=o.reduce(A,T.$);if(J){if(J instanceof k)return J.throw();return Q8(J,f)}}return R$({id:T.id,kind:T.kind,inner:A,meta:f,$:T.$})},R$=({id:T,kind:o,inner:F,meta:A,$:y,ignoreCache:S})=>{let f=XA[o],$=Bf(F),_=[],J={};for(let[p,v]of $){let h=f.keys[p],U=h.serialize??(h.child?z8:ko);if(J[p]=U(v),h.child===!0){let V=v;if(HT(V))_.push(...V);else _.push(V)}else if(typeof h.child==="function")_.push(...h.child(v))}if(f.finalizeInnerJson)J=f.finalizeInnerJson(J);let R={...J},O={};if(!ao(A))O=d(A,(p,v)=>[p,p==="examples"?v:ko(v)]),R.meta=RS(O,"description",!0);J=RS(J,f.collapsibleKey,!1);let Y=JSON.stringify({kind:o,...J});R=RS(R,f.collapsibleKey,!1);let H=RS(R,f.collapsibleKey,!0),Q=JSON.stringify({kind:o,...R});if(y.nodesByHash[Q]&&!S)return y.nodesByHash[Q];let E={id:T,kind:o,impl:f,inner:F,innerEntries:$,innerJson:J,innerHash:Y,meta:A,metaJson:O,json:R,hash:Q,collapsibleJson:H,children:_};if(o!=="intersection"){for(let p in F)if(p!=="in"&&p!=="out")E[p]=F[p]}let B=new t0[o](E,y);return y.nodesByHash[Q]=B},m0=(T,o)=>{if(T.id===o)return T;if(UT(Ro[o]))$T(`Unexpected attempt to overwrite node id ${o}`);return R$({id:o,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},Q8=(T,o,F)=>{if(F&&UT(Ro[F]))$T(`Unexpected attempt to overwrite node id ${F}`);return R$({id:F??J$(o.alias??T.kind),kind:T.kind,inner:T.inner,meta:o,$:T.$})},RS=(T,o,F)=>{let A=Object.keys(T);if(A.length===1&&A[0]===o){let y=T[o];if(F)return y;if(Yo(y,"object")&&(Object.keys(y).length===1||Array.isArray(y)))return y}return T};var yy=(T,o,F)=>{if(T.key!==o.key)return null;let A=T.key,y=zT(T.value,o.value,F),S=T.required||o.required?"required":"optional";if(y instanceof k)if(S==="optional")y=K.intrinsic.never.internal;else return y.withPrefixKey(T.key,T.required&&o.required?"required":"optional");if(S==="required")return F.$.node("required",{key:A,value:y});let f=T.hasDefault()?o.hasDefault()?T.default===o.default?T.default:G(W$(T.default,o.default)):T.default:o.hasDefault()?o.default:Vo;return F.$.node("optional",{key:A,value:y,default:f})};class Sy extends Bo{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=K.intrinsic.object.internal;serializedKey=_F(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=yT(this.value.flatRefs.map((T)=>no([this.key,...T.path],T.node)),no([this.key],this.value));_transform(T,o){o.path.push(this.key);let F=super._transform(T,o);return o.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,o)=>{if(this.key in T)return Go(this.key,()=>this.value.traverseAllows(T[this.key],o),o);return this.optional};traverseApply=(T,o)=>{if(this.key in T)Go(this.key,()=>this.value.traverseApply(T[this.key],o),o);else if(this.hasKind("required"))o.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var W$=(T,o)=>`Invalid intersection of default values ${r(T)} & ${r(o)}`;var V8=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,o)=>o.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,o)=>{if(o.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return o.node("optional",{...T,value:T.value.or(n.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:yy}});class h0 extends Sy{constructor(...T){super(...T);if("default"in this.inner)$y(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,...o}=this.inner;return this.cacheGetter("outProp",this.$.node("required",o,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${r(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=L8(this);defaultValueMorphRef=this.defaultValueMorph&&BT(this.defaultValueMorph)}var fy={implementation:V8,Node:h0},D8={},L8=(T)=>{if(!T.hasDefault())return;let o=`{${T.compiledKey}: ${T.value.id} = ${ko(T.default)}}`;return D8[o]??=M$(T.key,T.value,T.default)},M$=(T,o,F)=>{if(typeof F==="function")return o.includesTransform?(y,S)=>{return Go(T,()=>o(y[T]=F(),S),S),y}:(y)=>{return y[T]=F(),y};let A=o.includesTransform?o.assert(F):F;return Yo(A,"object")?(y,S)=>{return Go(T,()=>o(y[T]=F,S),S),y}:(y)=>{return y[T]=A,y}},$y=(T,o,F)=>{let A=UF(o);if(Yo(o,"object")&&!A)G(C8(F));let y=T.in(A?o():o);if(y instanceof Ho){if(F===null)G(`Default ${y.summary}`);let S=y.transform((f)=>f.transform(($)=>({...$,prefixPath:[F]})));G(`Default for ${S.summary}`)}return o},C8=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${_F(T)} `}must be specified as a function like () => ({my: 'object'})`};class No extends oy{constructor(T,o){super(T,o);Object.defineProperty(this,_o,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let o=this(T);if(o instanceof Ho)return o;return{value:o}}}}as(){return this}brand(T){if(T==="")return G(I8);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,o){let F=this.branches.map(T);return o?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let o=uf(this.$.resolvedConfig.toJsonSchema,T);o.useRefs||=this.isCyclic;let F=typeof o.dialect==="string"?{$schema:o.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(o)),o.useRefs)F.$defs=d(this.references,(A,y)=>y.isRoot()&&!y.alwaysExpandJsonSchema?[y.id,y.toResolvedJsonSchema(o)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let o=this.innerToJsonSchema(T);return Object.assign(o,this.metaJson)}intersect(T){let o=this.$.parseDefinition(T),F=this.rawIntersect(o);if(F instanceof k)return F;return this.$.finalize(F)}rawIntersect(T){return wo(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let o=this.intersect(T);return o instanceof k?o.throw():o}rawAnd(T){let o=this.rawIntersect(T);return o instanceof k?o.throw():o}or(T){let o=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(o))}rawOr(T){let o=[...this.branches,...T.branches];return this.$.node("union",o)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((o,F)=>o.intersect(F).toNeverIfDisjoint(),K.intrinsic.unknown.internal);if(T.branches.length===0)G(lf(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return G(k8(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let o=this.$.parseDefinition(T);return this.$.schema(o.distribute((F)=>this.applyStructuralOperation("merge",[g0(F)??G(n0("merge",F.expression))])))}applyStructuralOperation(T,o){return this.distribute((F)=>{if(F.equals(K.intrinsic.object)&&T!=="merge")return F;let A=g0(F);if(!A)G(n0(T,F.expression));if(T==="keyof")return A.keyof();if(T==="get")return A.get(...o);if(T==="props")return A.props;let y=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:A[y](...o)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let o=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>F.extends(o)))}exclude(T){let o=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.extends(o)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof k)}extends(T){let o=this.intersect(T);return!(o instanceof k)&&this.equals(o)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,o="shallow"){return this.configureReferences(T,o)}describe(T,o="shallow"){return this.configure({description:T},o)}optional(){return[this,"?"]}default(T){return $y(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let o=T.reduce((F,A)=>F.rawPipeOnce(A),this);return this.$.finalize(o)}tryPipe(...T){let o=T.reduce((F,A)=>F.rawPipeOnce(P(A,"root")?A:(y,S)=>{try{return A(y,S)}catch(f){return S.error({code:"predicate",predicate:A,actual:`aborted due to error:
25
- ${f}
26
- `})}}),this);return this.$.finalize(o)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let o=Fy(this,T,this.$);if(o instanceof k)return o.throw();return o}rawPipeOnce(T){if(P(T,"root"))return this.toNode(T);return this.distribute((o)=>o.hasKind("morph")?this.$.node("morph",{in:o.inner.in,morphs:[...o.morphs,T]}):this.$.node("morph",{in:o,morphs:[T]}),this.$.parseSchema)}narrow(T){return this.constrainOut("predicate",T)}constrain(T,o){return this._constrain("root",T,o)}constrainIn(T,o){return this._constrain("in",T,o)}constrainOut(T,o){return this._constrain("out",T,o)}_constrain(T,o,F){let A=this.$.node(o,F);if(A.isRoot())return A.isUnknown()?this:$T(`Unexpected constraint node ${A}`);let y=T==="root"?this:this[T];if(y.hasKind("morph")||A.impliedBasis&&!y.extends(A.impliedBasis))return U0(o,A.impliedBasis,this);let S=this.$.node("intersection",{[A.kind]:A}),f=T==="out"?Fy(this,S,this.$):wo(this,S,this.$);if(f instanceof k)f.throw();return this.$.finalize(f)}onUndeclaredKey(T){let o=typeof T==="string"?T:T.rule,F=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((A,y)=>A==="structure"?o==="ignore"?t_(y,{undeclared:1}):{...y,undeclared:o}:y,F?void 0:{shouldTransform:(A)=>!yF(fA,A.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!fF(this.shallowMorphs,T.shallowMorphs))return!1;if(!fF(this.flatMorphs,T.flatMorphs,{isEqual:(o,F)=>o.propString===F.propString&&(o.node.hasKind("morph")&&F.node.hasKind("morph")?o.node.hasEqualMorphs(F.node):o.node.hasKind("intersection")&&F.node.hasKind("intersection")?o.node.structure?.structuralMorphRef===F.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(T){return this.onUndeclaredKey({rule:T,deep:!0})}filter(T){return this.constrainIn("predicate",T)}divisibleBy(T){return this.constrain("divisor",T)}matching(T){return this.constrain("pattern",T)}atLeast(T){return this.constrain("min",T)}atMost(T){return this.constrain("max",T)}moreThan(T){return this.constrain("min",YA(T))}lessThan(T){return this.constrain("max",YA(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",YA(T))}lessThanLength(T){return this.constrain("maxLength",YA(T))}exactlyLength(T){return this.constrain("exactLength",T)}atOrAfter(T){return this.constrain("after",T)}atOrBefore(T){return this.constrain("before",T)}laterThan(T){return this.constrain("after",YA(T))}earlierThan(T){return this.constrain("before",YA(T))}}var I8="Expected a non-empty brand name after #",YA=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},Jy=(T,o)=>P(o,"root")?P(T,"root")?T.extends(o):o.allows(T):P(T,"root")?T.hasUnit(o):o===T,g0=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(K.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(K.intrinsic.emptyStructure);return null},k8=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${T}`,n0=(T,o)=>`${T} operand must be an object (was ${o})`;var eo=(T,o)=>d(yS(T),(F,A)=>[A,o]);var B8=(T)=>typeof T==="string"?{reference:T}:T,u0=(T)=>T instanceof k?K.intrinsic.never.internal:T,N8=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:B8,defaults:{description:(T)=>T.reference},intersections:{alias:(T,o,F)=>F.$.lazilyResolve(()=>u0(zT(T.resolution,o.resolution,F)),`${T.reference}${F.pipe?"=>":"&"}${o.reference}`),...eo("alias",(T,o,F)=>{if(o.isUnknown())return T;if(o.isNever())return o;if(o.isBasis()&&!o.overlaps(K.intrinsic.object))return k.init("assignability",K.intrinsic.object,o);return F.$.lazilyResolve(()=>u0(zT(T.resolution,o,F)),`${T.reference}${F.pipe?"=>":"&"}${o.id}`)})}});class c0 extends No{expression=this.reference;structure=void 0;get resolution(){let T=this._resolve();return Ro[this.id]=T}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let T=this.reference,o=Ro[T],F=[];while(P(o,"context")){if(F.includes(o.id))return G(p8(o.id,F));F.push(o.id),o=Ro[o.id]}if(!P(o,"root"))return $T(`Unexpected resolution for reference ${this.reference}
28
- Seen: [${F.join("->")}]
29
- Resolution: ${r(o)}`);return o}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),o=this.$.resolutions[T];if(typeof o==="string")return o;if(P(o,"root"))return o.id;return $T(`Unexpected resolution for reference ${this.reference}: ${r(o)}`)}get defaultShortDescription(){return Zo.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,o)=>{let F=o.seen[this.reference];if(F?.includes(T))return!0;return o.seen[this.reference]=yT(F,T),this.resolution.traverseAllows(T,o)};traverseApply=(T,o)=>{let F=o.seen[this.reference];if(F?.includes(T))return;o.seen[this.reference]=yT(F,T),this.resolution.traverseApply(T,o)};compile(T){let o=this.resolutionId;T.if(`ctx.seen.${o} && ctx.seen.${o}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${o}`,()=>T.line(`ctx.seen.${o} = []`)),T.line(`ctx.seen.${o}.push(data)`),T.return(T.invoke(o))}}var p8=(T,o)=>`Alias '${T}' has a shallow resolution cycle: ${[...o,T].join("->")}`,_y={implementation:N8,Node:c0};class hF extends No{traverseApply=(T,o)=>{if(!this.traverseAllows(T,o))o.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return VF(this.errorContext)}compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var j8=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:yA(T,"numberAllowsNaN")&&T.domain!=="number"?G(WS.writeBadAllowNanMessage(T.domain)):T,applyConfig:(T,o)=>T.numberAllowsNaN===void 0&&T.domain==="number"&&o.numberAllowsNaN?{...T,numberAllowsNaN:!0}:T,defaults:{description:(T)=>Zo[T.domain],actual:(T)=>Number.isNaN(T)?"NaN":Zo[tT(T)]},intersections:{domain:(T,o)=>T.domain==="number"&&o.domain==="number"?T.numberAllowsNaN?o:T:k.init("domain",T,o)}});class i0 extends hF{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>tT(T)===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 Zo[this.domain]}innerToJsonSchema(T){if(this.domain==="bigint"||this.domain==="symbol")return T.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var WS={implementation:j8,Node:i0,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var x8=l({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(UT(T))return T;let{structure:o,...F}=T,A=!!o,y=o??{},S=d(F,(f,$)=>{if(hT(f,X0)){if(A)G(`Flattened structure key ${f} cannot be specified alongside a root 'structure' key.`);return y[f]=$,[]}return[f,$]});if(P(y,"constraint")||!ao(y))S.structure=y;return S},finalizeInnerJson:({structure:T,...o})=>Yo(T,"object")?{...T,...o}:o,keys:{domain:{child:!0,parse:(T,o)=>o.$.node("domain",T)},proto:{child:!0,parse:(T,o)=>o.$.node("proto",T)},structure:{child:!0,parse:(T,o)=>o.$.node("structure",T),serialize:(T)=>{if(!T.sequence?.minLength)return T.collapsibleJson;let{sequence:o,...F}=T.collapsibleJson,{minVariadicLength:A,...y}=o,S=y.variadic&&Object.keys(y).length===1?y.variadic:y;return{...F,sequence:S}}},divisor:{child:!0,parse:So("divisor")},max:{child:!0,parse:So("max")},min:{child:!0,parse:So("min")},maxLength:{child:!0,parse:So("maxLength")},minLength:{child:!0,parse:So("minLength")},exactLength:{child:!0,parse:So("exactLength")},before:{child:!0,parse:So("before")},after:{child:!0,parse:So("after")},pattern:{child:!0,parse:So("pattern")},predicate:{child:!0,parse:So("predicate")}},reduce:(T,o)=>d0({},T,{$:o,invert:!1,pipe:!1}),defaults:{description:(T)=>{if(T.children.length===0)return"unknown";if(T.structure)return T.structure.description;let o=[];if(T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisDescription))o.push(T.basis.description);if(T.refinements.length){let F=T.refinements.toSorted((A,y)=>A.kind==="min"&&y.kind==="max"?-1:0).map((A)=>A.description);o.push(...F)}if(T.inner.predicate)o.push(...T.inner.predicate.map((F)=>F.description));return o.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map((o)=>o.expected).join(`
22
+ `);class B0{path=[];errors=new F0(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,F){this.root=T,this.config=F}get data(){let T=this.root;for(let F of this.path)T=T?.[F];return T}get propString(){return i0(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let F=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(F)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let F={path:new L_(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(F);else this.queuedMorphs.push(F)}finalize(T){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 T?T(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(T){return this.errorFromContext(T)}errorFromContext(T){let F=new ZF(T,this);if(this.currentBranch)this.currentBranch.error=F;else this.errors.add(F);return F}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:F,morphs:_}of T){if(this.errors.affectsPath(F))continue;this.applyMorphsAtPath(F,_)}}}applyMorphsAtPath(T,F){let _=T.at(-1),W;if(_!==void 0){W=this.root;for(let J=0;J<T.length-1;J++)W=W[T[J]]}this.path=[...T];for(let J of F){let $=OT(J),Y=J(W===void 0?this.root:W[_],this);if(Y instanceof ZF){this.errors.add(Y);break}if(Y instanceof F0){if(!$)this.errors.merge(Y);break}if(W===void 0)this.root=Y;else W[_]=Y;this.applyQueuedMorphs()}}}var _0=(T,F,_)=>{if(!_)return F();_.path.push(T);let W=F();return _.path.pop(),W};class C_ extends k0{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,F){super((W,J,$=this.onFail)=>{if(J)return this.traverseApply(W,J),J.hasError()?J.errors:J.data;return this.rootApply(W,$)},{attach:T});this.attachments=T,this.$=F,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((W,J)=>LG(W,J.shallowReferences),[this]);let _=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!_){let J=this.children[W].flatRefs;for(let $=0;$<J.length;$++){let Y=J[$];if(!this.flatRefs.some((Z)=>E8(Z,Y))){this.flatRefs.push(Y);for(let Z of Y.node.branches)if(Z.hasKind("morph")||Z.hasKind("intersection")&&Z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:Y.path,propString:Y.propString,node:Z})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,J)=>W.path.length>J.path.length?1:W.path.length<J.path.length?-1:W.propString>J.propString?1:W.propString<J.propString?-1:W.node.expression<J.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new B0(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(F,_)=>{if(this.allows(F))return F;let W=new B0(F,this.$.resolvedConfig);return this.traverseApply(F,W),W.finalize(_)};case"contextual":return(F,_)=>{let W=new B0(F,this.$.resolvedConfig);return this.traverseApply(F,W),W.finalize(_)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(F,_)=>{if(this.allows(F))return this.contextFreeMorph(T&&(typeof F==="object"&&F!==null||typeof F==="function")?T(F):F);let W=new B0(F,this.$.resolvedConfig);return this.traverseApply(F,W),W.finalize(_)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,a(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=DG(this.metaJson);cacheGetter(T,F){return Object.defineProperty(this,T,{value:F}),F}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=pF(this.kind);precompilation;assert=(T,F)=>this(T,F,(_)=>_.throw());traverse(T,F){return this(T,F,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let F={};for(let[_,W]of this.innerEntries){let J=this.impl.keys[_];if(J.reduceIo)J.reduceIo(T,F,W);else if(J.child){let $=W;F[_]=YT($)?$.map((Y)=>Y[T]):$[T]}else F[_]=W}return this.$.node(this.kind,F)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let F=OT(T)?T:this.$.parseDefinition(T);return this.innerHash===F.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)RF(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!u0(T,this.kind))RF(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return u0(H8,this.kind)}isConstraint(){return u0(IW,this.kind)}isStructural(){return u0(xF,this.kind)}isRefinement(){return u0(Y2,this.kind)}isRoot(){return u0(bF,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let F=N_.normalize(T);return this._select(F)}_select(T){let F=N_.applyBoundary[T.boundary??"references"](this);if(T.kind)F=F.filter((_)=>_.kind===T.kind);if(T.where)F=F.filter(T.where);return N_.applyMethod[T.method??"filter"](F,this,T)}transform(T,F){return this._transform(T,this._createTransformContext(F))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,F){let _=F.bindScope??this.$;if(F.seen[this.id])return this.$.lazilyResolve(F.seen[this.id]);if(F.shouldTransform?.(this,F)===!1)return this;let W;if(F.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==F.undeclaredKeyHandling)F={...F,undeclaredKeyHandling:this.undeclared};let J=m(this.inner,(X,O)=>{if(!this.impl.keys[X].child)return[X,O];let M=O;if(!YT(M)){let K=M._transform(T,F);return K?[X,K]:[]}if(M.length===0)return[X,O];let E=M.flatMap((K)=>{return K._transform(T,F)??[]});return E.length?[X,E]:[]});delete F.seen[this.id];let $=Object.assign(J,{meta:this.meta}),Y=F.selected&&!F.selected.includes(this)?$:T(this.kind,$,F);if(Y===null)return null;if(OT(Y))return W=Y;let Z=Object.keys(Y);if((Z.length===0||Z.length===1&&Z[0]==="meta")&&!b0(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in Y))return F.undeclaredKeyHandling?{...Y,value:w.intrinsic.unknown}:null;if(this.kind==="morph")Y.in??=w.intrinsic.unknown;return W=_.node(this.kind,Y,F.parseOptions)}configureReferences(T,F="references"){let _=N_.normalize(F),W=typeof T==="string"?(Z,A)=>({...A,meta:{...A.meta,description:T}}):typeof T==="function"?(Z,A)=>({...A,meta:T(A.meta)}):(Z,A)=>({...A,meta:{...A.meta,...T}});if(_.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let J=this._select(_),$=J&&_F(J),Y=_.boundary==="child"?(Z,A)=>A.root.children.includes(Z):_.boundary==="shallow"?(Z)=>Z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:Y,selected:$}))}}var N_={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,F,_)=>{if(T.length===0)RF(z8(F,_));return T},find:(T)=>T[0],assertFind:(T,F,_)=>{if(T.length===0)RF(z8(F,_));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?qT(T,N_.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},z8=(T,F)=>`${T} had no references matching ${o(F)}.`,KG=(T)=>i0(T,{stringifyNonKey:(F)=>F.expression}),VG=/"(\$ark\.[^"]+)"/g,DG=(T)=>JSON.stringify(T).replaceAll(VG,"$1"),f0=(T,F)=>({path:T,node:F,propString:KG(T)}),E8=(T,F)=>T.propString===F.propString&&T.node.equals(F.node),A2=(T,F)=>x0(T,F,{isEqual:E8}),LG=(T,F)=>x0(T,F,{isEqual:(_,W)=>_.equals(W)});class I extends Array{static init(T,F,_,W){return new I({kind:T,l:F,r:_,path:W?.path??[],optional:W?.optional??!1})}add(T,F,_,W){return this.push({kind:T,l:F,r:_,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:F,r:_}=this[0],W=i0(T);return H2(`Intersection${W&&` at ${W}`} of ${R8(F,_)}`)}return`The following intersections result in unsatisfiable types:
23
+ \u2022 ${this.map(({path:T,l:F,r:_})=>`${T}: ${R8(F,_)}`).join(`
24
+ \u2022 `)}`}throw(){return z(this.describeReasons())}invert(){let T=this.map((F)=>({...F,l:F.r,r:F.l}));if(!(T instanceof I))return new I(...T);return T}withPrefixKey(T,F){return this.map((_)=>({..._,path:[T,..._.path],optional:_.optional||F==="optional"}))}toNeverIfDisjoint(){return w.intrinsic.never}}var R8=(T,F)=>`${G2(T)} and ${G2(F)}`,G2=(T)=>OT(T)?T.expression:YT(T)?T.map(G2).join(" | ")||"never":String(T),H2=(T)=>`${T} results in an unsatisfiable type`;var gF={},W0=(T,F,_)=>UT(T,F,{$:_,invert:!1,pipe:!1}),k_=(T,F,_)=>UT(T,F,{$:_,invert:!1,pipe:!0}),UT=(T,F,_)=>{let W=_.pipe?"|>":"&",J=`${T.hash}${W}${F.hash}`;if(gF[J]!==void 0)return gF[J];if(!_.pipe){let Z=`${F.hash}${W}${T.hash}`;if(gF[Z]!==void 0){let A=gF[Z],X=A instanceof I?A.invert():A;return gF[J]=X,X}}let $=!_.pipe||!T.includesTransform&&!F.includesTransform;if($&&T.equals(F))return T;let Y=$?O2(T,F,_):T.hasKindIn(...bF)?SG(T,F,_):O2(T,F,_);if(OT(Y)){if(T.equals(Y))Y=T;else if(F.equals(Y))Y=F}return gF[J]=Y,Y},O2=(T,F,_)=>{let W=T.precedence<F.precedence?T.kind:F.kind,J=T.impl.intersections[F.kind]??F.impl.intersections[T.kind];if(J===void 0)return null;else if(W===T.kind)return J(T,F,_);else{let $=J(F,T,{..._,invert:!_.invert});if($ instanceof I)$=$.invert();return $}},SG=(T,F,_)=>T.includesTransform||F.includesTransform?_.invert?w8(F,T,_):w8(T,F,_):O2(T,F,_),w8=(T,F,_)=>T.distribute((W)=>IG(W,F,_),(W)=>{let J=W.filter(OT);if(J.length===0)return I.init("union",T.branches,F.branches);if(J.length<T.branches.length||!T.branches.every((Z,A)=>Z.in.equals(J[A].in)))return _.$.parseSchema(J);let $;if(J.length===1){let Z=J[0];if(!$)return Z;return _.$.node("morph",{...Z.inner,in:Z.in.configure($,"self")})}let Y={branches:J};if($)Y.meta=$;return _.$.parseSchema(Y)}),IG=(T,F,_)=>{if(T.hasKind("morph")){let J=[...T.morphs];if(T.lastMorphIfNode){let $=UT(T.lastMorphIfNode,F,_);if($ instanceof I)return $;J[J.length-1]=$}else J.push(F);return _.$.node("morph",{morphs:J,in:T.inner.in})}if(F.hasKind("morph")){let J=UT(T,F.in,_);if(J instanceof I)return J;return _.$.node("morph",{morphs:[F],in:J})}return _.$.node("morph",{morphs:[F],in:T})};class R0 extends C_{constructor(T,F){super(T,F);Object.defineProperty(this,iT,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return W0(this,T,this.$)}}class n0 extends R0{traverseApply=(T,F)=>{if(!this.traverseAllows(T,F))F.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return YF(this.errorContext)}}var cT=(T)=>(F,_)=>{if(YT(F)){if(F.length===0)return;let J=F.map(($)=>_.$.node(T,$));if(T==="predicate")return J;return J.sort(($,Y)=>$.hash<Y.hash?-1:1)}let W=_.$.node(T,F);return W.hasOpenIntersection()?[W]:W},mF=(T)=>{let F=T.r.shift();if(!F){let W=T.l.length===0&&T.kind==="structure"?w.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,NG(T.l)),{prereduced:!0});for(let J of T.roots){if(W instanceof I)return W;W=UT(J,W,T.ctx)}return W}let _=!1;for(let W=0;W<T.l.length;W++){let J=UT(T.l[W],F,T.ctx);if(J===null)continue;if(J instanceof I)return J;if(!_){if(J.isRoot())return T.roots.push(J),T.l.splice(W),mF(T);T.l[W]=J,_=!0}else if(!T.l.includes(J))return a(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!_)T.l.push(F);if(T.kind==="intersection"){if(F.impliedSiblings)for(let W of F.impliedSiblings)x0(T.r,W)}return mF(T)},oF=(T)=>{return Object.entries(T).flatMap(([_,W])=>(_ in NW)?W:[]).sort((_,W)=>_.precedence<W.precedence?-1:_.precedence>W.precedence?1:_.kind==="predicate"&&W.kind==="predicate"?0:_.hash<W.hash?-1:1)},NG=(T)=>{let F={};for(let _ of T)if(_.hasOpenIntersection())F[_.kind]=r(F[_.kind],_);else{if(F[_.kind])return a(`Unexpected intersection of closed refinements of kind ${_.kind}`);F[_.kind]=_}return F},K8=(...T)=>z(V8(...T)),V8=(T,F,_)=>{let W=_.hasKind("morph")?"a morph":_.isUnknown()?"unknown":_.exclude(F).defaultShortDescription;return`${rJ(T)} operand must be ${F.description} (was ${W})`};var D8=(T,F,_)=>new XF(T,F,_,_,null);class kW extends k0{}class XF extends k0{[iT]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,F,_,W,J){super((...$)=>{let Y=m(this.names,(Z,A)=>{let X=this.arg$.parse($[Z]);if(!X.extends(this.constraints[Z]))z(CG(A,this.constraints[Z].expression,X.expression));return[A,X]});if(this.defIsLazy()){let Z=this.bodyDef(Y);return this.$.parse(Z)}return this.$.parse(F,{args:Y})});this.paramDefs=T,this.bodyDef=F,this.$=_,this.arg$=W,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof kW}cacheGetter(T,F){return Object.defineProperty(this,T,{value:F}),F}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:Z8(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,w.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var CG=(T,F,_)=>`${T} must be assignable to ${F} (was ${_})`;var kG=c({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class L8 extends R0{serializedPredicate=VT(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=YF(this.errorContext);traverseApply=(T,F)=>{if(!this.predicate(T,F.external)&&!F.hasError())F.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,F){return F.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var U2={implementation:kG,Node:L8};var BG=c({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:z(fG(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,F,_)=>_.$.node("divisor",{rule:Math.abs(T.rule*F.rule/qG(T.rule,F.rule))})},obviatesBasisDescription:!0});class S8 extends n0{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=w.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var M2={implementation:BG,Node:S8};var fG=(T)=>`divisor must be an integer (was ${T})`,qG=(T,F)=>{let _,W=T,J=F;while(J!==0)_=J,J=W%J,W=_;return W};class O0 extends n0{boundOperandKind=vG[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=xG(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${jG[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?bG(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var jG={"<":">=","<=":">",">":"<=",">=":"<"},yG={min:"max",minLength:"maxLength",after:"before"},BW={parse:(T)=>T||void 0},fW=(T)=>(F)=>{if(typeof F==="number")return{rule:F};let{exclusive:_,...W}=F;return _?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},qW=(T)=>(F)=>{if(typeof F==="number"||typeof F==="string"||F instanceof Date)return{rule:F};let{exclusive:_,...W}=F;if(!_)return W;let J=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return _?{...W,rule:T==="after"?J+1:J-1}:W},jW=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,PG=(T,F)=>`${T} bound must be a positive integer (was ${F})`,uF=(T)=>(F)=>{if(!Number.isInteger(F)||F<0)z(PG(T,F));return F},vG={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},xG=(T,F)=>`${qT(T,yG)?">":"<"}${F?"":"="}`,bG=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),I8=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var hG=c({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:jW,serialize:(T)=>T.toISOString()}},normalize:qW("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:DF},intersections:{after:(T,F)=>T.isStricterThan(F)?T:F}});class N8 extends O0{impliedBasis=w.intrinsic.Date.internal;collapsibleLimitString=DF(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,F){return F.fallback.date({code:"date",base:T,after:this.rule})}}var Q2={implementation:hG,Node:N8};var pG=c({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:jW,serialize:(T)=>T.toISOString()}},normalize:qW("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:DF},intersections:{before:(T,F)=>T.isStricterThan(F)?T:F,after:(T,F,_)=>T.overlapsRange(F)?T.overlapIsUnit(F)?_.$.node("unit",{unit:T.rule}):null:I.init("range",T,F)}});class C8 extends O0{collapsibleLimitString=DF(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=w.intrinsic.Date.internal;reduceJsonSchema(T,F){return F.fallback.date({code:"date",base:T,before:this.rule})}}var z2={implementation:pG,Node:C8};var gG=c({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:uF("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,F,_)=>I.init("unit",_.$.node("unit",{unit:T.rule}),_.$.node("unit",{unit:F.rule}),{path:["length"]}),minLength:(T,F)=>T.rule>=F.rule?T:I.init("range",T,F),maxLength:(T,F)=>T.rule<=F.rule?T:I.init("range",T,F)}});class k8 extends n0{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=w.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return ET.throwInternalOperandError("exactLength",T)}}}var E2={implementation:gG,Node:k8};var mG=c({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:BW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,F)=>T.isStricterThan(F)?T:F,min:(T,F,_)=>T.overlapsRange(F)?T.overlapIsUnit(F)?_.$.node("unit",{unit:T.rule}):null:I.init("range",T,F)},obviatesBasisDescription:!0});class B8 extends O0{impliedBasis=w.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var R2={implementation:mG,Node:B8};var oG=c({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:uF("maxLength")}},reduce:(T,F)=>T.rule===0?F.node("exactLength",T):void 0,normalize:fW("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,F)=>T.isStricterThan(F)?T:F,minLength:(T,F,_)=>T.overlapsRange(F)?T.overlapIsUnit(F)?_.$.node("exactLength",{rule:T.rule}):null:I.init("range",T,F)}});class f8 extends O0{impliedBasis=w.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return ET.throwInternalOperandError("maxLength",T)}}}var w2={implementation:oG,Node:f8};var uG=c({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:BW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,F)=>T.isStricterThan(F)?T:F},obviatesBasisDescription:!0});class q8 extends O0{impliedBasis=w.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var K2={implementation:uG,Node:q8};var cG=c({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:uF("minLength")}},reduce:(T)=>T.rule===0?w.intrinsic.unknown:void 0,normalize:fW("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,F)=>T.isStricterThan(F)?T:F}});class j8 extends O0{impliedBasis=w.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return ET.throwInternalOperandError("minLength",T)}}}var V2={implementation:cG,Node:j8};var y8={min:K2.implementation,max:R2.implementation,minLength:V2.implementation,maxLength:w2.implementation,exactLength:E2.implementation,after:Q2.implementation,before:z2.implementation},P8={min:K2.Node,max:R2.Node,minLength:V2.Node,maxLength:w2.Node,exactLength:E2.Node,after:Q2.Node,before:z2.Node};var dG=c({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class v8 extends n0{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=w.intrinsic.string.internal;reduceJsonSchema(T,F){if(T.pattern)return F.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var D2={implementation:dG,Node:v8};var B_=(T,F)=>{let _=lG(T);if(F&&!F.includes(_))return z(`Root of kind ${_} should be one of ${F}`);return _},lG=(T)=>{if(q(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in T0)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return z(x8(T));if("morphs"in T)return"morph";if("branches"in T||YT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let F=Object.keys(T);if(F.length===0||F.some((_)=>(_ in NW)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return z(x8(T))},x8=(T)=>`${o(T)} is not a valid type schema`,b8={},iG=(T)=>YT(T)?T.map((F)=>F.collapsibleJson):T.collapsibleJson,tT={};w.nodesByRegisteredId=tT;var L2=(T)=>{return b8[T]??=0,`${T}${++b8[T]}`},S2=(T)=>{let F=cF[T.kind],_=F.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:J,...$}=_,Y=J===void 0?{}:typeof J==="string"?{description:J}:J,Z=i1($).sort(([X],[O])=>hF(X)?hF(O)?pF(X)-pF(O):1:hF(O)?-1:X<O?-1:1).filter(([X,O])=>{if(X.startsWith("meta.")){let M=X.slice(5);return Y[M]=O,!1}return!0});for(let X of Z){let O=X[0],M=F.keys[O];if(!M)return z(`Key ${O} is not valid on ${T.kind} schema`);let E=M.parse?M.parse(X[1],T):X[1];if(E!==H0&&(E!==void 0||M.preserveUndefined))W[O]=E}if(F.reduce&&!T.prereduced){let X=F.reduce(W,T.$);if(X){if(X instanceof I)return X.throw();return tG(X,Y)}}return I2({id:T.id,kind:T.kind,inner:W,meta:Y,$:T.$})},I2=({id:T,kind:F,inner:_,meta:W,$:J,ignoreCache:$})=>{let Y=cF[F],Z=i1(_),A=[],X={};for(let[f,y]of Z){let h=Y.keys[f],TT=h.serialize??(h.child?iG:E0);if(X[f]=TT(y),h.child===!0){let u=y;if(YT(u))A.push(...u);else A.push(u)}else if(typeof h.child==="function")A.push(...h.child(y))}if(Y.finalizeInnerJson)X=Y.finalizeInnerJson(X);let O={...X},M={};if(!b0(W))M=m(W,(f,y)=>[f,f==="examples"?y:E0(y)]),O.meta=yW(M,"description",!0);X=yW(X,Y.collapsibleKey,!1);let E=JSON.stringify({kind:F,...X});O=yW(O,Y.collapsibleKey,!1);let K=yW(O,Y.collapsibleKey,!0),j=JSON.stringify({kind:F,...O});if(J.nodesByHash[j]&&!$)return J.nodesByHash[j];let S={id:T,kind:F,impl:Y,inner:_,innerEntries:Z,innerJson:X,innerHash:E,meta:W,metaJson:M,json:O,hash:j,collapsibleJson:K,children:A};if(F!=="intersection"){for(let f in _)if(f!=="in"&&f!=="out")S[f]=_[f]}let P=new p8[F](S,J);return J.nodesByHash[j]=P},h8=(T,F)=>{if(T.id===F)return T;if(OT(tT[F]))a(`Unexpected attempt to overwrite node id ${F}`);return I2({id:F,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},tG=(T,F,_)=>{if(_&&OT(tT[_]))a(`Unexpected attempt to overwrite node id ${_}`);return I2({id:_??L2(F.alias??T.kind),kind:T.kind,inner:T.inner,meta:F,$:T.$})},yW=(T,F,_)=>{let W=Object.keys(T);if(W.length===1&&W[0]===F){let J=T[F];if(_)return J;if(eT(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return T};var f_=(T,F,_)=>{if(T.key!==F.key)return null;let W=T.key,J=UT(T.value,F.value,_),$=T.required||F.required?"required":"optional";if(J instanceof I)if($==="optional")J=w.intrinsic.never.internal;else return J.withPrefixKey(T.key,T.required&&F.required?"required":"optional");if($==="required")return _.$.node("required",{key:W,value:J});let Y=T.hasDefault()?F.hasDefault()?T.default===F.default?T.default:z(N2(T.default,F.default)):T.default:F.hasDefault()?F.default:H0;return _.$.node("optional",{key:W,value:J,default:Y})};class q_ extends R0{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=w.intrinsic.object.internal;serializedKey=t0(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=r(this.value.flatRefs.map((T)=>f0([this.key,...T.path],T.node)),f0([this.key],this.value));_transform(T,F){F.path.push(this.key);let _=super._transform(T,F);return F.path.pop(),_}hasDefault(){return"default"in this.inner}traverseAllows=(T,F)=>{if(this.key in T)return _0(this.key,()=>this.value.traverseAllows(T[this.key],F),F);return this.optional};traverseApply=(T,F)=>{if(this.key in T)_0(this.key,()=>this.value.traverseApply(T[this.key],F),F);else if(this.hasKind("required"))F.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var N2=(T,F)=>`Invalid intersection of default values ${o(T)} & ${o(F)}`;var nG=c({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,F)=>F.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,F)=>{if(F.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return F.node("optional",{...T,value:T.value.or(v.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:f_}});class g8 extends q_{constructor(...T){super(...T);if("default"in this.inner)y_(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,...F}=this.inner;return this.cacheGetter("outProp",this.$.node("required",F,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${o(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=sG(this);defaultValueMorphRef=this.defaultValueMorph&&VT(this.defaultValueMorph)}var j_={implementation:nG,Node:g8},rG={},sG=(T)=>{if(!T.hasDefault())return;let F=`{${T.compiledKey}: ${T.value.id} = ${E0(T.default)}}`;return rG[F]??=C2(T.key,T.value,T.default)},C2=(T,F,_)=>{if(typeof _==="function")return F.includesTransform?(J,$)=>{return _0(T,()=>F(J[T]=_(),$),$),J}:(J)=>{return J[T]=_(),J};let W=F.includesTransform?F.assert(_):_;return eT(W,"object")?(J,$)=>{return _0(T,()=>F(J[T]=_,$),$),J}:(J)=>{return J[T]=W,J}},y_=(T,F,_)=>{let W=WF(F);if(eT(F,"object")&&!W)z(aG(_));let J=T.in(W?F():F);if(J instanceof F0){if(_===null)z(`Default ${J.summary}`);let $=J.transform((Y)=>Y.transform((Z)=>({...Z,prefixPath:[_]})));z(`Default for ${$.summary}`)}return F},aG=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${t0(T)} `}must be specified as a function like () => ({my: 'object'})`};class w0 extends C_{constructor(T,F){super(T,F);Object.defineProperty(this,iT,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let F=this(T);if(F instanceof F0)return F;return{value:F}}}}as(){return this}brand(T){if(T==="")return z(eG);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,F){let _=this.branches.map(T);return F?.(_)??_}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let F=Z2(this.$.resolvedConfig.toJsonSchema,T);F.useRefs||=this.isCyclic;let _=typeof F.dialect==="string"?{$schema:F.dialect}:{};if(Object.assign(_,this.toJsonSchemaRecurse(F)),F.useRefs)_.$defs=m(this.references,(W,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema(F)]:[]);return _}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let F=this.innerToJsonSchema(T);return Object.assign(F,this.metaJson)}intersect(T){let F=this.$.parseDefinition(T),_=this.rawIntersect(F);if(_ instanceof I)return _;return this.$.finalize(_)}rawIntersect(T){return W0(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let F=this.intersect(T);return F instanceof I?F.throw():F}rawAnd(T){let F=this.rawIntersect(T);return F instanceof I?F.throw():F}or(T){let F=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(F))}rawOr(T){let F=[...this.branches,...T.branches];return this.$.node("union",F)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((F,_)=>F.intersect(_).toNeverIfDisjoint(),w.intrinsic.unknown.internal);if(T.branches.length===0)z(H2(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return z(T9(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let F=this.$.parseDefinition(T);return this.$.schema(F.distribute((_)=>this.applyStructuralOperation("merge",[m8(_)??z(o8("merge",_.expression))])))}applyStructuralOperation(T,F){return this.distribute((_)=>{if(_.equals(w.intrinsic.object)&&T!=="merge")return _;let W=m8(_);if(!W)z(o8(T,_.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(...F);if(T==="props")return W.props;let J=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{..._.inner,structure:W[J](...F)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let F=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((_)=>_.extends(F)))}exclude(T){let F=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((_)=>!_.extends(F)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof I)}extends(T){let F=this.intersect(T);return!(F instanceof I)&&this.equals(F)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,F="shallow"){return this.configureReferences(T,F)}describe(T,F="shallow"){return this.configure({description:T},F)}optional(){return[this,"?"]}default(T){return y_(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let F=T.reduce((_,W)=>_.rawPipeOnce(W),this);return this.$.finalize(F)}tryPipe(...T){let F=T.reduce((_,W)=>_.rawPipeOnce(q(W,"root")?W:(J,$)=>{try{return W(J,$)}catch(Y){return $.error({code:"predicate",predicate:W,actual:`aborted due to error:
25
+ ${Y}
26
+ `})}}),this);return this.$.finalize(F)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let F=k_(this,T,this.$);if(F instanceof I)return F.throw();return F}rawPipeOnce(T){if(q(T,"root"))return this.toNode(T);return this.distribute((F)=>F.hasKind("morph")?this.$.node("morph",{in:F.inner.in,morphs:[...F.morphs,T]}):this.$.node("morph",{in:F,morphs:[T]}),this.$.parseSchema)}narrow(T){return this.constrainOut("predicate",T)}constrain(T,F){return this._constrain("root",T,F)}constrainIn(T,F){return this._constrain("in",T,F)}constrainOut(T,F){return this._constrain("out",T,F)}_constrain(T,F,_){let W=this.$.node(F,_);if(W.isRoot())return W.isUnknown()?this:a(`Unexpected constraint node ${W}`);let J=T==="root"?this:this[T];if(J.hasKind("morph")||W.impliedBasis&&!J.extends(W.impliedBasis))return K8(F,W.impliedBasis,this);let $=this.$.node("intersection",{[W.kind]:W}),Y=T==="out"?k_(this,$,this.$):W0(this,$,this.$);if(Y instanceof I)Y.throw();return this.$.finalize(Y)}onUndeclaredKey(T){let F=typeof T==="string"?T:T.rule,_=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((W,J)=>W==="structure"?F==="ignore"?pJ(J,{undeclared:1}):{...J,undeclared:F}:J,_?void 0:{shouldTransform:(W)=>!u0(xF,W.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!d0(this.shallowMorphs,T.shallowMorphs))return!1;if(!d0(this.flatMorphs,T.flatMorphs,{isEqual:(F,_)=>F.propString===_.propString&&(F.node.hasKind("morph")&&_.node.hasKind("morph")?F.node.hasEqualMorphs(_.node):F.node.hasKind("intersection")&&_.node.hasKind("intersection")?F.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(T){return this.onUndeclaredKey({rule:T,deep:!0})}filter(T){return this.constrainIn("predicate",T)}divisibleBy(T){return this.constrain("divisor",T)}matching(T){return this.constrain("pattern",T)}atLeast(T){return this.constrain("min",T)}atMost(T){return this.constrain("max",T)}moreThan(T){return this.constrain("min",dF(T))}lessThan(T){return this.constrain("max",dF(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",dF(T))}lessThanLength(T){return this.constrain("maxLength",dF(T))}exactlyLength(T){return this.constrain("exactLength",T)}atOrAfter(T){return this.constrain("after",T)}atOrBefore(T){return this.constrain("before",T)}laterThan(T){return this.constrain("after",dF(T))}earlierThan(T){return this.constrain("before",dF(T))}}var eG="Expected a non-empty brand name after #",dF=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},P_=(T,F)=>q(F,"root")?q(T,"root")?T.extends(F):F.allows(T):q(T,"root")?T.hasUnit(F):F===T,m8=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(w.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(w.intrinsic.emptyStructure);return null},T9=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
+ ${T}`,o8=(T,F)=>`${T} operand must be an object (was ${F})`;var h0=(T,F)=>m(CW(T),(_,W)=>[W,F]);var F9=(T)=>typeof T==="string"?{reference:T}:T,u8=(T)=>T instanceof I?w.intrinsic.never.internal:T,_9=c({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:F9,defaults:{description:(T)=>T.reference},intersections:{alias:(T,F,_)=>_.$.lazilyResolve(()=>u8(UT(T.resolution,F.resolution,_)),`${T.reference}${_.pipe?"=>":"&"}${F.reference}`),...h0("alias",(T,F,_)=>{if(F.isUnknown())return T;if(F.isNever())return F;if(F.isBasis()&&!F.overlaps(w.intrinsic.object))return I.init("assignability",w.intrinsic.object,F);return _.$.lazilyResolve(()=>u8(UT(T.resolution,F,_)),`${T.reference}${_.pipe?"=>":"&"}${F.id}`)})}});class c8 extends w0{expression=this.reference;structure=void 0;get resolution(){let T=this._resolve();return tT[this.id]=T}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let T=this.reference,F=tT[T],_=[];while(q(F,"context")){if(_.includes(F.id))return z(W9(F.id,_));_.push(F.id),F=tT[F.id]}if(!q(F,"root"))return a(`Unexpected resolution for reference ${this.reference}
28
+ Seen: [${_.join("->")}]
29
+ Resolution: ${o(F)}`);return F}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),F=this.$.resolutions[T];if(typeof F==="string")return F;if(q(F,"root"))return F.id;return a(`Unexpected resolution for reference ${this.reference}: ${o(F)}`)}get defaultShortDescription(){return T0.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,F)=>{let _=F.seen[this.reference];if(_?.includes(T))return!0;return F.seen[this.reference]=r(_,T),this.resolution.traverseAllows(T,F)};traverseApply=(T,F)=>{let _=F.seen[this.reference];if(_?.includes(T))return;F.seen[this.reference]=r(_,T),this.resolution.traverseApply(T,F)};compile(T){let F=this.resolutionId;T.if(`ctx.seen.${F} && ctx.seen.${F}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${F}`,()=>T.line(`ctx.seen.${F} = []`)),T.line(`ctx.seen.${F}.push(data)`),T.return(T.invoke(F))}}var W9=(T,F)=>`Alias '${T}' has a shallow resolution cycle: ${[...F,T].join("->")}`,v_={implementation:_9,Node:c8};class LF extends w0{traverseApply=(T,F)=>{if(!this.traverseAllows(T,F))F.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return YF(this.errorContext)}compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var J9=c({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:PF(T,"numberAllowsNaN")&&T.domain!=="number"?z(PW.writeBadAllowNanMessage(T.domain)):T,applyConfig:(T,F)=>T.numberAllowsNaN===void 0&&T.domain==="number"&&F.numberAllowsNaN?{...T,numberAllowsNaN:!0}:T,defaults:{description:(T)=>T0[T.domain],actual:(T)=>Number.isNaN(T)?"NaN":T0[fT(T)]},intersections:{domain:(T,F)=>T.domain==="number"&&F.domain==="number"?T.numberAllowsNaN?F:T:I.init("domain",T,F)}});class d8 extends LF{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>fT(T)===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 T0[this.domain]}innerToJsonSchema(T){if(this.domain==="bigint"||this.domain==="symbol")return T.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var PW={implementation:J9,Node:d8,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var $9=c({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(OT(T))return T;let{structure:F,..._}=T,W=!!F,J=F??{},$=m(_,(Y,Z)=>{if(qT(Y,O8)){if(W)z(`Flattened structure key ${Y} cannot be specified alongside a root 'structure' key.`);return J[Y]=Z,[]}return[Y,Z]});if(q(J,"constraint")||!b0(J))$.structure=J;return $},finalizeInnerJson:({structure:T,...F})=>eT(T,"object")?{...T,...F}:F,keys:{domain:{child:!0,parse:(T,F)=>F.$.node("domain",T)},proto:{child:!0,parse:(T,F)=>F.$.node("proto",T)},structure:{child:!0,parse:(T,F)=>F.$.node("structure",T),serialize:(T)=>{if(!T.sequence?.minLength)return T.collapsibleJson;let{sequence:F,..._}=T.collapsibleJson,{minVariadicLength:W,...J}=F,$=J.variadic&&Object.keys(J).length===1?J.variadic:J;return{..._,sequence:$}}},divisor:{child:!0,parse:cT("divisor")},max:{child:!0,parse:cT("max")},min:{child:!0,parse:cT("min")},maxLength:{child:!0,parse:cT("maxLength")},minLength:{child:!0,parse:cT("minLength")},exactLength:{child:!0,parse:cT("exactLength")},before:{child:!0,parse:cT("before")},after:{child:!0,parse:cT("after")},pattern:{child:!0,parse:cT("pattern")},predicate:{child:!0,parse:cT("predicate")}},reduce:(T,F)=>l8({},T,{$:F,invert:!1,pipe:!1}),defaults:{description:(T)=>{if(T.children.length===0)return"unknown";if(T.structure)return T.structure.description;let F=[];if(T.basis&&!T.refinements.some((_)=>_.impl.obviatesBasisDescription))F.push(T.basis.description);if(T.refinements.length){let _=T.refinements.toSorted((W,J)=>W.kind==="min"&&J.kind==="max"?-1:0).map((W)=>W.description);F.push(..._)}if(T.inner.predicate)F.push(...T.inner.predicate.map((_)=>_.description));return F.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map((F)=>F.expected).join(`
30
30
  \u25E6 `)}`,problem:(T)=>`(${T.actual}) must be...
31
- ${T.expected}`},intersections:{intersection:(T,o,F)=>d0(T.inner,o.inner,F),...eo("intersection",(T,o,F)=>{if(T.children.length===0)return o;let{domain:A,proto:y,...S}=T.inner,f=y??A,$=f?zT(f,o,F):o;return $ instanceof k?$:T?.basis?.equals($)?T:T.$.node("intersection",{...S,[$.kind]:$},{prereduced:!0})})}});class r0 extends No{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=b8(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(T){return this.children.reduce((o,F)=>F.isBasis()?F.toJsonSchemaRecurse(T):F.reduceJsonSchema(o,T),{})}traverseAllows=(T,o)=>this.children.every((F)=>F.traverseAllows(T,o));traverseApply=(T,o)=>{let F=o.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,o),o.currentErrorCount>F)return}if(this.refinements.length){for(let A=0;A<this.refinements.length-1;A++)if(this.refinements[A].traverseApply(T,o),o.failFast&&o.currentErrorCount>F)return;if(this.refinements.at(-1).traverseApply(T,o),o.currentErrorCount>F)return}if(this.structure){if(this.structure.traverseApply(T,o),o.currentErrorCount>F)return}if(this.inner.predicate){for(let A=0;A<this.inner.predicate.length-1;A++)if(this.inner.predicate[A].traverseApply(T,o),o.failFast&&o.currentErrorCount>F)return;this.inner.predicate.at(-1).traverseApply(T,o)}};compile(T){if(T.traversalKind==="Allows"){for(let o of this.children)T.check(o);T.return(!0);return}if(T.initializeErrorCount(),this.basis){if(T.check(this.basis),this.children.length>1)T.returnIfFail()}if(this.refinements.length){for(let o=0;o<this.refinements.length-1;o++)T.check(this.refinements[o]),T.returnIfFailFast();if(T.check(this.refinements.at(-1)),this.structure||this.inner.predicate)T.returnIfFail()}if(this.structure){if(T.check(this.structure),this.inner.predicate)T.returnIfFail()}if(this.inner.predicate){for(let o=0;o<this.inner.predicate.length-1;o++)T.check(this.inner.predicate[o]),T.returnIfFail();T.check(this.inner.predicate.at(-1))}}}var O$={implementation:x8,Node:r0},b8=(T)=>{let o=T.structure?.expression||`${T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((F)=>F.expression).join(" & ")}`||"unknown";if(o==="Array == 0")o="[]";return o},d0=(T,o,F)=>{let A={},y=T.proto??T.domain,S=o.proto??o.domain,f=y?S?zT(y,S,F):y:S;if(f instanceof k)return f;if(f)A[f.kind]=f;return WA({kind:"intersection",baseInner:A,l:MA(T),r:MA(o),roots:[],ctx:F})};var q8=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,o)=>o.$.parseSchema(T)},morphs:{parse:KF,serialize:(T)=>T.map((o)=>P(o,"root")?o.json:BT(o))},declaredIn:{child:!1,serialize:(T)=>T.json},declaredOut:{child:!1,serialize:(T)=>T.json}},normalize:(T)=>T,defaults:{description:(T)=>`a morph from ${T.in.description} to ${T.out?.description??"unknown"}`},intersections:{morph:(T,o,F)=>{if(!T.hasEqualMorphs(o))return G(v8(T.expression,o.expression));let A=zT(T.in,o.in,F);if(A instanceof k)return A;let y={morphs:T.morphs};if(T.declaredIn||o.declaredIn){let S=zT(T.in,o.in,F);if(S instanceof k)return S.throw();else y.declaredIn=S}if(T.declaredOut||o.declaredOut){let S=zT(T.out,o.out,F);if(S instanceof k)return S.throw();else y.declaredOut=S}return A.distribute((S)=>F.$.node("morph",{...y,in:S}),F.$.parseSchema)},...eo("morph",(T,o,F)=>{let A=T.inner.in?zT(T.inner.in,o,F):o;return A instanceof k?A:A.equals(T.inner.in)?T:F.$.node("morph",{...T.inner,in:A})})}});class l0 extends No{serializedMorphs=this.morphs.map(BT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=P(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??K.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??K.intrinsic.unknown.internal}declareIn(T){return this.$.node("morph",{...this.inner,declaredIn:T})}declareOut(T){return this.$.node("morph",{...this.inner,declaredOut:T})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(T){return T.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(T),out:this.introspectableOut?.toJsonSchemaRecurse(T)??null})}compile(T){if(T.traversalKind==="Allows"){if(!this.introspectableIn)return;T.return(T.invoke(this.introspectableIn));return}if(this.introspectableIn)T.line(T.invoke(this.introspectableIn));T.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(T,o)=>!this.introspectableIn||this.introspectableIn.traverseAllows(T,o);traverseApply=(T,o)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(T,o);o.queueMorphs(this.morphs)};hasEqualMorphs(T){return fF(this.morphs,T.morphs,{isEqual:(o,F)=>o===F||P(o,"root")&&P(F,"root")&&o.equals(F)})}}var X$={implementation:q8,Node:l0},v8=(T,o)=>`The intersection of distinct morphs at a single path is indeterminate:
31
+ ${T.expected}`},intersections:{intersection:(T,F,_)=>l8(T.inner,F.inner,_),...h0("intersection",(T,F,_)=>{if(T.children.length===0)return F;let{domain:W,proto:J,...$}=T.inner,Y=J??W,Z=Y?UT(Y,F,_):F;return Z instanceof I?Z:T?.basis?.equals(Z)?T:T.$.node("intersection",{...$,[Z.kind]:Z},{prereduced:!0})})}});class i8 extends w0{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=Y9(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(T){return this.children.reduce((F,_)=>_.isBasis()?_.toJsonSchemaRecurse(T):_.reduceJsonSchema(F,T),{})}traverseAllows=(T,F)=>this.children.every((_)=>_.traverseAllows(T,F));traverseApply=(T,F)=>{let _=F.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,F),F.currentErrorCount>_)return}if(this.refinements.length){for(let W=0;W<this.refinements.length-1;W++)if(this.refinements[W].traverseApply(T,F),F.failFast&&F.currentErrorCount>_)return;if(this.refinements.at(-1).traverseApply(T,F),F.currentErrorCount>_)return}if(this.structure){if(this.structure.traverseApply(T,F),F.currentErrorCount>_)return}if(this.inner.predicate){for(let W=0;W<this.inner.predicate.length-1;W++)if(this.inner.predicate[W].traverseApply(T,F),F.failFast&&F.currentErrorCount>_)return;this.inner.predicate.at(-1).traverseApply(T,F)}};compile(T){if(T.traversalKind==="Allows"){for(let F of this.children)T.check(F);T.return(!0);return}if(T.initializeErrorCount(),this.basis){if(T.check(this.basis),this.children.length>1)T.returnIfFail()}if(this.refinements.length){for(let F=0;F<this.refinements.length-1;F++)T.check(this.refinements[F]),T.returnIfFailFast();if(T.check(this.refinements.at(-1)),this.structure||this.inner.predicate)T.returnIfFail()}if(this.structure){if(T.check(this.structure),this.inner.predicate)T.returnIfFail()}if(this.inner.predicate){for(let F=0;F<this.inner.predicate.length-1;F++)T.check(this.inner.predicate[F]),T.returnIfFail();T.check(this.inner.predicate.at(-1))}}}var k2={implementation:$9,Node:i8},Y9=(T)=>{let F=T.structure?.expression||`${T.basis&&!T.refinements.some((_)=>_.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((_)=>_.expression).join(" & ")}`||"unknown";if(F==="Array == 0")F="[]";return F},l8=(T,F,_)=>{let W={},J=T.proto??T.domain,$=F.proto??F.domain,Y=J?$?UT(J,$,_):J:$;if(Y instanceof I)return Y;if(Y)W[Y.kind]=Y;return mF({kind:"intersection",baseInner:W,l:oF(T),r:oF(F),roots:[],ctx:_})};var Z9=c({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,F)=>F.$.parseSchema(T)},morphs:{parse:_F,serialize:(T)=>T.map((F)=>q(F,"root")?F.json:VT(F))},declaredIn:{child:!1,serialize:(T)=>T.json},declaredOut:{child:!1,serialize:(T)=>T.json}},normalize:(T)=>T,defaults:{description:(T)=>`a morph from ${T.in.description} to ${T.out?.description??"unknown"}`},intersections:{morph:(T,F,_)=>{if(!T.hasEqualMorphs(F))return z(X9(T.expression,F.expression));let W=UT(T.in,F.in,_);if(W instanceof I)return W;let J={morphs:T.morphs};if(T.declaredIn||F.declaredIn){let $=UT(T.in,F.in,_);if($ instanceof I)return $.throw();else J.declaredIn=$}if(T.declaredOut||F.declaredOut){let $=UT(T.out,F.out,_);if($ instanceof I)return $.throw();else J.declaredOut=$}return W.distribute(($)=>_.$.node("morph",{...J,in:$}),_.$.parseSchema)},...h0("morph",(T,F,_)=>{let W=T.inner.in?UT(T.inner.in,F,_):F;return W instanceof I?W:W.equals(T.inner.in)?T:_.$.node("morph",{...T.inner,in:W})})}});class t8 extends w0{serializedMorphs=this.morphs.map(VT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=q(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??w.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??w.intrinsic.unknown.internal}declareIn(T){return this.$.node("morph",{...this.inner,declaredIn:T})}declareOut(T){return this.$.node("morph",{...this.inner,declaredOut:T})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(T){return T.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(T),out:this.introspectableOut?.toJsonSchemaRecurse(T)??null})}compile(T){if(T.traversalKind==="Allows"){if(!this.introspectableIn)return;T.return(T.invoke(this.introspectableIn));return}if(this.introspectableIn)T.line(T.invoke(this.introspectableIn));T.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(T,F)=>!this.introspectableIn||this.introspectableIn.traverseAllows(T,F);traverseApply=(T,F)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(T,F);F.queueMorphs(this.morphs)};hasEqualMorphs(T){return d0(this.morphs,T.morphs,{isEqual:(F,_)=>F===_||q(F,"root")&&q(_,"root")&&F.equals(_)})}}var B2={implementation:Z9,Node:t8},X9=(T,F)=>`The intersection of distinct morphs at a single path is indeterminate:
32
32
  Left: ${T}
33
- Right: ${o}`;var P8=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>uA(T)??ko(T)},dateAllowsInvalid:{}},normalize:(T)=>{let o=typeof T==="string"?{proto:PF[T]}:typeof T==="function"?UT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:PF[T.proto]}:T;if(typeof o.proto!=="function")G(Ry.writeInvalidSchemaMessage(o.proto));if(yA(o,"dateAllowsInvalid")&&o.proto!==Date)G(Ry.writeBadInvalidDateMessage(o.proto));return o},applyConfig:(T,o)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&o.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?u_[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":nA(T)},intersections:{proto:(T,o)=>T.proto===Date&&o.proto===Date?T.dateAllowsInvalid?o:T:bf(T.proto,o.proto)?T:bf(o.proto,T.proto)?o:k.init("proto",T,o),domain:(T,o)=>o.domain==="object"?T:k.init("domain",K.intrinsic.object.internal,o)}});class s0 extends hF{builtinName=uA(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(T)=>T instanceof Date&&T.toString()!=="Invalid Date":(T)=>T instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(T){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return T.fallback.date?.({code:"date",base:{}})??T.fallback.proto({code:"proto",base:{},proto:this.proto});default:return T.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 Ry={implementation:P8,Node:s0,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${tT(T)})`};var m8=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,o)=>{let F=[];for(let A of T){let y=P(A,"root")?A.branches:o.$.parseSchema(A).branches;for(let S of y)if(S.hasKind("morph")){let f=F.findIndex(($)=>$.hasKind("morph")&&$.hasEqualMorphs(S));if(f===-1)F.push(S);else{let $=F[f];F[f]=o.$.node("morph",{...$.inner,in:$.in.rawOr(S.in)})}}else F.push(S)}if(!o.def.ordered)F.sort((A,y)=>A.hash<y.hash?-1:1);return F}}},normalize:(T)=>HT(T)?{branches:T}:T,reduce:(T,o)=>{let F=l8(T);if(F.length===1)return F[0];if(F.length===T.branches.length)return;return o.node("union",{...T,branches:F},{prereduced:!0})},defaults:{description:(T)=>T.distribute((o)=>o.description,ZA),expected:(T)=>{let o=q_(T.errors,"propString"),F=Object.entries(o).map(([A,y])=>{let S=[];for(let _ of y)so(S,_.expected);let f=ZA(S),$=y.every((_)=>_.actual===y[0].actual)?y[0].actual:r(y[0].data);return`${A&&`${A} `}must be ${f}${$&&` (was ${$})`}`});return ZA(F)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,o,F)=>{if(T.isNever!==o.isNever)return k.init("presence",T,o);let A;if(T.ordered){if(o.ordered)G(a8(T.expression,o.expression));if(A=Y$(o.branches,T.branches,F),A instanceof k)A.invert()}else A=Y$(T.branches,o.branches,F);if(A instanceof k)return A;return F.$.parseSchema(T.ordered||o.ordered?{branches:A,ordered:!0}:{branches:A})},...eo("union",(T,o,F)=>{let A=Y$(T.branches,[o],F);if(A instanceof k)return A;if(A.length===1)return A[0];return F.$.parseSchema(T.ordered?{branches:A,ordered:!0}:{branches:A})})}});class T1 extends No{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],o=-1;for(let F of this.branches){if(F.hasKind("unit")&&F.domain==="boolean"){if(o===-1)o=T.length,T.push(F);else T[o]=K.intrinsic.boolean;continue}T.push(F)}return T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?i8(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,r8);createBranchedOptimisticRootApply(){return(T,o)=>{let F=this.traverseOptimistic(T);if(F!==Vo)return F;let A=new go(T,this.$.resolvedConfig);return this.traverseApply(T,A),A.finalize(o)}}get shallowMorphs(){return this.branches.reduce((T,o)=>so(T,o.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((T)=>T.defaultShortDescription,ZA)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(K.intrinsic.boolean))return{type:"boolean"};let o=this.branchGroups.map((F)=>F.toJsonSchemaRecurse(T));if(o.every((F)=>Object.keys(F).length===1&&yA(F,"const")))return{enum:o.map((F)=>F.const)};return{anyOf:o}}traverseAllows=(T,o)=>this.branches.some((F)=>F.traverseAllows(T,o));traverseApply=(T,o)=>{let F=[];for(let A=0;A<this.branches.length;A++){if(o.pushBranch(),this.branches[A].traverseApply(T,o),!o.hasError()){if(this.branches[A].includesTransform)return o.queuedMorphs.push(...o.popBranch().queuedMorphs);return o.popBranch()}F.push(o.popBranch().error)}o.errorFromNodeContext({code:"union",errors:F,meta:this.meta})};traverseOptimistic=(T)=>{for(let o=0;o<this.branches.length;o++){let F=this.branches[o];if(F.traverseAllows(T)){if(F.contextFreeMorph)return F.contextFreeMorph(T);return T}}return Vo};compile(T){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(T);let o=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")o=`typeof ${o} === "object" ? ${o} === null ? "null" : "object" : typeof ${o} === "function" ? "object" : typeof ${o}`;let F=this.discriminant.cases,A=Object.keys(F),{optimistic:y}=T;if(T.optimistic=!1,T.block(`switch(${o})`,()=>{for(let J in F){let R=F[J],O=J==="default"?J:`case ${J}`;T.line(`${O}: return ${R===!0?y?T.data:R:y?`${T.invoke(R)} ? ${R.contextFreeMorph?`${BT(R.contextFreeMorph)}(${T.data})`:T.data} : "${Vo}"`:T.invoke(R)}`)}return T}),T.traversalKind==="Allows"){T.return(y?`"${Vo}"`:!1);return}let S=ZA(this.discriminant.kind==="domain"?A.map((J)=>{let R=J.slice(1,-1);return R==="function"?Zo.object:Zo[R]}):A),f=this.discriminant.path.map((J)=>typeof J==="symbol"?BT(J):JSON.stringify(J)),$=JSON.stringify(S),_=this.discriminant.kind==="domain"?`${u8}[${o}]`:`${c8}(${o})`;T.line(`ctx.errorFromNodeContext({
33
+ Right: ${F}`;var A9=c({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>E_(T)??E0(T)},dateAllowsInvalid:{}},normalize:(T)=>{let F=typeof T==="string"?{proto:KF[T]}:typeof T==="function"?OT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:KF[T.proto]}:T;if(typeof F.proto!=="function")z(x_.writeInvalidSchemaMessage(F.proto));if(PF(F,"dateAllowsInvalid")&&F.proto!==Date)z(x_.writeBadInvalidDateMessage(F.proto));return F},applyConfig:(T,F)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&F.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?uJ[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":z_(T)},intersections:{proto:(T,F)=>T.proto===Date&&F.proto===Date?T.dateAllowsInvalid?F:T:a1(T.proto,F.proto)?T:a1(F.proto,T.proto)?F:I.init("proto",T,F),domain:(T,F)=>F.domain==="object"?T:I.init("domain",w.intrinsic.object.internal,F)}});class n8 extends LF{builtinName=E_(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(T)=>T instanceof Date&&T.toString()!=="Invalid Date":(T)=>T instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(T){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return T.fallback.date?.({code:"date",base:{}})??T.fallback.proto({code:"proto",base:{},proto:this.proto});default:return T.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 x_={implementation:A9,Node:n8,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${fT(T)})`};var G9=c({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,F)=>{let _=[];for(let W of T){let J=q(W,"root")?W.branches:F.$.parseSchema(W).branches;for(let $ of J)if($.hasKind("morph")){let Y=_.findIndex((Z)=>Z.hasKind("morph")&&Z.hasEqualMorphs($));if(Y===-1)_.push($);else{let Z=_[Y];_[Y]=F.$.node("morph",{...Z.inner,in:Z.in.rawOr($.in)})}}else _.push($)}if(!F.def.ordered)_.sort((W,J)=>W.hash<J.hash?-1:1);return _}}},normalize:(T)=>YT(T)?{branches:T}:T,reduce:(T,F)=>{let _=K9(T);if(_.length===1)return _[0];if(_.length===T.branches.length)return;return F.node("union",{...T,branches:_},{prereduced:!0})},defaults:{description:(T)=>T.distribute((F)=>F.description,lF),expected:(T)=>{let F=vJ(T.errors,"propString"),_=Object.entries(F).map(([W,J])=>{let $=[];for(let A of J)x0($,A.expected);let Y=lF($),Z=J.every((A)=>A.actual===J[0].actual)?J[0].actual:o(J[0].data);return`${W&&`${W} `}must be ${Y}${Z&&` (was ${Z})`}`});return lF(_)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,F,_)=>{if(T.isNever!==F.isNever)return I.init("presence",T,F);let W;if(T.ordered){if(F.ordered)z(D9(T.expression,F.expression));if(W=f2(F.branches,T.branches,_),W instanceof I)W.invert()}else W=f2(T.branches,F.branches,_);if(W instanceof I)return W;return _.$.parseSchema(T.ordered||F.ordered?{branches:W,ordered:!0}:{branches:W})},...h0("union",(T,F,_)=>{let W=f2(T.branches,[F],_);if(W instanceof I)return W;if(W.length===1)return W[0];return _.$.parseSchema(T.ordered?{branches:W,ordered:!0}:{branches:W})})}});class a8 extends w0{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],F=-1;for(let _ of this.branches){if(_.hasKind("unit")&&_.domain==="boolean"){if(F===-1)F=T.length,T.push(_);else T[F]=w.intrinsic.boolean;continue}T.push(_)}return T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?E9(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,w9);createBranchedOptimisticRootApply(){return(T,F)=>{let _=this.traverseOptimistic(T);if(_!==H0)return _;let W=new B0(T,this.$.resolvedConfig);return this.traverseApply(T,W),W.finalize(F)}}get shallowMorphs(){return this.branches.reduce((T,F)=>x0(T,F.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((T)=>T.defaultShortDescription,lF)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(w.intrinsic.boolean))return{type:"boolean"};let F=this.branchGroups.map((_)=>_.toJsonSchemaRecurse(T));if(F.every((_)=>Object.keys(_).length===1&&PF(_,"const")))return{enum:F.map((_)=>_.const)};return{anyOf:F}}traverseAllows=(T,F)=>this.branches.some((_)=>_.traverseAllows(T,F));traverseApply=(T,F)=>{let _=[];for(let W=0;W<this.branches.length;W++){if(F.pushBranch(),this.branches[W].traverseApply(T,F),!F.hasError()){if(this.branches[W].includesTransform)return F.queuedMorphs.push(...F.popBranch().queuedMorphs);return F.popBranch()}_.push(F.popBranch().error)}F.errorFromNodeContext({code:"union",errors:_,meta:this.meta})};traverseOptimistic=(T)=>{for(let F=0;F<this.branches.length;F++){let _=this.branches[F];if(_.traverseAllows(T)){if(_.contextFreeMorph)return _.contextFreeMorph(T);return T}}return H0};compile(T){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(T);let F=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")F=`typeof ${F} === "object" ? ${F} === null ? "null" : "object" : typeof ${F} === "function" ? "object" : typeof ${F}`;let _=this.discriminant.cases,W=Object.keys(_),{optimistic:J}=T;if(T.optimistic=!1,T.block(`switch(${F})`,()=>{for(let X in _){let O=_[X],M=X==="default"?X:`case ${X}`;T.line(`${M}: return ${O===!0?J?T.data:O:J?`${T.invoke(O)} ? ${O.contextFreeMorph?`${VT(O.contextFreeMorph)}(${T.data})`:T.data} : "${H0}"`:T.invoke(O)}`)}return T}),T.traversalKind==="Allows"){T.return(J?`"${H0}"`:!1);return}let $=lF(this.discriminant.kind==="domain"?W.map((X)=>{let O=X.slice(1,-1);return O==="function"?T0.object:T0[O]}):W),Y=this.discriminant.path.map((X)=>typeof X==="symbol"?VT(X):JSON.stringify(X)),Z=JSON.stringify($),A=this.discriminant.kind==="domain"?`${Q9}[${F}]`:`${z9}(${F})`;T.line(`ctx.errorFromNodeContext({
34
34
  code: "predicate",
35
- expected: ${$},
36
- actual: ${_},
37
- relativePath: [${f}],
35
+ expected: ${Z},
36
+ actual: ${A},
37
+ relativePath: [${Y}],
38
38
  meta: ${this.compiledMeta}
39
- })`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let o of this.branches)T.line("ctx.pushBranch()").line(T.invoke(o)).if("!ctx.hasError()",()=>T.return(o.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:o}=T;T.optimistic=!1;for(let F of this.branches)T.if(`${T.invoke(F)}`,()=>T.return(o?F.contextFreeMorph?`${BT(F.contextFreeMorph)}(${T.data})`:T.data:!0));T.return(o?`"${Vo}"`:!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=d(this.unitBranches,(S,f)=>[`${f.in.serializedValue}`,f.hasKind("morph")?f:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:y}}let T=[];for(let y=0;y<this.branches.length-1;y++){let S=this.branches[y];for(let f=y+1;f<this.branches.length;f++){let $=this.branches[f],_=wo(S.in,$.in,S.$);if(!(_ instanceof k))continue;for(let J of _){if(!J.kind||J.optional)continue;let R,O;if(J.kind==="domain"){let{l:H,r:Q}=J;R=`"${typeof H==="string"?H:H.domain}"`,O=`"${typeof Q==="string"?Q:Q.domain}"`}else if(J.kind==="unit")R=J.l.serializedValue,O=J.r.serializedValue;else continue;let Y=T.find((H)=>fF(H.path,J.path)&&H.kind===J.kind);if(!Y)T.push({kind:J.kind,cases:{[R]:{branchIndices:[y],condition:J.l},[O]:{branchIndices:[f],condition:J.r}},path:J.path});else{if(Y.cases[R])Y.cases[R].branchIndices=so(Y.cases[R].branchIndices,y);else Y.cases[R]??={branchIndices:[y],condition:J.l};if(Y.cases[O])Y.cases[O].branchIndices=so(Y.cases[O].branchIndices,f);else Y.cases[O]??={branchIndices:[f],condition:J.r}}}}}let o=this.ordered?g8(T,this.branches):T;if(!o.length)return null;let F=t8(o,this),A={};for(let y in F.best.cases){let S=h8(F,y);if(S===null){A[y]=!0;continue}if(S.length===this.branches.length)return null;if(this.ordered)S.sort((_,J)=>_.originalIndex-J.originalIndex);let f=S.map((_)=>_.branch),$=f.length===1?f[0]:this.$.node("union",this.ordered?{branches:f,ordered:!0}:f);Object.assign(this.referencesById,$.referencesById),A[y]=$}if(F.defaultEntries.length){let y=F.defaultEntries.map((S)=>S.branch);A.default=this.$.node("union",this.ordered?{branches:y,ordered:!0}:y,{prereduced:!0}),Object.assign(this.referencesById,A.default.referencesById)}return Object.assign(F.location,{cases:A})}}var t8=(T,o)=>{let F=T.sort((S,f)=>Object.keys(f.cases).length-Object.keys(S.cases).length)[0],A={kind:F.kind,path:F.path,optionallyChainedPropString:o1(F.path)},y=o.branches.map((S,f)=>({originalIndex:f,branch:S}));return{best:F,location:A,defaultEntries:y,node:o}},h8=(T,o)=>{let F=T.best.cases[o],A=n8(F.condition,T.location.path,T.node.$),y=[],S=[];for(let f=0;f<T.defaultEntries.length;f++){let $=T.defaultEntries[f];if(F.branchIndices.includes($.originalIndex)){let _=a0(T.node.branches[$.originalIndex],T.location);if(_===null)y=null;else y?.push({originalIndex:$.originalIndex,branch:_})}else if($.branch.hasKind("alias")&&A.hasKind("domain")&&A.domain==="object")y?.push($);else{if($.branch.in.overlaps(A)){let _=a0($.branch,T.location);y?.push({originalIndex:$.originalIndex,branch:_})}S.push($)}}return T.defaultEntries=S,y},g8=(T,o)=>{return T.filter((A)=>{let y=Object.values(A.cases).map((S)=>S.branchIndices);for(let S=0;S<y.length-1;S++){let f=y[S];for(let $=S+1;$<y.length;$++){let _=y[$];for(let J of f)for(let R of _)if(J>R){if(o[J].overlaps(o[R]))return!1}}}return!0})},n8=(T,o,F)=>{let A=T==="undefined"?F.node("unit",{unit:void 0}):T==="null"?F.node("unit",{unit:null}):T==="boolean"?F.units([!0,!1]):T;for(let y=o.length-1;y>=0;y--){let S=o[y];A=F.node("intersection",typeof S==="number"?{proto:"Array",sequence:[...x_(S).map((f)=>({})),A]}:{domain:"object",required:[{key:S,value:A}]})}return A},o1=(T)=>T.reduce((o,F)=>o+gf(F,!0),"data"),u8=BT(v_),c8=BT(r),Z$={implementation:m8,Node:T1},i8=(T)=>({kind:T.kind,path:T.path.map((o)=>typeof o==="string"?o:_F(o)),cases:d(T.cases,(o,F)=>[o,F===!0?F:F.hasKind("union")&&F.discriminantJson?F.discriminantJson:F.json])}),d8={delimiter:" | ",finalDelimiter:" | "},r8=(T)=>ZA(T,d8),ZA=(T,o)=>{let F=o?.delimiter??", ",A=o?.finalDelimiter??" or ";if(T.length===0)return"never";if(T.length===1)return T[0];if(T.length===2&&T[0]==="false"&&T[1]==="true"||T[0]==="true"&&T[1]==="false")return"boolean";let y={},S=T.filter(($)=>y[$]?!1:y[$]=!0),f=S.pop();return`${S.join(F)}${S.length?A:""}${f}`},Y$=(T,o,F)=>{let A=o.map(()=>[]);for(let S=0;S<T.length;S++){let f={};for(let $=0;$<o.length;$++){if(A[$]===null)continue;if(T[S].equals(o[$])){A[$]=null,f={};break}let _=zT(T[S],o[$],F);if(_ instanceof k)continue;if(_.equals(T[S])){A[$].push(T[S]),f={};break}if(_.equals(o[$]))A[$]=null;else f[$]=_}for(let $ in f)A[$][S]=f[$]}let y=A.flatMap((S,f)=>S?.flatMap(($)=>$.branches)??o[f]);return y.length===0?k.init("union",T,o):y},l8=({branches:T,ordered:o})=>{if(T.length<2)return T;let F=T.map(()=>!0);for(let A=0;A<T.length;A++)for(let y=A+1;y<T.length&&F[A]&&F[y];y++){if(T[A].equals(T[y])){F[y]=!1;continue}let S=wo(T[A].in,T[y].in,T[0].$);if(S instanceof k)continue;if(!o)s8(T[A],T[y]);if(S.equals(T[A].in))F[A]=!!o;else if(S.equals(T[y].in))F[y]=!1}return T.filter((A,y)=>F[y])},s8=(T,o)=>{if(!T.includesTransform&&!o.includesTransform)return;if(!fF(T.shallowMorphs,o.shallowMorphs))G(e0(T.expression,o.expression));if(!fF(T.flatMorphs,o.flatMorphs,{isEqual:(F,A)=>F.propString===A.propString&&(F.node.hasKind("morph")&&A.node.hasKind("morph")?F.node.hasEqualMorphs(A.node):F.node.hasKind("intersection")&&A.node.hasKind("intersection")?F.node.structure?.structuralMorphRef===A.node.structure?.structuralMorphRef:!1)}))G(e0(T.expression,o.expression))},a0=(T,o)=>T.transform((F,A)=>{if(F==="domain"||F==="unit")return null;return A},{shouldTransform:(F,A)=>{let y=o1(A.path);if(!o.optionallyChainedPropString.startsWith(y))return!1;if(F.hasKind("domain")&&F.domain==="object")return!0;if((F.hasKind("domain")||o.kind==="unit")&&y===o.optionallyChainedPropString)return!0;return F.children.length!==0&&F.kind!=="index"}}),e0=(T,o)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
39
+ })`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let F of this.branches)T.line("ctx.pushBranch()").line(T.invoke(F)).if("!ctx.hasError()",()=>T.return(F.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:F}=T;T.optimistic=!1;for(let _ of this.branches)T.if(`${T.invoke(_)}`,()=>T.return(F?_.contextFreeMorph?`${VT(_.contextFreeMorph)}(${T.data})`:T.data:!0));T.return(F?`"${H0}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let J=m(this.unitBranches,($,Y)=>[`${Y.in.serializedValue}`,Y.hasKind("morph")?Y:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:J}}let T=[];for(let J=0;J<this.branches.length-1;J++){let $=this.branches[J];for(let Y=J+1;Y<this.branches.length;Y++){let Z=this.branches[Y],A=W0($.in,Z.in,$.$);if(!(A instanceof I))continue;for(let X of A){if(!X.kind||X.optional)continue;let O,M;if(X.kind==="domain"){let{l:K,r:j}=X;O=`"${typeof K==="string"?K:K.domain}"`,M=`"${typeof j==="string"?j:j.domain}"`}else if(X.kind==="unit")O=X.l.serializedValue,M=X.r.serializedValue;else continue;let E=T.find((K)=>d0(K.path,X.path)&&K.kind===X.kind);if(!E)T.push({kind:X.kind,cases:{[O]:{branchIndices:[J],condition:X.l},[M]:{branchIndices:[Y],condition:X.r}},path:X.path});else{if(E.cases[O])E.cases[O].branchIndices=x0(E.cases[O].branchIndices,J);else E.cases[O]??={branchIndices:[J],condition:X.l};if(E.cases[M])E.cases[M].branchIndices=x0(E.cases[M].branchIndices,Y);else E.cases[M]??={branchIndices:[Y],condition:X.r}}}}}let F=this.ordered?U9(T,this.branches):T;if(!F.length)return null;let _=H9(F,this),W={};for(let J in _.best.cases){let $=O9(_,J);if($===null){W[J]=!0;continue}if($.length===this.branches.length)return null;if(this.ordered)$.sort((A,X)=>A.originalIndex-X.originalIndex);let Y=$.map((A)=>A.branch),Z=Y.length===1?Y[0]:this.$.node("union",this.ordered?{branches:Y,ordered:!0}:Y);Object.assign(this.referencesById,Z.referencesById),W[J]=Z}if(_.defaultEntries.length){let J=_.defaultEntries.map(($)=>$.branch);W.default=this.$.node("union",this.ordered?{branches:J,ordered:!0}:J,{prereduced:!0}),Object.assign(this.referencesById,W.default.referencesById)}return Object.assign(_.location,{cases:W})}}var H9=(T,F)=>{let _=T.sort(($,Y)=>Object.keys(Y.cases).length-Object.keys($.cases).length)[0],W={kind:_.kind,path:_.path,optionallyChainedPropString:e8(_.path)},J=F.branches.map(($,Y)=>({originalIndex:Y,branch:$}));return{best:_,location:W,defaultEntries:J,node:F}},O9=(T,F)=>{let _=T.best.cases[F],W=M9(_.condition,T.location.path,T.node.$),J=[],$=[];for(let Y=0;Y<T.defaultEntries.length;Y++){let Z=T.defaultEntries[Y];if(_.branchIndices.includes(Z.originalIndex)){let A=r8(T.node.branches[Z.originalIndex],T.location);if(A===null)J=null;else J?.push({originalIndex:Z.originalIndex,branch:A})}else if(Z.branch.hasKind("alias")&&W.hasKind("domain")&&W.domain==="object")J?.push(Z);else{if(Z.branch.in.overlaps(W)){let A=r8(Z.branch,T.location);J?.push({originalIndex:Z.originalIndex,branch:A})}$.push(Z)}}return T.defaultEntries=$,J},U9=(T,F)=>{return T.filter((W)=>{let J=Object.values(W.cases).map(($)=>$.branchIndices);for(let $=0;$<J.length-1;$++){let Y=J[$];for(let Z=$+1;Z<J.length;Z++){let A=J[Z];for(let X of Y)for(let O of A)if(X>O){if(F[X].overlaps(F[O]))return!1}}}return!0})},M9=(T,F,_)=>{let W=T==="undefined"?_.node("unit",{unit:void 0}):T==="null"?_.node("unit",{unit:null}):T==="boolean"?_.units([!0,!1]):T;for(let J=F.length-1;J>=0;J--){let $=F[J];W=_.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...yJ($).map((Y)=>({})),W]}:{domain:"object",required:[{key:$,value:W}]})}return W},e8=(T)=>T.reduce((F,_)=>F+$2(_,!0),"data"),Q9=VT(xJ),z9=VT(o),q2={implementation:G9,Node:a8},E9=(T)=>({kind:T.kind,path:T.path.map((F)=>typeof F==="string"?F:t0(F)),cases:m(T.cases,(F,_)=>[F,_===!0?_:_.hasKind("union")&&_.discriminantJson?_.discriminantJson:_.json])}),R9={delimiter:" | ",finalDelimiter:" | "},w9=(T)=>lF(T,R9),lF=(T,F)=>{let _=F?.delimiter??", ",W=F?.finalDelimiter??" or ";if(T.length===0)return"never";if(T.length===1)return T[0];if(T.length===2&&T[0]==="false"&&T[1]==="true"||T[0]==="true"&&T[1]==="false")return"boolean";let J={},$=T.filter((Z)=>J[Z]?!1:J[Z]=!0),Y=$.pop();return`${$.join(_)}${$.length?W:""}${Y}`},f2=(T,F,_)=>{let W=F.map(()=>[]);for(let $=0;$<T.length;$++){let Y={};for(let Z=0;Z<F.length;Z++){if(W[Z]===null)continue;if(T[$].equals(F[Z])){W[Z]=null,Y={};break}let A=UT(T[$],F[Z],_);if(A instanceof I)continue;if(A.equals(T[$])){W[Z].push(T[$]),Y={};break}if(A.equals(F[Z]))W[Z]=null;else Y[Z]=A}for(let Z in Y)W[Z][$]=Y[Z]}let J=W.flatMap(($,Y)=>$?.flatMap((Z)=>Z.branches)??F[Y]);return J.length===0?I.init("union",T,F):J},K9=({branches:T,ordered:F})=>{if(T.length<2)return T;let _=T.map(()=>!0);for(let W=0;W<T.length;W++)for(let J=W+1;J<T.length&&_[W]&&_[J];J++){if(T[W].equals(T[J])){_[J]=!1;continue}let $=W0(T[W].in,T[J].in,T[0].$);if($ instanceof I)continue;if(!F)V9(T[W],T[J]);if($.equals(T[W].in))_[W]=!!F;else if($.equals(T[J].in))_[J]=!1}return T.filter((W,J)=>_[J])},V9=(T,F)=>{if(!T.includesTransform&&!F.includesTransform)return;if(!d0(T.shallowMorphs,F.shallowMorphs))z(s8(T.expression,F.expression));if(!d0(T.flatMorphs,F.flatMorphs,{isEqual:(_,W)=>_.propString===W.propString&&(_.node.hasKind("morph")&&W.node.hasKind("morph")?_.node.hasEqualMorphs(W.node):_.node.hasKind("intersection")&&W.node.hasKind("intersection")?_.node.structure?.structuralMorphRef===W.node.structure?.structuralMorphRef:!1)}))z(s8(T.expression,F.expression))},r8=(T,F)=>T.transform((_,W)=>{if(_==="domain"||_==="unit")return null;return W},{shouldTransform:(_,W)=>{let J=e8(W.path);if(!F.optionallyChainedPropString.startsWith(J))return!1;if(_.hasKind("domain")&&_.domain==="object")return!0;if((_.hasKind("domain")||F.kind==="unit")&&J===F.optionallyChainedPropString)return!0;return _.children.length!==0&&_.kind!=="index"}}),s8=(T,F)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
40
  Left: ${T}
41
- Right: ${o}`,a8=(T,o)=>`The intersection of two ordered unions is indeterminate:
41
+ Right: ${F}`,D9=(T,F)=>`The intersection of two ordered unions is indeterminate:
42
42
  Left: ${T}
43
- Right: ${o}`;var e8=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():ko(T)}},normalize:(T)=>T,defaults:{description:(T)=>r(T.unit),problem:({expected:T,actual:o})=>`${T===o?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${o})`}`},intersections:{unit:(T,o)=>k.init("unit",T,o),...eo("unit",(T,o)=>{if(o.allows(T.unit))return T;let F=o.hasKind("intersection")?o.basis:o;if(F){let A=F.hasKind("domain")?F:K.intrinsic.object;if(T.domain!==A.domain){let y=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:K.intrinsic[T.domain];return k.init("domain",y,A)}}return k.init("assignability",T,o.hasKind("intersection")?o.children.find((A)=>!A.allows(T.unit)):o)})}});class A1 extends hF{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=F1(this.unit,this.serializedValue);compiledNegation=F1(this.unit,this.serializedValue,"negated");expression=r(this.unit);domain=tT(this.unit);get defaultShortDescription(){return this.domain==="object"?Zo.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:K.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var H$={implementation:e8,Node:A1},F1=(T,o,F)=>{if(T instanceof Date){let A=`data instanceof Date && data.toISOString() === ${o}`;return F?`!(${A})`:A}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${o}`};var TY=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,o)=>{let F=o.$.parseSchema(T);if(!F.extends(K.intrinsic.key))return G(FY(F.expression));let A=F.branches.filter((y)=>y.hasKind("unit"));if(A.length)return G(oY(A.map((y)=>r(y.unit))));return F}},value:{child:!0,parse:(T,o)=>o.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,o,F)=>{if(T.signature.equals(o.signature)){let A=zT(T.value,o.value,F),y=A instanceof k?K.intrinsic.never.internal:A;return F.$.node("index",{signature:T.signature,value:y})}if(T.signature.extends(o.signature)&&T.value.subsumes(o.value))return o;if(o.signature.extends(T.signature)&&o.value.subsumes(T.value))return T;return null}}});class y1 extends Bo{impliedBasis=K.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=yT(this.value.flatRefs.map((T)=>no([this.signature,...T.path],T.node)),no([this.signature],this.value));traverseAllows=(T,o)=>vF(T).every((F)=>{if(this.signature.traverseAllows(F[0],o))return Go(F[0],()=>this.value.traverseAllows(F[1],o),o);return!0});traverseApply=(T,o)=>{for(let F of vF(T))if(this.signature.traverseAllows(F[0],o))Go(F[0],()=>this.value.traverseApply(F[1],o),o)};_transform(T,o){o.path.push(this.signature);let F=super._transform(T,o);return o.path.pop(),F}compile(){}}var G$={implementation:TY,Node:y1},oY=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,FY=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var AY=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,o)=>o.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:yy,optional:yy}});class S1 extends Sy{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=VF(this.errorContext)}var w$={implementation:AY,Node:S1};var yY=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}},optionals:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((o)=>o[0]),parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>{let A=o.$.parseSchema(F[0]);return $y(A,F[1],null),[A,F[1]]})},serialize:(T)=>T.map((o)=>[o[0].collapsibleJson,ko(o[1])])},variadic:{child:!0,parse:(T,o)=>o.$.parseSchema(T,o)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return G(JY);if(T.optionals?.length||T.defaultables?.length)return G(K$)}if(T.minVariadicLength&&!T.variadic)return G("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,o)=>{let F=T.minVariadicLength??0,A=T.prefix?.slice()??[],y=T.defaultables?.slice()??[],S=T.optionals?.slice()??[],f=T.postfix?.slice()??[];if(T.variadic){while(S.at(-1)?.equals(T.variadic))S.pop();if(S.length===0&&y.length===0)while(A.at(-1)?.equals(T.variadic))A.pop(),F++;while(f[0]?.equals(T.variadic))f.shift(),F++}else if(S.length===0&&y.length===0)A.push(...f.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==A.length)return o.node("sequence",{...T,prefix:A,defaultables:y,optionals:S,postfix:f,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${r(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,o,F)=>{let A=Wy({l:T.tuple,r:o.tuple,disjoint:new k,result:[],fixedVariants:[],ctx:F}),y=A.disjoint.length===0?[A,...A.fixedVariants]:A.fixedVariants;return y.length===0?A.disjoint:y.length===1?F.$.node("sequence",f1(y[0].result)):F.$.node("union",y.map((S)=>({proto:Array,sequence:f1(S.result)})))}}});class $1 extends Bo{impliedBasis=K.intrinsic.Array.internal;tuple=$Y(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((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=SF(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return df(this.flatRefs,this.prevariadic.flatMap((T,o)=>yT(T.node.flatRefs.map((F)=>no([`${o}`,...F.path],F.node)),no([`${o}`],T.node)))),df(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>yT(T.flatRefs.map((o)=>no([K.intrinsic.nonNegativeIntegerString.internal,...o.path],o.node)),no([K.intrinsic.nonNegativeIntegerString.internal],T)))),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=fY(this);defaultValueMorphsReference=this.defaultValueMorphs.length?BT(this.defaultValueMorphs):void 0;elementAtIndex(T,o){if(o<this.prevariadic.length)return this.tuple[o];let F=T.length-this.postfixLength;if(o>=F)return{kind:"postfix",node:this.postfix[o-F]};return{kind:"variadic",node:this.variadic??$T(`Unexpected attempt to access index ${o} on ${this}`)}}traverseAllows=(T,o)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],o))return!1;return!0};traverseApply=(T,o)=>{let F=0;for(;F<T.length;F++)Go(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],o),o)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[o,F]of this.prefix.entries())T.traverseKey(`${o}`,`data[${o}]`,F);for(let[o,F]of this.defaultablesAndOptionals.entries()){let A=`${o+this.prefixLength}`;T.if(`${A} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(A,`data[${A}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[o,F]of this.postfix.entries()){let A=`firstPostfixIndex + ${o}`;T.traverseKey(A,`data[${A}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,o){o.path.push(K.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,o);return o.path.pop(),F}expression=this.description;reduceJsonSchema(T,o){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let A=F.node.toJsonSchemaRecurse(o);if(F.kind==="defaultables"){let y=typeof F.default==="function"?F.default():F.default;A.default=K.intrinsic.jsonData.allows(y)?y:o.fallback.defaultValue({code:"defaultValue",base:A,value:y})}return A});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(o)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let A=this.postfix.map((y)=>y.toJsonSchemaRecurse(o));T=o.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:A})}}else T.items=!1,delete T.maxItems;return T}}var SY={},fY=(T)=>{if(!T.defaultables)return[];let o=[],F="[",A=T.prefixLength+T.defaultablesLength-1;for(let y=T.prefixLength;y<=A;y++){let[S,f]=T.defaultables[y-T.prefixLength];o.push(M$(y,S,f)),F+=`${y}: ${S.id} = ${ko(f)}, `}return F+="]",SY[F]??=o},E$={implementation:yY,Node:$1},$Y=(T)=>{let o=[];if(T.prefix)for(let F of T.prefix)o.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,A]of T.defaultables)o.push({kind:"defaultables",node:F,default:A});if(T.optionals)for(let F of T.optionals)o.push({kind:"optionals",node:F});if(T.variadic)o.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)o.push({kind:"postfix",node:F});return o},f1=(T)=>T.reduce((o,F)=>{if(F.kind==="variadic")o.variadic=F.node;else if(F.kind==="defaultables")o.defaultables=yT(o.defaultables,[[F.node,F.default]]);else o[F.kind]=yT(o[F.kind],F.node);return o},{}),K$="A postfix required element cannot follow an optional or defaultable element",JY="A postfix element requires a variadic element",Wy=(T)=>{let[o,...F]=T.l,[A,...y]=T.r;if(!o||!A)return T;let S=F.at(-1)?.kind==="postfix",f=y.at(-1)?.kind==="postfix",$=o.kind==="prefix"||A.kind==="prefix"?"prefix":o.kind==="postfix"||A.kind==="postfix"?"postfix":o.kind==="variadic"&&A.kind==="variadic"?"variadic":S||f?"prefix":o.kind==="defaultables"||A.kind==="defaultables"?"defaultables":"optionals";if(o.kind==="prefix"&&A.kind==="variadic"&&f){let O=Wy({...T,fixedVariants:[],r:y.map((Y)=>({...Y,kind:"prefix"}))});if(O.disjoint.length===0)T.fixedVariants.push(O)}else if(A.kind==="prefix"&&o.kind==="variadic"&&S){let O=Wy({...T,fixedVariants:[],l:F.map((Y)=>({...Y,kind:"prefix"}))});if(O.disjoint.length===0)T.fixedVariants.push(O)}let _=zT(o.node,A.node,T.ctx);if(_ instanceof k)if($==="prefix"||$==="postfix")T.disjoint.push(..._.withPrefixKey($==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:$,node:K.intrinsic.never.internal}];else if($==="optionals"||$==="defaultables")return T;else return Wy({...T,fixedVariants:[],l:F.map((O)=>({...O,kind:"prefix"})),r:F.map((O)=>({...O,kind:"prefix"}))});else if($==="defaultables"){if(o.kind==="defaultables"&&A.kind==="defaultables"&&o.default!==A.default)G(W$(o.default,A.default));T.result=[...T.result,{kind:$,node:_,default:o.kind==="defaultables"?o.default:A.kind==="defaultables"?A.default:$T(`Unexpected defaultable intersection from ${o.kind} and ${A.kind} elements.`)}]}else T.result=[...T.result,{kind:$,node:_}];let J=T.l.length,R=T.r.length;if(o.kind!=="variadic"||J>=R&&(A.kind==="variadic"||R===1))T.l=F;if(A.kind!=="variadic"||R>=J&&(o.kind==="variadic"||J===1))T.r=y;return Wy(T)};var R1=(T)=>(o)=>{if(o.props.length||o.index){let F=o.index?.map((y)=>y[T])??[];for(let y of o.props)F.push(y[T]);if(o.undeclared)F.push(`+ (undeclared): ${o.undeclared}`);let A=`{ ${F.join(", ")} }`;return o.sequence?`${A} & ${o.sequence.description}`:A}return o.sequence?.description??"{}"},_Y=R1("description"),RY=R1("expression"),J1=(T,o,F)=>{let A=T.required?"required":"optional";if(!o.signature.allows(T.key))return null;let y=wo(T.value,o.value,F);if(y instanceof k)return A==="optional"?F.node("optional",{key:T.key,value:K.intrinsic.never.internal}):y.withPrefixKey(T.key,T.kind);return null},WY=l({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,o)=>{if(!T.undeclared&&o.onUndeclaredKey!=="ignore")return{...T,undeclared:o.onUndeclaredKey};return T},keys:{required:{child:!0,parse:So("required"),reduceIo:(T,o,F)=>{o.required=yT(o.required,F.map((A)=>A[T]));return}},optional:{child:!0,parse:So("optional"),reduceIo:(T,o,F)=>{if(T==="in"){o.optional=F.map((A)=>A.in);return}for(let A of F)o[A.outProp.kind]=yT(o[A.outProp.kind],A.outProp.out)}},index:{child:!0,parse:So("index")},sequence:{child:!0,parse:So("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,o,F)=>{if(F!=="delete")return;if(T==="in")delete o.undeclared;else o.undeclared="reject"}}},defaults:{description:_Y},intersections:{structure:(T,o,F)=>{let A={...T.inner},y={...o.inner},S=new k;if(T.undeclared){let _=T.keyof();for(let J of o.requiredKeys)if(!_.allows(J))S.add("presence",K.intrinsic.never.internal,o.propsByKey[J].value,{path:[J]});if(y.optional)y.optional=y.optional.filter((J)=>_.allows(J.key));if(y.index)y.index=y.index.flatMap((J)=>{if(J.signature.extends(_))return J;let R=wo(_,J.signature,F.$);if(R instanceof k)return[];let O=MS(R,J.value,F.$);if(O.required)y.required=SF(y.required,O.required);if(O.optional)y.optional=SF(y.optional,O.optional);return O.index??[]})}if(o.undeclared){let _=o.keyof();for(let J of T.requiredKeys)if(!_.allows(J))S.add("presence",T.propsByKey[J].value,K.intrinsic.never.internal,{path:[J]});if(A.optional)A.optional=A.optional.filter((J)=>_.allows(J.key));if(A.index)A.index=A.index.flatMap((J)=>{if(J.signature.extends(_))return J;let R=wo(_,J.signature,F.$);if(R instanceof k)return[];let O=MS(R,J.value,F.$);if(O.required)A.required=SF(A.required,O.required);if(O.optional)A.optional=SF(A.optional,O.optional);return O.index??[]})}let f={};if(T.undeclared||o.undeclared)f.undeclared=T.undeclared==="reject"||o.undeclared==="reject"?"reject":"delete";let $=WA({kind:"structure",baseInner:f,l:MA(A),r:MA(y),roots:[],ctx:F});if($ instanceof k)S.push(...$);if(S.length)return S;return $}},reduce:(T,o)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,A=T.required??[],y=T.optional??[],S=[...y];for(let f of T.index){for(let $ of A){let _=J1($,f,o);if(_ instanceof k)return _}for(let[$,_]of y.entries()){let J=J1(_,f,o);if(J instanceof k)return J;if(J===null)continue;S[$]=J,F=!0}}if(F)return o.node("structure",{...T,optional:S},{prereduced:!0})}}});class W1 extends Bo{impliedBasis=K.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=SF(this.required,this.optional);propsByKey=d(this.props,(T,o)=>[o.key,o]);propsByKeyReference=BT(this.propsByKey);expression=RY(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:o}of this.index)T=T.concat(o.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((o,F)=>{let A=this.propsByKey[F.key];if(UT(F)){if(F.kind!=="required"&&F.kind!=="optional")return G(`Map result must have kind "required" or "optional" (was ${F.kind})`);return o[F.kind]=yT(o[F.kind],F),o}let y=F.kind??A?.kind??"required",S=d(F,(f,$)=>(f in fy.implementation.keys)?[f,$]:[]);return o[y]=yT(o[y],this.$.node(y,S)),o},{}))}assertHasKeys(T){let o=T.filter((F)=>!Jy(F,this.keyof()));if(o.length)return G(_1(this.expression,o))}get(T,...o){let F,A=!1,y=YY(T);if((typeof y==="string"||typeof y==="symbol")&&this.propsByKey[y])F=this.propsByKey[y].value,A=this.propsByKey[y].required;if(this.index){for(let f of this.index)if(Jy(y,f.signature))F=F?.and(f.value)??f.value}if(this.sequence&&Jy(y,K.intrinsic.nonNegativeIntegerString))if(P(y,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let f=Number.parseInt(y);if(f<this.sequence.prevariadic.length){let $=this.sequence.prevariadic[f].node;F=F?.and($)??$,A||=f<this.sequence.prefixLength}else if(this.sequence.variadic){let $=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and($)??$}}if(!F){if(this.sequence?.variadic&&P(y,"root")&&y.extends(K.intrinsic.number))return G(ZY(y.expression,this.sequence.expression));return G(_1(this.expression,[y]))}let S=F.get(...o);return A?S:S.or(K.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,...o}=this.inner;return this.$.node("structure",{...o,optional:this.props.map((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,...o}=this.inner;return this.$.node("structure",{...o,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let o=this.filterKeys("omit",[T.keyof()]);if(T.required)o.required=yT(o.required,T.required);if(T.optional)o.optional=yT(o.optional,T.optional);if(T.index)o.index=yT(o.index,T.index);if(T.sequence)o.sequence=T.sequence;if(T.undeclared)o.undeclared=T.undeclared;else delete o.undeclared;return this.$.node("structure",o)}filterKeys(T,o){let F=oS(this.inner),A=(y)=>{let S=o.some((f)=>Jy(y,f));return T==="pick"?S:!S};if(F.required)F.required=F.required.filter((y)=>A(y.key));if(F.optional)F.optional=F.optional.filter((y)=>A(y.key));if(F.index)F.index=F.index.filter((y)=>A(y.signature));return F}traverseAllows=(T,o)=>this._traverse("Allows",T,o);traverseApply=(T,o)=>this._traverse("Apply",T,o);_traverse=(T,o,F)=>{let A=F?.currentErrorCount??0;for(let y=0;y<this.props.length;y++)if(T==="Allows"){if(!this.props[y].traverseAllows(o,F))return!1}else if(this.props[y].traverseApply(o,F),F.failFast&&F.currentErrorCount>A)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(o,F))return!1}else if(this.sequence.traverseApply(o,F),F.failFast&&F.currentErrorCount>A)return!1}if(this.index||this.undeclared==="reject"){let y=Object.keys(o);y.push(...Object.getOwnPropertySymbols(o));for(let S=0;S<y.length;S++){let f=y[S];if(this.index){for(let $ of this.index)if($.signature.traverseAllows(f,F)){if(T==="Allows"){if(!Go(f,()=>$.value.traverseAllows(o[f],F),F))return!1}else if(Go(f,()=>$.value.traverseApply(o[f],F),F),F.failFast&&F.currentErrorCount>A)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(f)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[f],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((o)=>o.signature.allows(T))||this.sequence!==void 0&&K.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let o=[];if(this.props.length)o.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)o.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)o.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return o.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",OY(this))}structuralMorphRef=this.structuralMorph&&BT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let o of this.props)if(T.check(o),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),XY(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let o of this.index)T.if(`${T.invoke(o.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",o.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,o){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,o);case"array":let F=this.sequence?.reduceJsonSchema(T,o)??T;if(this.props.length||this.index)return o.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},o)});return F;default:return LT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,o){if(this.props.length){T.properties={};for(let F of this.props){let A=F.value.toJsonSchemaRecurse(o);if(typeof F.key==="symbol"){o.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:A,optional:F.optional});continue}if(F.hasDefault()){let y=typeof F.default==="function"?F.default():F.default;A.default=K.intrinsic.jsonData.allows(y)?y:o.fallback.defaultValue({code:"defaultValue",base:A,value:y})}T.properties[F.key]=A}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let A=F.value.toJsonSchemaRecurse(o);if(F.signature.equals(K.intrinsic.string)){T.additionalProperties=A;continue}for(let y of F.signature.branches){if(!y.extends(K.intrinsic.string)){T=o.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:A,optional:!1});continue}let S={type:"string"};if(y.hasKind("morph"))S=o.fallback.morph({code:"morph",base:y.in.toJsonSchemaRecurse(o),out:y.out.toJsonSchemaRecurse(o)});if(!y.hasKind("intersection"))return $T(`Unexpected index branch kind ${y.kind}.`);let{pattern:f}=y.inner;if(f){let $=Object.assign(S,{pattern:f[0].rule});for(let _=1;_<f.length;_++)S=o.fallback.patternIntersection({code:"patternIntersection",base:$,pattern:f[_].rule});T.patternProperties??={},T.patternProperties[$.pattern]=A}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var U$={},MY=(T)=>{let o="";for(let F=0;F<T.defaultable.length;F++)o+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)o+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(o+="delete !(",T.required)for(let F of T.required)o+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)o+=F.compiledKey+" | ";if(T.index)for(let F of T.index)o+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)o+=n.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)o+=F+" | ";o+=")"}return o},OY=(T)=>{let o=MY(T);if(!o)return;if(U$[o])return U$[o];let F=(A,y)=>{for(let S=0;S<T.defaultable.length;S++)if(!(T.defaultable[S].key in A))T.defaultable[S].defaultValueMorph(A,y);if(T.sequence?.defaultables)for(let S=A.length-T.sequence.prefixLength;S<T.sequence.defaultables.length;S++)T.sequence.defaultValueMorphs[S](A,y);if(T.undeclared==="delete"){for(let S in A)if(!T.declaresKey(S))delete A[S]}return A};return U$[o]=F},XY=(T,o)=>{let A=`(data${o.defaultable.some((y)=>y.defaultValueMorph.length===2)||o.sequence?.defaultValueMorphs.some((y)=>y.length===2)?", ctx":""})`;return T.block(`${A} => `,(y)=>{for(let S=0;S<o.defaultable.length;S++){let{serializedKey:f,defaultValueMorphRef:$}=o.defaultable[S];y.if(`!(${f} in data)`,(_)=>_.line(`${$}${A}`))}if(o.sequence?.defaultables)y.for(`i < ${o.sequence.defaultables.length}`,(S)=>S.set("data[i]",5),`data.length - ${o.sequence.prefixLength}`);if(o.undeclared==="delete")y.forIn("data",(S)=>S.if(`!(${o._compileDeclaresKey(S)})`,(f)=>f.line("delete data[k]")));return y.return("data")})},z$={implementation:WY,Node:W1},YY=(T)=>{if(P(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},ZY=(T,o)=>`${T} is not allowed as an array index on ${o}. Use the 'nonNegativeIntegerString' keyword instead.`,MS=(T,o,F)=>{let[A,y]=j_(T.branches,(f)=>f.hasKind("unit"));if(!A.length)return{index:F.node("index",{signature:T,value:o})};let S={};for(let f of A){let $=F.node("required",{key:f.unit,value:o});S[$.kind]=yT(S[$.kind],$)}if(y.length)S.index=F.node("index",{signature:y,value:o});return S},HY=(T)=>P(T,"root")?T.expression:r(T),_1=(T,o)=>`Key${o.length===1?"":"s"} ${o.map(HY).join(", ")} ${o.length===1?"does":"do"} not exist on ${T}`;var XA={...x0,alias:_y.implementation,domain:WS.implementation,unit:H$.implementation,proto:Ry.implementation,union:Z$.implementation,morph:X$.implementation,intersection:O$.implementation,divisor:ef.implementation,pattern:$$.implementation,predicate:af.implementation,required:w$.implementation,optional:fy.implementation,index:G$.implementation,sequence:E$.implementation,structure:z$.implementation};K.defaultConfig=g_(Object.assign(d(XA,(T,o)=>[T,o.defaults]),{jitless:r_(),clone:c_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:LT.defaultConfig}));K.resolvedConfig=eA(K.defaultConfig,K.config);var t0={...b0,alias:_y.Node,domain:WS.Node,unit:H$.Node,proto:Ry.Node,union:Z$.Node,morph:X$.Node,intersection:O$.Node,divisor:ef.Node,pattern:$$.Node,predicate:af.Node,required:w$.Node,optional:fy.Node,index:G$.Node,sequence:E$.Node,structure:z$.Node};class HA extends Nf{get[_o](){return"module"}}var Q$=(T,o)=>new HA(d(T,(F,A)=>[F,P(A,"module")?Q$(A,o):o.bindReference(A)]));var GY=(T)=>HT(T)?T:("branches"in T)&&HT(T.branches)?T.branches:void 0,wY=(T,o)=>G(`Node of kind ${o} is not valid as a ${T} definition`),M1=(T)=>`#${T} duplicates public alias ${T}`,V$={};K.ambient??={};var O1,Y1="function $",EY=(T)=>Z1(T,H1(T)),Z1=(T,o)=>{let F=o.write(Y1,4),A=o.compile()();for(let y of T){if(y.precompilation)continue;if(y.traverseAllows=A[`${y.id}Allows`].bind(A),y.isRoot()&&!y.allowsRequiresContext)y.allows=y.traverseAllows;if(y.traverseApply=A[`${y.id}Apply`].bind(A),A[`${y.id}Optimistic`])y.traverseOptimistic=A[`${y.id}Optimistic`].bind(A);y.precompilation=F}},H1=(T)=>new TS().return(T.reduce((o,F)=>{let A=new aA({kind:"Allows"}).indent();F.compile(A);let y=A.write(`${F.id}Allows`),S=new aA({kind:"Apply"}).indent();F.compile(S);let f=S.write(`${F.id}Apply`),$=`${o}${y},
44
- ${f},
45
- `;if(!F.hasKind("union"))return $;let _=new aA({kind:"Allows",optimistic:!0}).indent();F.compile(_);let J=_.write(`${F.id}Optimistic`);return`${$}${J},
43
+ Right: ${F}`;var L9=c({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():E0(T)}},normalize:(T)=>T,defaults:{description:(T)=>o(T.unit),problem:({expected:T,actual:F})=>`${T===F?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${F})`}`},intersections:{unit:(T,F)=>I.init("unit",T,F),...h0("unit",(T,F)=>{if(F.allows(T.unit))return T;let _=F.hasKind("intersection")?F.basis:F;if(_){let W=_.hasKind("domain")?_:w.intrinsic.object;if(T.domain!==W.domain){let J=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:w.intrinsic[T.domain];return I.init("domain",J,W)}}return I.init("assignability",T,F.hasKind("intersection")?F.children.find((W)=>!W.allows(T.unit)):F)})}});class F$ extends LF{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=T$(this.unit,this.serializedValue);compiledNegation=T$(this.unit,this.serializedValue,"negated");expression=o(this.unit);domain=fT(this.unit);get defaultShortDescription(){return this.domain==="object"?T0.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:w.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var j2={implementation:L9,Node:F$},T$=(T,F,_)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${F}`;return _?`!(${W})`:W}if(Number.isNaN(T))return`${_?"!":""}Number.isNaN(data)`;return`data ${_?"!":"="}== ${F}`};var S9=c({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,F)=>{let _=F.$.parseSchema(T);if(!_.extends(w.intrinsic.key))return z(N9(_.expression));let W=_.branches.filter((J)=>J.hasKind("unit"));if(W.length)return z(I9(W.map((J)=>o(J.unit))));return _}},value:{child:!0,parse:(T,F)=>F.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,F,_)=>{if(T.signature.equals(F.signature)){let W=UT(T.value,F.value,_),J=W instanceof I?w.intrinsic.never.internal:W;return _.$.node("index",{signature:T.signature,value:J})}if(T.signature.extends(F.signature)&&T.value.subsumes(F.value))return F;if(F.signature.extends(T.signature)&&F.value.subsumes(T.value))return T;return null}}});class _$ extends R0{impliedBasis=w.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=r(this.value.flatRefs.map((T)=>f0([this.signature,...T.path],T.node)),f0([this.signature],this.value));traverseAllows=(T,F)=>wF(T).every((_)=>{if(this.signature.traverseAllows(_[0],F))return _0(_[0],()=>this.value.traverseAllows(_[1],F),F);return!0});traverseApply=(T,F)=>{for(let _ of wF(T))if(this.signature.traverseAllows(_[0],F))_0(_[0],()=>this.value.traverseApply(_[1],F),F)};_transform(T,F){F.path.push(this.signature);let _=super._transform(T,F);return F.path.pop(),_}compile(){}}var y2={implementation:S9,Node:_$},I9=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,N9=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var C9=c({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,F)=>F.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:f_,optional:f_}});class W$ extends q_{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=YF(this.errorContext)}var P2={implementation:C9,Node:W$};var k9=c({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,F)=>{if(T.length===0)return;return T.map((_)=>F.$.parseSchema(_))}},optionals:{child:!0,parse:(T,F)=>{if(T.length===0)return;return T.map((_)=>F.$.parseSchema(_))}},defaultables:{child:(T)=>T.map((F)=>F[0]),parse:(T,F)=>{if(T.length===0)return;return T.map((_)=>{let W=F.$.parseSchema(_[0]);return y_(W,_[1],null),[W,_[1]]})},serialize:(T)=>T.map((F)=>[F[0].collapsibleJson,E0(F[1])])},variadic:{child:!0,parse:(T,F)=>F.$.parseSchema(T,F)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,F)=>{if(T.length===0)return;return T.map((_)=>F.$.parseSchema(_))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return z(j9);if(T.optionals?.length||T.defaultables?.length)return z(x2)}if(T.minVariadicLength&&!T.variadic)return z("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,F)=>{let _=T.minVariadicLength??0,W=T.prefix?.slice()??[],J=T.defaultables?.slice()??[],$=T.optionals?.slice()??[],Y=T.postfix?.slice()??[];if(T.variadic){while($.at(-1)?.equals(T.variadic))$.pop();if($.length===0&&J.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),_++;while(Y[0]?.equals(T.variadic))Y.shift(),_++}else if($.length===0&&J.length===0)W.push(...Y.splice(0));if(_!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return F.node("sequence",{...T,prefix:W,defaultables:J,optionals:$,postfix:Y,minVariadicLength:_},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((_)=>_.kind==="defaultables"?`${_.node.nestableExpression} = ${o(_.default)}`:_.kind==="optionals"?`${_.node.nestableExpression}?`:_.kind==="variadic"?`...${_.node.nestableExpression}[]`:_.node.expression).join(", ")}]`}},intersections:{sequence:(T,F,_)=>{let W=b_({l:T.tuple,r:F.tuple,disjoint:new I,result:[],fixedVariants:[],ctx:_}),J=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return J.length===0?W.disjoint:J.length===1?_.$.node("sequence",J$(J[0].result)):_.$.node("union",J.map(($)=>({proto:Array,sequence:J$($.result)})))}}});class $$ extends R0{impliedBasis=w.intrinsic.Array.internal;tuple=q9(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((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=c0(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return A2(this.flatRefs,this.prevariadic.flatMap((T,F)=>r(T.node.flatRefs.map((_)=>f0([`${F}`,..._.path],_.node)),f0([`${F}`],T.node)))),A2(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>r(T.flatRefs.map((F)=>f0([w.intrinsic.nonNegativeIntegerString.internal,...F.path],F.node)),f0([w.intrinsic.nonNegativeIntegerString.internal],T)))),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=f9(this);defaultValueMorphsReference=this.defaultValueMorphs.length?VT(this.defaultValueMorphs):void 0;elementAtIndex(T,F){if(F<this.prevariadic.length)return this.tuple[F];let _=T.length-this.postfixLength;if(F>=_)return{kind:"postfix",node:this.postfix[F-_]};return{kind:"variadic",node:this.variadic??a(`Unexpected attempt to access index ${F} on ${this}`)}}traverseAllows=(T,F)=>{for(let _=0;_<T.length;_++)if(!this.elementAtIndex(T,_).node.traverseAllows(T[_],F))return!1;return!0};traverseApply=(T,F)=>{let _=0;for(;_<T.length;_++)_0(_,()=>this.elementAtIndex(T,_).node.traverseApply(T[_],F),F)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[F,_]of this.prefix.entries())T.traverseKey(`${F}`,`data[${F}]`,_);for(let[F,_]of this.defaultablesAndOptionals.entries()){let W=`${F+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,_)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[F,_]of this.postfix.entries()){let W=`firstPostfixIndex + ${F}`;T.traverseKey(W,`data[${W}]`,_)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,F){F.path.push(w.intrinsic.nonNegativeIntegerString.internal);let _=super._transform(T,F);return F.path.pop(),_}expression=this.description;reduceJsonSchema(T,F){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((_)=>{let W=_.node.toJsonSchemaRecurse(F);if(_.kind==="defaultables"){let J=typeof _.default==="function"?_.default():_.default;W.default=w.intrinsic.jsonData.allows(J)?J:F.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let _=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(F)});if(this.maxLength)_.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((J)=>J.toJsonSchemaRecurse(F));T=F.fallback.arrayPostfix({code:"arrayPostfix",base:_,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var B9={},f9=(T)=>{if(!T.defaultables)return[];let F=[],_="[",W=T.prefixLength+T.defaultablesLength-1;for(let J=T.prefixLength;J<=W;J++){let[$,Y]=T.defaultables[J-T.prefixLength];F.push(C2(J,$,Y)),_+=`${J}: ${$.id} = ${E0(Y)}, `}return _+="]",B9[_]??=F},v2={implementation:k9,Node:$$},q9=(T)=>{let F=[];if(T.prefix)for(let _ of T.prefix)F.push({kind:"prefix",node:_});if(T.defaultables)for(let[_,W]of T.defaultables)F.push({kind:"defaultables",node:_,default:W});if(T.optionals)for(let _ of T.optionals)F.push({kind:"optionals",node:_});if(T.variadic)F.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let _ of T.postfix)F.push({kind:"postfix",node:_});return F},J$=(T)=>T.reduce((F,_)=>{if(_.kind==="variadic")F.variadic=_.node;else if(_.kind==="defaultables")F.defaultables=r(F.defaultables,[[_.node,_.default]]);else F[_.kind]=r(F[_.kind],_.node);return F},{}),x2="A postfix required element cannot follow an optional or defaultable element",j9="A postfix element requires a variadic element",b_=(T)=>{let[F,..._]=T.l,[W,...J]=T.r;if(!F||!W)return T;let $=_.at(-1)?.kind==="postfix",Y=J.at(-1)?.kind==="postfix",Z=F.kind==="prefix"||W.kind==="prefix"?"prefix":F.kind==="postfix"||W.kind==="postfix"?"postfix":F.kind==="variadic"&&W.kind==="variadic"?"variadic":$||Y?"prefix":F.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if(F.kind==="prefix"&&W.kind==="variadic"&&Y){let M=b_({...T,fixedVariants:[],r:J.map((E)=>({...E,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(W.kind==="prefix"&&F.kind==="variadic"&&$){let M=b_({...T,fixedVariants:[],l:_.map((E)=>({...E,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let A=UT(F.node,W.node,T.ctx);if(A instanceof I)if(Z==="prefix"||Z==="postfix")T.disjoint.push(...A.withPrefixKey(Z==="prefix"?T.result.length:`-${_.length+1}`,"required")),T.result=[...T.result,{kind:Z,node:w.intrinsic.never.internal}];else if(Z==="optionals"||Z==="defaultables")return T;else return b_({...T,fixedVariants:[],l:_.map((M)=>({...M,kind:"prefix"})),r:_.map((M)=>({...M,kind:"prefix"}))});else if(Z==="defaultables"){if(F.kind==="defaultables"&&W.kind==="defaultables"&&F.default!==W.default)z(N2(F.default,W.default));T.result=[...T.result,{kind:Z,node:A,default:F.kind==="defaultables"?F.default:W.kind==="defaultables"?W.default:a(`Unexpected defaultable intersection from ${F.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:Z,node:A}];let X=T.l.length,O=T.r.length;if(F.kind!=="variadic"||X>=O&&(W.kind==="variadic"||O===1))T.l=_;if(W.kind!=="variadic"||O>=X&&(F.kind==="variadic"||X===1))T.r=J;return b_(T)};var X$=(T)=>(F)=>{if(F.props.length||F.index){let _=F.index?.map((J)=>J[T])??[];for(let J of F.props)_.push(J[T]);if(F.undeclared)_.push(`+ (undeclared): ${F.undeclared}`);let W=`{ ${_.join(", ")} }`;return F.sequence?`${W} & ${F.sequence.description}`:W}return F.sequence?.description??"{}"},y9=X$("description"),P9=X$("expression"),Y$=(T,F,_)=>{let W=T.required?"required":"optional";if(!F.signature.allows(T.key))return null;let J=W0(T.value,F.value,_);if(J instanceof I)return W==="optional"?_.node("optional",{key:T.key,value:w.intrinsic.never.internal}):J.withPrefixKey(T.key,T.kind);return null},v9=c({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,F)=>{if(!T.undeclared&&F.onUndeclaredKey!=="ignore")return{...T,undeclared:F.onUndeclaredKey};return T},keys:{required:{child:!0,parse:cT("required"),reduceIo:(T,F,_)=>{F.required=r(F.required,_.map((W)=>W[T]));return}},optional:{child:!0,parse:cT("optional"),reduceIo:(T,F,_)=>{if(T==="in"){F.optional=_.map((W)=>W.in);return}for(let W of _)F[W.outProp.kind]=r(F[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:cT("index")},sequence:{child:!0,parse:cT("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,F,_)=>{if(_!=="delete")return;if(T==="in")delete F.undeclared;else F.undeclared="reject"}}},defaults:{description:y9},intersections:{structure:(T,F,_)=>{let W={...T.inner},J={...F.inner},$=new I;if(T.undeclared){let A=T.keyof();for(let X of F.requiredKeys)if(!A.allows(X))$.add("presence",w.intrinsic.never.internal,F.propsByKey[X].value,{path:[X]});if(J.optional)J.optional=J.optional.filter((X)=>A.allows(X.key));if(J.index)J.index=J.index.flatMap((X)=>{if(X.signature.extends(A))return X;let O=W0(A,X.signature,_.$);if(O instanceof I)return[];let M=vW(O,X.value,_.$);if(M.required)J.required=c0(J.required,M.required);if(M.optional)J.optional=c0(J.optional,M.optional);return M.index??[]})}if(F.undeclared){let A=F.keyof();for(let X of T.requiredKeys)if(!A.allows(X))$.add("presence",T.propsByKey[X].value,w.intrinsic.never.internal,{path:[X]});if(W.optional)W.optional=W.optional.filter((X)=>A.allows(X.key));if(W.index)W.index=W.index.flatMap((X)=>{if(X.signature.extends(A))return X;let O=W0(A,X.signature,_.$);if(O instanceof I)return[];let M=vW(O,X.value,_.$);if(M.required)W.required=c0(W.required,M.required);if(M.optional)W.optional=c0(W.optional,M.optional);return M.index??[]})}let Y={};if(T.undeclared||F.undeclared)Y.undeclared=T.undeclared==="reject"||F.undeclared==="reject"?"reject":"delete";let Z=mF({kind:"structure",baseInner:Y,l:oF(W),r:oF(J),roots:[],ctx:_});if(Z instanceof I)$.push(...Z);if($.length)return $;return Z}},reduce:(T,F)=>{if(T.index){if(!(T.required||T.optional))return;let _=!1,W=T.required??[],J=T.optional??[],$=[...J];for(let Y of T.index){for(let Z of W){let A=Y$(Z,Y,F);if(A instanceof I)return A}for(let[Z,A]of J.entries()){let X=Y$(A,Y,F);if(X instanceof I)return X;if(X===null)continue;$[Z]=X,_=!0}}if(_)return F.node("structure",{...T,optional:$},{prereduced:!0})}}});class A$ extends R0{impliedBasis=w.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=c0(this.required,this.optional);propsByKey=m(this.props,(T,F)=>[F.key,F]);propsByKeyReference=VT(this.propsByKey);expression=P9(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:F}of this.index)T=T.concat(F.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((F,_)=>{let W=this.propsByKey[_.key];if(OT(_)){if(_.kind!=="required"&&_.kind!=="optional")return z(`Map result must have kind "required" or "optional" (was ${_.kind})`);return F[_.kind]=r(F[_.kind],_),F}let J=_.kind??W?.kind??"required",$=m(_,(Y,Z)=>(Y in j_.implementation.keys)?[Y,Z]:[]);return F[J]=r(F[J],this.$.node(J,$)),F},{}))}assertHasKeys(T){let F=T.filter((_)=>!P_(_,this.keyof()));if(F.length)return z(Z$(this.expression,F))}get(T,...F){let _,W=!1,J=p9(T);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])_=this.propsByKey[J].value,W=this.propsByKey[J].required;if(this.index){for(let Y of this.index)if(P_(J,Y.signature))_=_?.and(Y.value)??Y.value}if(this.sequence&&P_(J,w.intrinsic.nonNegativeIntegerString))if(q(J,"root")){if(this.sequence.variadic)_=_?.and(this.sequence.element)??this.sequence.element}else{let Y=Number.parseInt(J);if(Y<this.sequence.prevariadic.length){let Z=this.sequence.prevariadic[Y].node;_=_?.and(Z)??Z,W||=Y<this.sequence.prefixLength}else if(this.sequence.variadic){let Z=this.$.node("union",this.sequence.variadicOrPostfix);_=_?.and(Z)??Z}}if(!_){if(this.sequence?.variadic&&q(J,"root")&&J.extends(w.intrinsic.number))return z(g9(J.expression,this.sequence.expression));return z(Z$(this.expression,[J]))}let $=_.get(...F);return W?$:$.or(w.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,...F}=this.inner;return this.$.node("structure",{...F,optional:this.props.map((_)=>_.hasKind("required")?this.$.node("optional",_.inner):_)})}require(){let{optional:T,...F}=this.inner;return this.$.node("structure",{...F,required:this.props.map((_)=>_.hasKind("optional")?{key:_.key,value:_.value}:_)})}merge(T){let F=this.filterKeys("omit",[T.keyof()]);if(T.required)F.required=r(F.required,T.required);if(T.optional)F.optional=r(F.optional,T.optional);if(T.index)F.index=r(F.index,T.index);if(T.sequence)F.sequence=T.sequence;if(T.undeclared)F.undeclared=T.undeclared;else delete F.undeclared;return this.$.node("structure",F)}filterKeys(T,F){let _=SW(this.inner),W=(J)=>{let $=F.some((Y)=>P_(J,Y));return T==="pick"?$:!$};if(_.required)_.required=_.required.filter((J)=>W(J.key));if(_.optional)_.optional=_.optional.filter((J)=>W(J.key));if(_.index)_.index=_.index.filter((J)=>W(J.signature));return _}traverseAllows=(T,F)=>this._traverse("Allows",T,F);traverseApply=(T,F)=>this._traverse("Apply",T,F);_traverse=(T,F,_)=>{let W=_?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(T==="Allows"){if(!this.props[J].traverseAllows(F,_))return!1}else if(this.props[J].traverseApply(F,_),_.failFast&&_.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(F,_))return!1}else if(this.sequence.traverseApply(F,_),_.failFast&&_.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(F);J.push(...Object.getOwnPropertySymbols(F));for(let $=0;$<J.length;$++){let Y=J[$];if(this.index){for(let Z of this.index)if(Z.signature.traverseAllows(Y,_)){if(T==="Allows"){if(!_0(Y,()=>Z.value.traverseAllows(F[Y],_),_))return!1}else if(_0(Y,()=>Z.value.traverseApply(F[Y],_),_),_.failFast&&_.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(Y)){if(T==="Allows")return!1;if(_.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[Y],meta:this.meta}),_.failFast)return!1}}}if(this.structuralMorph&&_&&!_.hasError())_.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((F)=>F.signature.allows(T))||this.sequence!==void 0&&w.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let F=[];if(this.props.length)F.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let _ of this.index)F.push(T.invoke(_.signature,{kind:"Allows",arg:"k"}));if(this.sequence)F.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return F.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",b9(this))}structuralMorphRef=this.structuralMorph&&VT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let F of this.props)if(T.check(F),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),h9(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let F of this.index)T.if(`${T.invoke(F.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",F.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,F){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,F);case"array":let _=this.sequence?.reduceJsonSchema(T,F)??T;if(this.props.length||this.index)return F.fallback.arrayObject({code:"arrayObject",base:_,object:this.reduceObjectJsonSchema({type:"object"},F)});return _;default:return ET.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,F){if(this.props.length){T.properties={};for(let _ of this.props){let W=_.value.toJsonSchemaRecurse(F);if(typeof _.key==="symbol"){F.fallback.symbolKey({code:"symbolKey",base:T,key:_.key,value:W,optional:_.optional});continue}if(_.hasDefault()){let J=typeof _.default==="function"?_.default():_.default;W.default=w.intrinsic.jsonData.allows(J)?J:F.fallback.defaultValue({code:"defaultValue",base:W,value:J})}T.properties[_.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((_)=>typeof _==="string"&&(_ in T.properties))}if(this.index)for(let _ of this.index){let W=_.value.toJsonSchemaRecurse(F);if(_.signature.equals(w.intrinsic.string)){T.additionalProperties=W;continue}for(let J of _.signature.branches){if(!J.extends(w.intrinsic.string)){T=F.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let $={type:"string"};if(J.hasKind("morph"))$=F.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse(F),out:J.out.toJsonSchemaRecurse(F)});if(!J.hasKind("intersection"))return a(`Unexpected index branch kind ${J.kind}.`);let{pattern:Y}=J.inner;if(Y){let Z=Object.assign($,{pattern:Y[0].rule});for(let A=1;A<Y.length;A++)$=F.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:Y[A].rule});T.patternProperties??={},T.patternProperties[Z.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var b2={},x9=(T)=>{let F="";for(let _=0;_<T.defaultable.length;_++)F+=T.defaultable[_].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)F+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(F+="delete !(",T.required)for(let _ of T.required)F+=_.compiledKey+" | ";if(T.optional)for(let _ of T.optional)F+=_.compiledKey+" | ";if(T.index)for(let _ of T.index)F+=_.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)F+=v.nonNegativeIntegerString.id;else for(let _=0;_<T.sequence.tuple.length;_++)F+=_+" | ";F+=")"}return F},b9=(T)=>{let F=x9(T);if(!F)return;if(b2[F])return b2[F];let _=(W,J)=>{for(let $=0;$<T.defaultable.length;$++)if(!(T.defaultable[$].key in W))T.defaultable[$].defaultValueMorph(W,J);if(T.sequence?.defaultables)for(let $=W.length-T.sequence.prefixLength;$<T.sequence.defaultables.length;$++)T.sequence.defaultValueMorphs[$](W,J);if(T.undeclared==="delete"){for(let $ in W)if(!T.declaresKey($))delete W[$]}return W};return b2[F]=_},h9=(T,F)=>{let W=`(data${F.defaultable.some((J)=>J.defaultValueMorph.length===2)||F.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return T.block(`${W} => `,(J)=>{for(let $=0;$<F.defaultable.length;$++){let{serializedKey:Y,defaultValueMorphRef:Z}=F.defaultable[$];J.if(`!(${Y} in data)`,(A)=>A.line(`${Z}${W}`))}if(F.sequence?.defaultables)J.for(`i < ${F.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${F.sequence.prefixLength}`);if(F.undeclared==="delete")J.forIn("data",($)=>$.if(`!(${F._compileDeclaresKey($)})`,(Y)=>Y.line("delete data[k]")));return J.return("data")})},h2={implementation:v9,Node:A$},p9=(T)=>{if(q(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},g9=(T,F)=>`${T} is not allowed as an array index on ${F}. Use the 'nonNegativeIntegerString' keyword instead.`,vW=(T,F,_)=>{let[W,J]=jJ(T.branches,(Y)=>Y.hasKind("unit"));if(!W.length)return{index:_.node("index",{signature:T,value:F})};let $={};for(let Y of W){let Z=_.node("required",{key:Y.unit,value:F});$[Z.kind]=r($[Z.kind],Z)}if(J.length)$.index=_.node("index",{signature:J,value:F});return $},m9=(T)=>q(T,"root")?T.expression:o(T),Z$=(T,F)=>`Key${F.length===1?"":"s"} ${F.map(m9).join(", ")} ${F.length===1?"does":"do"} not exist on ${T}`;var cF={...y8,alias:v_.implementation,domain:PW.implementation,unit:j2.implementation,proto:x_.implementation,union:q2.implementation,morph:B2.implementation,intersection:k2.implementation,divisor:M2.implementation,pattern:D2.implementation,predicate:U2.implementation,required:P2.implementation,optional:j_.implementation,index:y2.implementation,sequence:v2.implementation,structure:h2.implementation};w.defaultConfig=mJ(Object.assign(m(cF,(T,F)=>[T,F.defaults]),{jitless:iJ(),clone:cJ,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:ET.defaultConfig}));w.resolvedConfig=I_(w.defaultConfig,w.config);var p8={...P8,alias:v_.Node,domain:PW.Node,unit:j2.Node,proto:x_.Node,union:q2.Node,morph:B2.Node,intersection:k2.Node,divisor:M2.Node,pattern:D2.Node,predicate:U2.Node,required:P2.Node,optional:j_.Node,index:y2.Node,sequence:v2.Node,structure:h2.Node};class iF extends t1{get[iT](){return"module"}}var p2=(T,F)=>new iF(m(T,(_,W)=>[_,q(W,"module")?p2(W,F):F.bindReference(W)]));var o9=(T)=>YT(T)?T:("branches"in T)&&YT(T.branches)?T.branches:void 0,u9=(T,F)=>z(`Node of kind ${F} is not valid as a ${T} definition`),G$=(T)=>`#${T} duplicates public alias ${T}`,g2={};w.ambient??={};var H$,U$="function $",c9=(T)=>M$(T,Q$(T)),M$=(T,F)=>{let _=F.write(U$,4),W=F.compile()();for(let J of T){if(J.precompilation)continue;if(J.traverseAllows=W[`${J.id}Allows`].bind(W),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=W[`${J.id}Apply`].bind(W),W[`${J.id}Optimistic`])J.traverseOptimistic=W[`${J.id}Optimistic`].bind(W);J.precompilation=_}},Q$=(T)=>new LW().return(T.reduce((F,_)=>{let W=new S_({kind:"Allows"}).indent();_.compile(W);let J=W.write(`${_.id}Allows`),$=new S_({kind:"Apply"}).indent();_.compile($);let Y=$.write(`${_.id}Apply`),Z=`${F}${J},
44
+ ${Y},
45
+ `;if(!_.hasKind("union"))return Z;let A=new S_({kind:"Allows",optimistic:!0}).indent();_.compile(A);let X=A.write(`${_.id}Optimistic`);return`${Z}${X},
46
46
  `},`{
47
- `)+"}");class OS{config;resolvedConfig;name;get[_o](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,o){if(this.config=eA(K.config,o),this.resolvedConfig=eA(K.resolvedConfig,o),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(V$).length}`,this.name in V$)G(`A Scope already named ${this.name} already exists`);V$[this.name]=this;let F=Object.entries(T).map((A)=>this.preparseOwnAliasEntry(...A));for(let[A,y]of F){let S=A;if(A[0]==="#"){if(S=A.slice(1),S in this.aliases)G(M1(S));this.aliases[S]=y}else{if(S in this.aliases)G(M1(A));this.aliases[S]=y,this.exportedNames.push(S)}if(!P(y,"module")&&!P(y,"generic")&&!UF(y)){let f=this.preparseOwnDefinitionFormat(y,{alias:S});this.resolutions[S]=P(f,"root")?this.bindReference(f):this.createParseContext(f).id}}O1??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[O1.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=K.intrinsic?d(K.intrinsic,(A,y)=>A.startsWith("json")?[]:[A,this.bindReference(y)]):{}}cacheGetter(T,o){return Object.defineProperty(this,T,{value:o}),o}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let o=this;return(F,A)=>new LF(T,A?new SS(F):F,o,o,A??null)};units=(T,o)=>{let F=[];for(let y of T)if(!F.includes(y))F.push(y);let A=F.map((y)=>this.node("unit",{unit:y},o));return this.node("union",A,{...o,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,o){let F=this.node("alias",{reference:o??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,o)=>this.finalize(this.parseSchema(T,o));parseSchema=(T,o)=>this.node(Ay(T),T,o);preparseNode(T,o,F){let A=typeof T==="string"?T:Ay(o,T);if(UT(o)&&o.kind===A)return o;if(A==="alias"&&!F?.prereduced){let{reference:f}=_y.implementation.normalize(o,this);if(f.startsWith("$")){let $=this.resolveRoot(f.slice(1));o=$,A=$.kind}}else if(A==="union"&&Yo(o,"object")){let f=GY(o);if(f?.length===1)o=f[0],A=Ay(o)}if(UT(o)&&o.kind===A)return o;let S=XA[A].normalize?.(o,this)??o;if(UT(S))return S.kind===A?S:wY(A,S.kind);return{...F,$:this,kind:A,def:S,prefix:F.alias??A}}bindReference(T){let o;if(UT(T))o=T.$===this?T:new T.constructor(T.attachments,this);else o=T.$===this?T:new LF(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,o.referencesById);return o}resolveRoot(T){return this.maybeResolveRoot(T)??G(C$(T))}maybeResolveRoot(T){let o=this.maybeResolve(T);if(P(o,"generic"))return;return o}maybeResolveSubalias(T){return D$(this.aliases,T)??D$(this.ambient,T)}get ambient(){return K.ambient}maybeResolve(T){let o=this.resolutions[T];if(o){if(typeof o!=="string")return this.bindReference(o);let A=Ro[o];if(P(A,"root"))return this.resolutions[T]=A;if(P(A,"context")){if(A.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(A.phase==="resolved")return $T(`Unexpected resolved context for was uncached by its scope: ${r(A)}`);A.phase="resolving";let y=this.bindReference(this.parseOwnDefinitionFormat(A.def,A));return A.phase="resolved",Ro[y.id]=y,Ro[A.id]=y,this.resolutions[T]=y}return $T(`Unexpected nodesById entry for ${o}: ${r(A)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),P(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(P(F,"module")){if(!F.root)G(E1(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let o=T.id??J$(T.prefix);return Ro[o]=Object.assign(T,{[_o]:"context",$:this,id:o,phase:"unresolved"})}traversal(T){return new go(T,this.resolvedConfig)}import(...T){return new HA(d(this.export(...T),(o,F)=>[`#${o}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let A=this.aliases[F];this._exports[F]=P(A,"module")?Q$(A,this):X1(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=w1(this,this._exports),this._json=G1(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=H1(this.references);this.precompilation=F.write(Y1,4),Z1(this.references,F)}this.resolved=!0}let o=T.length?T:this.exportedNames;return new HA(d(o,(F,A)=>[A,this._exports[A]]))}resolve(T){return this.export()[T]}node=(T,o,F={})=>{let A=this.preparseNode(T,o,F);if(UT(A))return this.bindReference(A);let y=this.createParseContext(A),S=_$(y),f=this.bindReference(S);return Ro[y.id]=f};parse=(T,o={})=>this.finalize(this.parseDefinition(T,o));parseDefinition(T,o={}){if(P(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,o);if(P(F,"root"))return this.bindReference(F);let A=this.createParseContext(F);Ro[A.id]=A;let y=this.bindReference(this.parseOwnDefinitionFormat(T,A));if(y.isCyclic)y=m0(y,A.id);return Ro[A.id]=y,y}finalize(T){if(X1(T),!T.precompilation&&!this.resolvedConfig.jitless)EY(T.references);return T}}class L$ extends OS{parseOwnDefinitionFormat(T,o){return _$(o)}preparseOwnDefinitionFormat(T,o){return this.preparseNode(Ay(T),T,o)}preparseOwnAliasEntry(T,o){return[T,o]}normalizeRootScopeValue(T){return T}}var X1=(T)=>{let o=T.references.filter((F)=>F.hasKind("alias"));for(let F of o){Object.assign(F.referencesById,F.resolution.referencesById);for(let A of T.references)if(F.id in A.referencesById)Object.assign(A.referencesById,F.referencesById)}return T},G1=(T)=>d(T,(o,F)=>[o,P(F,"root")||P(F,"generic")?F.json:P(F,"module")?G1(F):$T(`Unexpected resolution ${r(F)}`)]),D$=(T,o)=>{let F=o.indexOf(".");if(F===-1)return;let A=o.slice(0,F),y=T[A];if(y===void 0)return;if(!P(y,"module"))return G(KY(A));let S=o.slice(F+1),f=y[S];if(f===void 0)return D$(y,S);if(P(f,"root")||P(f,"generic"))return f;if(P(f,"module"))return f.root??G(E1(o));$T(`Unexpected resolution for alias '${o}': ${r(f)}`)},XS=(T,o)=>new L$(T,o),My=new L$({});var w1=(T,o)=>{let F={};for(let A in o){let y=o[A];if(P(y,"module")){let S=w1(T,y),f=d(S,($,_)=>[`${A}.${$}`,_]);Object.assign(F,f)}else if(P(y,"root")||P(y,"generic"))F[A]=y;else $T(`Unexpected scope resolution ${r(y)}`)}return F},C$=(T)=>`'${T}' is unresolvable`,KY=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,E1=(T)=>`Reference to submodule '${T}' must specify an alias`;My.export();var{schema:WT,node:GA,defineSchema:kK,generic:po}=My;var I$="^(?:0|[1-9]\\d*)$",UY=new RegExp(I$),pK=BT(UY);var K1=XS({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();K.intrinsic={...K1};var U1=XS({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:I$}},{prereducedAliases:!0}).export();Object.assign(K.intrinsic,U1);var zY=XS({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),n={...K1,...U1,...zY,emptyStructure:GA("structure",{},{prereduced:!0})};K.intrinsic={...n};var Q1=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],z1=(T)=>T.toString()!=="Invalid Date",V1=(T)=>T.slice(2,-1),k$=(T)=>`'${T}' could not be parsed by the Date constructor`,D1=(T,o)=>QY(T,o),QY=(T,o)=>{let F=new Date(T);if(z1(F))return F;let A=y0(T);if(A!==void 0){let y=new Date(A);if(z1(y))return y}return o?G(o===!0?k$(T):o):void 0};var B$=(T,o)=>{let F=T.scanner.shiftUntil(VY[C1[o]]);if(T.scanner.lookahead==="")return T.error(LY(F,o));if(T.scanner.shift(),o==="/"){try{new RegExp(F)}catch(A){G(String(A))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(hT(o,N$))T.root=T.ctx.$.node("unit",{unit:F});else{let A=D1(F,k$(F));T.root=T.ctx.$.node("unit",{meta:F,unit:A})}},N$={"'":1,'"':1},L1={"/":1,"'":1,'"':1},C1={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},VY={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},DY={'"':"double-quote","'":"single-quote","/":"forward slash"},LY=(T,o)=>`${o}${T} requires a closing ${DY[C1[o]]}`;var I1=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,YS="Optional definitions like 'string?' are only valid as properties in an object or tuple",ZS="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var k1={">":!0,">=":!0},B1={"<":!0,"<=":!0};var wA={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},N1=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,HS=(T)=>`Missing ${T}`,p1=(T,o)=>`Left bounds are only valid when paired with right bounds (try ...${o}${T})`,GS=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,j1=(T,o,F,A)=>`An expression may have at most one left bound (parsed ${T}${wA[o]}, ${F}${wA[A]})`;var x1=(T,o,F)=>b1(T,o,F,[]),b1=(T,o,F,A)=>{let y=F.parseUntilFinalizer();if(A.push(y.root),y.finalizer===">"){if(A.length!==o.params.length)return F.error(p$(T,o.names,A.map((S)=>S.expression)));return A}if(y.finalizer===",")return b1(T,o,F,A);return y.error(HS(">"))},p$=(T,o,F)=>`${T}<${o.join(", ")}> requires exactly ${o.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var j$=(T)=>{let o=T.scanner.shiftUntilNextTerminator();if(o==="keyof")T.addPrefix("keyof");else T.root=IY(T,o)},CY=(T,o,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(p$(T,o.names,[]));let y=x1(T,o,F);return o(...y)},IY=(T,o)=>kY(T,o)??BY(T,o)??T.error(o===""?T.scanner.lookahead==="#"?I1(T.shiftedByOne().scanner.shiftUntilNextTerminator()):x$(T):C$(o)),kY=(T,o)=>{if(T.ctx.args?.[o]){let A=T.ctx.args[o];if(typeof A!=="string")return A;return T.ctx.$.node("alias",{reference:A},{prereduced:!0})}let F=T.ctx.$.maybeResolve(o);if(P(F,"root"))return F;if(F===void 0)return;if(P(F,"generic"))return CY(o,F,T);return G(`Unexpected resolution ${r(F)}`)},BY=(T,o)=>{let F=S0(o);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let A=$0(o);if(A!==void 0)return T.ctx.$.node("unit",{unit:A})},x$=(T)=>{let o=T.previousOperator();return o?b$(o,T.scanner.unscanned):NY(T.scanner.unscanned)},b$=(T,o="")=>`Token '${T}' requires a right operand${o?` before '${o}'`:""}`,NY=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var q$=(T)=>T.scanner.lookahead===""?T.error(x$(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(L1)?B$(T,T.scanner.shift()):T.scanner.lookaheadIsIn(zF)?q$(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in N$?B$(T,`${T.scanner.shift()}${T.scanner.shift()}`):j$(T):j$(T);class WF extends tf{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in WF.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...zF};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,o)=>T===">"?o[0]==="="?o[1]==="=":o.trimStart()===""||hT(o.trimStart()[0],WF.terminatingChars):T==="="?o[0]!=="=":T===","||T==="?"}var v1=(T,o)=>{let F=pY(T,o);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let A=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(A,F);return}}return xY(T,F)},P1={"<":1,">":1,"=":1},pY=(T,o)=>T.scanner.lookaheadIs("=")?`${o}${T.scanner.shift()}`:o;var q1=(T,o,F,A)=>{if(F.extends(K.intrinsic.number)){if(typeof o!=="number")return G(v$(T,o,A));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(K.intrinsic.lengthBoundable)){if(typeof o!=="number")return G(v$(T,o,A));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(K.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return G(L0(F.expression))},jY=(T)=>({rule:Q1(T.limit)?V1(T.limit):T.limit,exclusive:T.comparator.length===1}),xY=(T,o)=>{let F=T.unsetRoot(),A=T.scanner.location;T.parseOperand();let y=T.unsetRoot(),S=T.scanner.sliceChars(A,T.scanner.location);if(T.root=F,!y.hasKind("unit")||typeof y.unit!=="number"&&!(y.unit instanceof Date))return T.error(v$(o,S,"right"));let f=y.unit,$=o.length===1,_=q1(o,typeof f==="number"?f:S,F,"right");for(let R of _)T.constrainRoot(R,o==="=="?{rule:f}:{rule:f,exclusive:$});if(!T.branches.leftBound)return;if(!hT(o,B1))return T.error(GS(o));let J=q1(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(J[0],jY(T.branches.leftBound)),T.branches.leftBound=null},v$=(T,o,F)=>`Comparator ${F==="left"?wA[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${o})`;var m1=(T)=>{T.scanner.shiftUntilNonWhitespace();let o=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(o)};var h1=(T)=>{let o=T.scanner.shiftUntilNextTerminator(),F=f0(o,{errorOnFail:t1(o)});if(F===0)T.error(t1(0));T.root=T.root.constrain("divisor",F)},t1=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var P$=(T)=>{let o=T.scanner.shift();return o===""?T.finalize(""):o==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(bY):o==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(o):o==="&"?T.pushRootToBranch(o):o===")"?T.finalizeGroup():WF.lookaheadIsFinalizing(o,T.scanner.unscanned)?T.finalize(o):hT(o,P1)?v1(T,o):o==="%"?h1(T):o==="#"?m1(T):(o in zF)?P$(T):T.error(wS(o))},wS=(T,o="")=>`'${T}' is not allowed here${o&&` (should be ${o})`}`,bY="Missing expected ']'";var g1=(T)=>{let o=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(qY(F.expression));let A=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[o,"=",A]},qY=(T)=>`Default value '${T}' must a literal value`;var m$=(T,o)=>{let F=o.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let S=o.$.maybeResolveRoot(T.slice(0,-2));if(S)return S.array()}let A=new EA(new WF(T),o),y=vY(A);if(A.finalizer===">")G(wS(">"));return y},vY=(T)=>{T.parseOperand();let o=Oy(T).root;if(!o)return $T(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")o=g1(T);else if(T.finalizer==="?")o=[o,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)G(wS(T.scanner.lookahead));return o},Oy=(T)=>{while(T.finalizer===void 0)PY(T);return T},PY=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class EA{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,o){this.scanner=T,this.ctx=o}error(T){return G(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(HS(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,o){let F=wA[o];if(!hT(F,k1))return this.error(GS(o));if(this.branches.leftBound)return this.error(j1(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,limit:T}}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 T=this.groups.pop();if(!T)return this.error(N1(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():$T(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let o=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(o)??o,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return Oy(new EA(this.scanner,this.ctx))}parseOperator(){return P$(this)}parseOperand(){return q$(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(p1(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 mY="An empty string is not a valid generic parameter name",ES=(T,o,F)=>{T.shiftUntilNonWhitespace();let A=T.shiftUntilNextTerminator();if(A===""){if(T.lookahead===""&&o.length)return o;return G(mY)}return T.shiftUntilNonWhitespace(),tY(T,A,o,F)},n1="extends ",tY=(T,o,F,A)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(n1))T.jumpForward(n1.length);else{if(T.lookahead===",")T.shift();return F.push(o),ES(T,F,A)}let y=Oy(new EA(T,A));return F.push([o,y.root]),ES(T,F,A)};class t$ extends ho{$;constructor(T){super((...o)=>new Xy(T)(...o),{bind:T});this.$=T}in(T){return new Xy(this.$,T===void 0?void 0:this.$.parse(T))}at(T,o){return new Xy(this.$).at(T,o)}case(T,o){return new Xy(this.$).case(T,o)}}class Xy extends ho{$;in;key;branches=[];constructor(T,o){super((F)=>this.caseEntries(Object.entries(F).map(([A,y])=>A==="default"?[A,y]:[this.$.parse(A),y])));this.$=T,this.in=o}at(T,o){if(this.key)G(gY);if(this.branches.length)G(hY);return this.key=T,o?this.match(o):this}case(T,o){return this.caseEntry(this.$.parse(T),o)}caseEntry(T,o){let A=(this.key?this.$.parse({[this.key]:T}):T).pipe(o);return this.branches.push(A),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([o,F])=>o==="default"?[o,F]:[this.$.node("unit",{unit:o}),F]))}caseEntries(T){for(let o=0;o<T.length;o++){let[F,A]=T[o];if(F==="default"){if(o!==T.length-1)G("default may only be specified as the last key of a switch definition");return this.default(A)}if(typeof A!=="function")return G(`Value for case "${F}" must be a function (was ${tT(A)})`);this.caseEntry(F,A)}return this}default(T){if(typeof T==="function")this.case(n.unknown,T);let o={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")o.meta={onFail:u1};let F=this.$.node("union",o);if(!this.in)return this.$.finalize(F);let A=this.in.pipe(F);if(T==="never"||T==="assert")A=A.configureReferences({onFail:u1},"self");return this.$.finalize(A)}}var u1=(T)=>T.throw(),hY="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",gY="At most one key matcher may be specified per expression";var KS=(T,o)=>{if(HT(T)){if(T[1]==="=")return[o.$.parseOwnDefinitionFormat(T[0],o),"=",T[2]];if(T[1]==="?")return[o.$.parseOwnDefinitionFormat(T[0],o),"?"]}return US(T,o)},c1="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",i1="Only required keys may specify default values, e.g. { value: 'number = 0' }";var d1=(T,o)=>{let F,A={},y=vF(T);for(let[f,$]of y){let _=cY(f);if(_.kind==="spread"){if(!ao(A))return G(uY);let H=o.$.parseOwnDefinitionFormat($,o);if(H.equals(n.object))continue;if(!H.hasKind("intersection")||!H.basis?.equals(n.object))return G(iY(H.expression));F=H.structure;continue}if(_.kind==="undeclared"){if($!=="reject"&&$!=="delete"&&$!=="ignore")G(nY($));A.undeclared=$;continue}let J=KS($,o),R=_;if(_.kind==="required"){if(!HT(J))h$(A,"required",{key:_.normalized,value:J},o);else h$(A,"optional",J[1]==="="?{key:_.normalized,value:J[0],default:J[2]}:{key:_.normalized,value:J[0]},o);continue}if(HT(J)){if(J[1]==="?")G(c1);if(J[1]==="=")G(i1)}if(_.kind==="optional"){h$(A,"optional",{key:_.normalized,value:J},o);continue}let O=o.$.parseOwnDefinitionFormat(R.normalized,o),Y=MS(O,J,o.$);if(Y.index)A.index=yT(A.index,Y.index);if(Y.required)A.required=yT(A.required,Y.required)}let S=o.$.node("structure",A);return o.$.parseSchema({domain:"object",structure:F?.merge(S)??S})},h$=(T,o,F,A)=>{T[o]=yT(T[o],A.$.node(o,F))},nY=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${r(T)})`,uY="Spread operator may only be used as the first key in an object",cY=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===cA?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===cA&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},iY=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var l1=(T,o)=>A6(T)?TR[T[0]](T,o):o6(T)?e1[T[1]](T,o):null,dY=(T,o)=>o.$.parseOwnDefinitionFormat(T[1],o).keyof(),g$=(T,o)=>{if(T[2]===void 0)return G(b$(T[1],""));let F=o.$.parseOwnDefinitionFormat(T[0],o),A=o.$.parseOwnDefinitionFormat(T[2],o);if(T[1]==="|")return o.$.node("union",{branches:[F,A]});let y=T[1]==="&"?wo(F,A,o.$):Fy(F,A,o.$);if(y instanceof k)return y.throw();return y},rY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).array(),lY=(T,o)=>{if(typeof T[2]!=="function")return G(s1("=>",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).pipe(T[2])},s1=(T,o)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof o})`,sY=(T,o)=>{if(typeof T[2]!=="function")return G(s1(":",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).constrain("predicate",T[2])},aY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).configureReferences(T[2],"shallow"),a1=(T)=>T,eY=a1({"[]":rY,"?":()=>G(YS)}),T6=a1({"|":g$,"&":g$,":":sY,"=>":lY,"|>":g$,"@":aY,"=":()=>G(ZS)}),e1={...eY,...T6},o6=(T)=>e1[T[1]]!==void 0,F6=(T)=>T,TR=F6({keyof:dY,instanceof:(T,o)=>{if(typeof T[1]!=="function")return G(r1(nA(T[1])));let F=T.slice(1).map((A)=>typeof A==="function"?o.$.node("proto",{proto:A}):G(r1(nA(A))));return F.length===1?F[0]:o.$.node("union",{branches:F})},"===":(T,o)=>o.$.units(T.slice(1))}),A6=(T)=>TR[T[0]]!==void 0,r1=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var AR=(T,o)=>{let F=[{}],A=0;while(A<T.length){let y=!1;if(T[A]==="..."&&A<T.length-1)y=!0,A++;let S=KS(T[A],o),[f,$,_]=!HT(S)?[S]:S;if(A++,y){if(!f.extends(K.intrinsic.Array))return G(f6(f.expression));F=F.flatMap((J)=>f.distribute((R)=>S6(oS(J),R)))}else F=F.map((J)=>{if($==="?")return yR(J,f);if($==="=")return y6(J,f,_);return n$(J,f)})}return o.$.parseSchema(F.map((y)=>ao(y)?{proto:Array,exactLength:0}:{proto:Array,sequence:y}))},n$=(T,o)=>{if(T.defaultables||T.optionals)return G(T.variadic?K$:$6);if(T.variadic)T.postfix=yT(T.postfix,o);else T.prefix=yT(T.prefix,o);return T},yR=(T,o)=>{if(T.variadic)return G(SR);return T.optionals=yT(T.optionals,o),T},y6=(T,o,F)=>{if(T.variadic)return G(SR);if(T.optionals)return G(J6);return T.defaultables=yT(T.defaultables,[[o,F]]),T},oR=(T,o)=>{if(T.postfix)G(FR);if(T.variadic){if(!T.variadic.equals(o))G(FR)}else T.variadic=o.internal;return T},S6=(T,o)=>{let F=o.select({method:"find",kind:"sequence"});if(!F)return oR(T,K.intrinsic.unknown);if(F.prefix)for(let A of F.prefix)n$(T,A);if(F.optionals)for(let A of F.optionals)yR(T,A);if(F.variadic)oR(T,F.variadic);if(F.postfix)for(let A of F.postfix)n$(T,A);return T},f6=(T)=>`Spread element must be an array (was ${T})`,FR="A tuple may have at most one variadic element",$6="A required element may not follow an optional element",SR="An optional element may not follow a variadic element";var J6="A defaultable element may not follow an optional element without a default";var _6={},US=(T,o)=>{if(typeof T==="string"){if(o.args&&Object.keys(o.args).some((A)=>T.includes(A)))return m$(T,o);let F=_6[o.$.name]??={};return F[T]??=m$(T,o)}return Yo(T,"object")?R6(T,o):G(u$(tT(T)))},R6=(T,o)=>{let F=gA(T);switch(F){case void 0:if(P(T,"root"))return T;return d1(T,o);case"Array":return W6(T,o);case"RegExp":return o.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let A=UF(T)?T():T;if(P(A,"root"))return A;return G(u$("Function"))}default:return G(u$(F??r(T)))}},W6=(T,o)=>l1(T,o)??AR(T,o),u$=(T)=>`Type definitions must be strings or objects (was ${T})`;class c$ extends ho{constructor(T){let o=Object.assign({errors:Ho,hkt:yo,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let A=F[0].slice(1,-1),y=T.parseGenericParams(A,{});return new LF(y,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:o})}}var KA=K;class zS extends OS{get ambientAttachments(){if(!KA.typeAttachments)return;return this.cacheGetter("ambientAttachments",d(KA.typeAttachments,(T,o)=>[T,this.bindReference(o)]))}preparseOwnAliasEntry(T,o){let F=T.indexOf("<");if(F===-1){if(P(o,"module")||P(o,"generic"))return[T,o];let S=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,f=this.resolvedConfig.keywords?.[S];if(f)o=[o,"@",f];return[T,o]}if(T.at(-1)!==">")G("'>' must be the last character of a generic declaration in a scope");let A=T.slice(0,F),y=T.slice(F+1,-1);return[A,()=>{let S=this.parseGenericParams(y,{alias:A});return Q0(S,o,this)}]}parseGenericParams(T,o){return ES(new WF(T),[],this.createParseContext({...o,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(UF(T)&&!P(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,o){return{...o,def:T,prefix:o.alias??"type"}}parseOwnDefinitionFormat(T,o){if(!(o.alias&&(o.alias in this.aliases))&&!o.args)o.args={this:o.id};let A=US(T,o);if(HT(A)){if(A[1]==="=")return G(ZS);if(A[1]==="?")return G(YS)}return A}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(n_(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((o)=>this.parse(o)));and=(...T)=>T.reduce((o,F)=>o.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((o,F)=>o.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new t$(this);declare=()=>({type:this.type});define(T){return T}type=new c$(this);static scope=(T,o={})=>new zS(T,o);static module=(T,o={})=>this.scope(T,o).export()}var i$=Object.assign(zS.scope,{define:(T)=>T}),TT=zS;class fR extends yo{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var M6=po(["base",n.object],["props",n.object])((T)=>T.base.merge(T.props),fR),$R=TT.module({Key:n.key,Merge:M6});class JR extends yo{}var O6=po("element")((T)=>{let o=T.element.exclude(n.Array),F=o.array();return o.rawOr(F).pipe(KF).distribute((A)=>A.assertHasKind("morph").declareOut(F),WT)},JR),_R=TT.module({root:n.Array,readonly:"root",index:n.nonNegativeIntegerString,liftFrom:O6},{name:"Array"});var d$=WT(["string",mF.FileConstructor]),X6=d$.rawOr(d$.array()),RR=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:X6}}),WR=TT.module({root:["instanceof",FormData],value:d$,parsed:RR,parse:WT({in:FormData,morphs:(T)=>{let o={};for(let[F,A]of T)if(F in o){let y=o[F];if(typeof y==="string"||y instanceof mF.FileConstructor)o[F]=[y,A];else y.push(A)}else o[F]=A;return o},declaredOut:RR})},{name:"FormData"});var MR=TT.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 Y6={Boolean:1,Number:1,String:1},OR=TT.module({...d({...pf,...xf},(T,o)=>(T in Y6)?[]:[T,["instanceof",o]]),Array:_R,TypedArray:MR,FormData:WR});var Z6=WT({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"}),H6=WT({domain:"number",divisor:1}),QS=TT.module({root:n.number,integer:H6,epoch:Z6,safe:WT({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 CT=(T,o,F)=>{let A={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:o}};if(F)A.meta={format:F};return GA("intersection",A)},XR=CT(iA,"a well-formed integer string"),DR=TT.module({root:XR,parse:WT({in:XR,morphs:(T,o)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:o.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:n.integer})},{name:"string.integer"}),G6=CT(/^[\dA-Fa-f]+$/,"hex characters only"),w6=TT.module({root:CT(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:CT(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),YR=CT(/^[A-Z].*$/,"capitalized"),E6=TT.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:YR}),preformatted:YR},{name:"string.capitalize"}),K6=(T)=>{let o=T.replaceAll(/[ -]+/g,""),F=0,A,y,S=!1;for(let f=o.length-1;f>=0;f--){if(A=o.substring(f,f+1),y=Number.parseInt(A,10),S)y*=2,F+=y>=10?y%10+1:y;else F+=y;S=!S}return!!(F%10===0?o:!1)},U6=/^(?: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}))$/,z6=WT({domain:"string",pattern:{meta:"a credit card number",rule:U6.source},predicate:{meta:"a credit card number",predicate:K6}});var Q6=/^([+-]?\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 V6=(T)=>!Number.isNaN(new Date(T).valueOf()),ZR=WT({domain:"string",predicate:{meta:"a parsable date",predicate:V6}}).assertHasKind("intersection"),HR=DR.root.internal.narrow((T,o)=>{let F=Number.parseInt(T),A=QS.epoch(F);if(A instanceof Ho)return o.errors.merge(A),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),D6=TT.module({root:HR,parse:WT({in:HR,morphs:(T)=>new Date(T),declaredOut:n.Date})},{name:"string.date.epoch"}),GR=CT(Q6,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),L6=TT.module({root:GR,parse:WT({in:GR,morphs:(T)=>new Date(T),declaredOut:n.Date})},{name:"string.date.iso"}),C6=TT.module({root:ZR,parse:WT({declaredIn:ZR,in:"string",morphs:(T,o)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return o.error("a parsable date");return F},declaredOut:n.Date}),iso:L6,epoch:D6},{name:"string.date"}),I6=CT(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),wR="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",CF=`(${wR}[.]){3}${wR}`,k6=new RegExp(`^${CF}$`),bT="(?:[0-9a-fA-F]{1,4})",B6=new RegExp(`^((?:${bT}:){7}(?:${bT}|:)|(?:${bT}:){6}(?:${CF}|:${bT}|:)|(?:${bT}:){5}(?::${CF}|(:${bT}){1,2}|:)|(?:${bT}:){4}(?:(:${bT}){0,1}:${CF}|(:${bT}){1,3}|:)|(?:${bT}:){3}(?:(:${bT}){0,2}:${CF}|(:${bT}){1,4}|:)|(?:${bT}:){2}(?:(:${bT}){0,3}:${CF}|(:${bT}){1,5}|:)|(?:${bT}:){1}(?:(:${bT}){0,4}:${CF}|(:${bT}){1,6}|:)|(?::((?::${bT}){0,5}:${CF}|(?::${bT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),N6=TT.module({root:["v4 | v6","@","an IP address"],v4:CT(k6,"an IPv4 address","ipv4"),v6:CT(B6,"an IPv6 address","ipv6")},{name:"string.ip"}),UA="a JSON string",LR=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${UA} (${T})`},p6=WT({meta:UA,domain:"string",predicate:{meta:UA,predicate:(T,o)=>{try{return JSON.parse(T),!0}catch(F){return o.reject({code:"predicate",expected:UA,problem:LR(F)})}}}}),j6=(T,o)=>{if(T.length===0)return o.error({code:"predicate",expected:UA,actual:"empty"});try{return JSON.parse(T)}catch(F){return o.error({code:"predicate",expected:UA,problem:LR(F)})}},x6=TT.module({root:p6,parse:WT({meta:"safe JSON string parser",in:"string",morphs:j6,declaredOut:n.jsonObject})},{name:"string.json"}),ER=CT(/^[a-z]*$/,"only lowercase letters"),b6=TT.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:ER}),preformatted:ER},{name:"string.lower"}),CR=["NFC","NFD","NFKC","NFKD"],Yy=d(CR,(T,o)=>[o,WT({domain:"string",predicate:(F)=>F.normalize(o)===F,meta:`${o}-normalized unicode`})]),VS=d(CR,(T,o)=>[o,WT({in:"string",morphs:(F)=>F.normalize(o),declaredOut:Yy[o]})]),q6=TT.module({root:VS.NFC,preformatted:Yy.NFC},{name:"string.normalize.NFC"}),v6=TT.module({root:VS.NFD,preformatted:Yy.NFD},{name:"string.normalize.NFD"}),P6=TT.module({root:VS.NFKC,preformatted:Yy.NFKC},{name:"string.normalize.NFKC"}),m6=TT.module({root:VS.NFKD,preformatted:Yy.NFKD},{name:"string.normalize.NFKD"}),t6=TT.module({root:"NFC",NFC:q6,NFD:v6,NFKC:P6,NFKD:m6},{name:"string.normalize"}),KR=CT(ay,"a well-formed numeric string"),h6=TT.module({root:KR,parse:WT({in:KR,morphs:(T)=>Number.parseFloat(T),declaredOut:n.number})},{name:"string.numeric"}),UR="a regex pattern",g6=WT({domain:"string",predicate:{meta:UR,predicate:(T,o)=>{try{return new RegExp(T),!0}catch(F){return o.reject({code:"predicate",expected:UR,problem:String(F)})}}},meta:{format:"regex"}}),n6=/^(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-]+)*))?$/,u6=CT(n6,"a semantic version (see https://semver.org/)"),zR=CT(/^\S.*\S$|^\S?$/,"trimmed"),c6=TT.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:zR}),preformatted:zR},{name:"string.trim"}),QR=CT(/^[A-Z]*$/,"only uppercase letters"),i6=TT.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:QR}),preformatted:QR},{name:"string.upper"}),d6=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},VR=WT({domain:"string",predicate:{meta:"a URL string",predicate:d6},meta:{format:"uri"}}),r6=TT.module({root:VR,parse:WT({declaredIn:VR,in:"string",morphs:(T,o)=>{try{return new URL(T)}catch{return o.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),l6=TT.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:CT(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:CT(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:CT(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:CT(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:CT(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:CT(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:CT(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:CT(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),IR=TT.module({root:n.string,alpha:CT(/^[A-Za-z]*$/,"only letters"),alphanumeric:CT(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:G6,base64:w6,capitalize:E6,creditCard:z6,date:C6,digits:CT(/^\d*$/,"only digits 0-9"),email:I6,integer:DR,ip:N6,json:x6,lower:b6,normalize:t6,numeric:h6,regex:g6,semver:u6,trim:c6,upper:i6,url:r6,uuid:l6},{name:"string"});var kR=TT.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}),BR=TT.module({root:n.unknown,any:n.unknown},{name:"unknown"}),s6=TT.module({root:n.jsonObject,stringify:GA("morph",{in:n.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:n.string})},{name:"object.json"}),NR=TT.module({root:n.object,json:s6},{name:"object"});class pR extends yo{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var a6=po(["K",n.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),pR);class jR extends yo{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var e6=po(["T",n.object],["K",n.key])((T)=>T.T.pick(T.K),jR);class xR extends yo{description='omit a set of properties from an object like `Omit(User, "age")`'}var TZ=po(["T",n.object],["K",n.key])((T)=>T.T.omit(T.K),xR);class bR extends yo{description="make all named properties of an object optional like `Partial(User)`"}var oZ=po(["T",n.object])((T)=>T.T.partial(),bR);class qR extends yo{description="make all named properties of an object required like `Required(User)`"}var FZ=po(["T",n.object])((T)=>T.T.required(),qR);class vR extends yo{description='exclude branches of a union like `Exclude("boolean", "true")`'}var AZ=po("T","U")((T)=>T.T.exclude(T.U),vR);class PR extends yo{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var yZ=po("T","U")((T)=>T.T.extract(T.U),PR),mR=TT.module({Exclude:AZ,Extract:yZ,Omit:TZ,Partial:oZ,Pick:e6,Record:a6,Required:FZ});var IF=i$({...kR,...mR,...OR,...$R,string:IR,number:QS,object:NR,unknown:BR},{prereducedAliases:!0,name:"ark"}),gT=IF.export();Object.assign(KA.ambient,gT);KA.typeAttachments={string:gT.string.root,number:gT.number.root,bigint:gT.bigint,boolean:gT.boolean,symbol:gT.symbol,undefined:gT.undefined,null:gT.null,object:gT.object.root,unknown:gT.unknown.root,false:gT.false,true:gT.true,never:gT.never,arrayIndex:gT.Array.index,Key:gT.Key,Record:gT.Record,Array:gT.Array.root,Date:gT.Date};var Eo=Object.assign(IF.type,KA.typeAttachments),SZ=IF.match,fZ=IF.generic,oQ=IF.schema,$Z=IF.define,JZ=IF.declare;function DS(T=Math.random){return T().toString(36).slice(2)}class Zy extends Promise{fate;resolve;reject;done=!1;constructor(T){let o,F;super((A,y)=>{o=A,F=y});this.resolve=o,this.reject=F,this.use(T instanceof Promise?T:new Promise(T))}pass(T,o){if(T===this.fate)this.resolve(o),this.done=!0}fail(T,o){if(T===this.fate)this.reject(o),this.done=!0}use(T){if(T instanceof Promise){let o=T;this.fate=o,o.then((F)=>{this.pass(o,F)},(F)=>{this.fail(o,F)})}else this.resolve(T),this.fate=void 0}}var tR=(T,o,F=ST.STORE)=>{return MF(F,{key:`${T.key}:JSON`,get:({get:A})=>o.toJson(A(T)),set:({set:A},y)=>{A(T,o.fromJson(y))}})};function j(T){while(T.child!==null)T=T.child;return T}class oT{Subscriber;subscribers=new Map;subscribe(T,o){return this.subscribers.set(T,o),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let o=this.subscribers.values();for(let F of o)F(T)}}class r$ extends oT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function OF(T,o,F){let A={key:o.key,type:"atom_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H=o.default,Q={key:O,default:H instanceof Function?H(_):H};if(o.effects)Q.effects=o.effects(_);let E=Lo(Y,Q,R);return S.next({type:"state_creation",token:E}),E},A,{subject:S,install:(_)=>OF(_,o),internalRoles:F});return T.families.set(o.key,$),T.defaults.set(o.key,o.default),A}function hR(T,o){if("mutable"in o)return Hy(T,o);return OF(T,o)}function XF(T,o,F){let A={key:o.key,type:"readonly_selector_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H=Gy(Y,{key:O,get:o.get(_)},R);return S.next({type:"state_creation",token:H}),H},A,{internalRoles:F,subject:S,install:(_)=>XF(_,o),default:(_)=>{return o.get(_)({get:(...R)=>MT(T,...R),find:(...R)=>i(T,...R),json:(R)=>nT(T,R)})}});return T.families.set(o.key,$),A}function LS(T,o){if("set"in o)return wy(T,o);return XF(T,o)}class CS{_buffer;_index=0;constructor(T){let o;if(typeof T==="number")o=T;else o=T.length;this._buffer=Array.from({length:o})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new CS([...this._buffer]);return T._index=this._index,T}}var _Z={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function gR(T,o){let F=AT(o),A=`${T.key}(${F})`,y=_Z[T.type],S={key:A,type:y};return Object.assign(S,{family:{key:T.key,subKey:F}}),Object.assign(S,{counterfeit:!0}),S}function Ko(T){let o={key:T.key,type:T.type};if("family"in T)o.family=T.family;return o}function zA(T){return nR(ST.STORE,T)}function gF(T){return hR(ST.STORE,T)}function l$(...T){if(T.length===2)return MT(ST.STORE,...T);return MT(ST.STORE,...T)}function IS(T,o,F=ST.STORE){return F.joins.set(T.key,new Ey(T,o,F)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function cR(T){return iR(T,ST.STORE)}var s$=(T)=>(o,F,A,y,...S)=>{console[T](`${o} ${F} "${A}" ${y}`,...S)},RZ={error:s$("error"),info:s$("info"),warn:s$("warn")};class a${logLevel;filter;logger;constructor(T,o,F=RZ){this.logLevel=T,this.filter=o,this.logger=F}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}var eQ=Symbol("claim");class dR{store;constructor(T=ST.STORE){this.store=T,rR("root",T)}allocate(T,o,F){return nF(this.store,T,o,F)}fuse(T,o,F){return lR(this.store,T,o,F)}deallocate(T){uF(this.store,T)}claim(T,o,F){return QA(this.store,T,o,F)}}class e${store;realm;constructor(T=ST.STORE){this.store=T,this.realm=new dR(T)}allocate(T,o,F){nF(this.store,T,o,F)}deallocate(T){uF(this.store,T)}claim(T,o,F){QA(this.store,T,o,F)}}function BS(T){return LS(ST.STORE,T)}function aT(T){return"epoch"in T.transactionMeta}function OT(T){return"phase"in T.transactionMeta}var sR=(T)=>{let o=j(T);if(!OT(o)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",o.transactionMeta.update.key,"Aborting transaction"),o.parent.child=null};function XT(T){return T[0].toUpperCase()+T.slice(1)}function TF(T){return T.type.split("_").map(XT).join(" ")}class cF extends Error{constructor(T,o){super(`${TF(T)} ${AT(T.key)} not found in store "${o.config.name}".`)}}function VA(T,o,F){return(...A)=>{let y=JT(T,o);if(y)return y.run(A,F);throw new cF(o,T)}}var NS=(T)=>(o)=>T instanceof Function?T(o):T;var kF=(T,o)=>{if(T.valueMap.has(o.key))return T.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),aR(o,T);switch(o.type){case"selector":case"readonly_selector":return T.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();case"atom":case"mutable_atom":{let F=o.default,A;if(F instanceof Function)A=F();else A=F;return T.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",A),A}}};var eR=(T,o)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",o.type,o.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:o},T.logger.info("\u2B55",o.type,o.key,`operation start in store "${T.config.name}"${!OT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},TW=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},oW=(T,o)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",o,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(o)},DA=(T,o)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",o,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(o)};var FW=(T,o,F)=>{switch(o.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",F.newValue,") subscribers:",o.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":T.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(F)};var TJ=(T,o)=>{let F=j(T),A=F.selectorAtoms.getRelatedKeys(o.key);if(F.logger.info("\uD83E\uDDF9",o.type,o.key,A?`evicting ${A.size} states downstream:`:"no downstream states",A??"to evict"),A){if(F.operation.open)F.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let y of A){if(oW(F,y))continue;AW(y,F),DA(F,y)}}};var yW=(T,o,F)=>{let A=kF(T,o),y=A;if(o.type==="mutable_atom"&&OT(T)){let{parent:f}=T;y=Uy(T,o,f)}if(y=NS(F)(y),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",y),y=jo(T,o.key,y,o.subject),fW(T,o.key))$W(T,o.key);DA(T,o.key),TJ(T,o);let S={oldValue:A,newValue:y};if(!OT(T)){FW(T,o,S);return}if(T.on.transactionApplying.state===null){let{key:f}=o;if(SW(S.newValue))return;let $={type:"atom_update",key:f,...S};if(o.family)$.family=o.family;T.transactionMeta.update.updates.push($),T.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")}else if(o.key.startsWith("*")){let f=o.key.slice(1),$=T.atoms.get(f),_=T.valueMap.get(f);if($.type==="mutable_atom"&&OT(T)){let{parent:R}=T;_=Uy(T,$,R)}if(_.do(S.newValue)===null)TJ(T,$)}};var pS=(T,o,F)=>{switch(o.type){case"atom":case"mutable_atom":yW(T,o,F);break;case"selector":o.set(F);break}};function JW(T,o){if(o.family){let F=T.families.get(o.family.key);if(F)return F}}function jT(T,...o){let F,A,y,S;if(o.length===2){if(F=o[0],S=o[1],A=JW(T,F)??null,A)y=F.family?rT(F.family.subKey):null,F=i(T,A,y)}else A=o[0],y=o[1],S=o[2],F=i(T,A,y);if("counterfeit"in F&&"family"in F){let _=F.family.subKey,J=T.disposalTraces.buffer.find((R)=>R?.key===_);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,J?`This state was previously disposed:
48
- ${J.trace}`:"No previous disposal trace was found.");return}let f=eR(T,F);if(f){let _=T.on.operationClose.subscribe(`waiting to set "${F.key}" at T-${f}`,()=>{_(),T.logger.info("\uD83D\uDFE2",F.type,F.key,`resuming deferred setState from T-${f}`),jT(T,F,S)});return}let $=JT(T,F);pS(T,$,S),TW(T)}function jS(T,o,F){let{key:A,newValue:y,oldValue:S}=o,f=T==="newValue"?y:S,$={key:A,type:"atom"};if(o.family)Object.assign($,{family:o.family});jT(F,$,f)}function _W(T){let{stack:o}=T;if(o)return`
49
- `+o.split(`
50
- `)?.slice(1)?.join(`
51
- `);return""}function rR(T,o=ST.STORE){let F={key:T,stringKey:AT(T),dependsOn:"any"};return o.molecules.set(AT(T),F),T}function nF(T,o,F,A="any"){let y=o,S=AT(F),f=[],$=j(T);if(Array.isArray(y))for(let R of y){let O=AT(R);if($.molecules.get(O))T.moleculeGraph.set(O,S,{source:O});else f.push(O)}else{let R=AT(y);if($.molecules.get(R))T.moleculeGraph.set(R,S,{source:R});else f.push(R)}if(f.length===0)$.molecules.set(S,{key:F,stringKey:S,dependsOn:A});let _={type:"molecule_creation",key:F,provenance:y};if(OT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push(_);else $.on.moleculeCreation.next(_);for(let R of f){let O=T.disposalTraces.buffer.find((Y)=>Y?.key===R);T.logger.error("\u274C","molecule",F,"allocation failed:",`Could not allocate to ${R} in store "${T.config.name}".`,O?`
52
- ${R} was most recently disposed
53
- ${O.trace}`:`No previous disposal trace for ${R} was found.`)}return F}function lR(T,o,F,A){let y=`T$--${o}==${F}++${A}`;return nF(T,[F,A],y,"all"),y}function uF(T,o){let F=AT(o),A=T.molecules.get(F);if(!A){let H=T.disposalTraces.buffer.find((Q)=>Q?.key===F);T.logger.error("\u274C","molecule",o,"deallocation failed:",`Could not find allocation for ${F} in store "${T.config.name}".`,H?`
54
- This state was most recently deallocated
55
- ${H.trace}`:`No previous disposal trace for ${F} was found.`);return}let y=T.moleculeJoins.getRelatedKeys(A.key);if(y)for(let H of y){let Q=T.joins.get(H);if(Q)Q.relations.delete(A.key),Q.molecules.delete(A.stringKey)}T.moleculeJoins.delete(A.stringKey);let S=[],f=[],$={type:"molecule_disposal",key:A.key,values:f,provenance:S},_=j(T);_.molecules.delete(F);let J=OT(_)&&_.transactionMeta.phase==="building";if(J)_.transactionMeta.update.updates.push($);let R=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:A.stringKey});if(R)for(let[H,{source:Q}]of R)if(Q===A.stringKey){let E=rT(H);uF(T,E)}else S.push(Q);let O=_.moleculeData.getRelatedKeys(A.stringKey);if(O)for(let H of O){let Q=_.families.get(H),E=i(T,Q,A.key);f.push([Q.key,E]),iF(T,E)}if(_.moleculeGraph.delete(A.stringKey),_.moleculeJoins.delete(A.stringKey),_.moleculeData.delete(A.stringKey),!J)_.on.moleculeDisposal.next($);_.molecules.delete(A.stringKey);let Y=_W(new Error);T.disposalTraces.add({key:F,trace:Y})}function QA(T,o,F,A){let y=AT(F),S=j(T),f=S.molecules.get(y);if(!f){let Y=T.disposalTraces.buffer.find((H)=>H?.key===y);return T.logger.error("\u274C","molecule",F,"claim failed:",`Could not allocate to ${y} in store "${T.config.name}".`,Y?`
56
- ${y} was most recently disposed
57
- ${Y.trace}`:`No previous disposal trace for ${y} was found.`),F}let $=AT(o),_=S.molecules.get($);if(!_){let Y=T.disposalTraces.buffer.find((H)=>H?.key===$);return T.logger.error("\u274C","molecule",F,"claim failed:",`Could not allocate to ${$} in store "${T.config.name}".`,Y?`
58
- ${$} was most recently disposed
59
- ${Y.trace}`:`No previous disposal trace for ${$} was found.`),F}let J=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:f.stringKey}).filter(([,{source:Y}])=>Y!==y).map(([Y])=>rT(Y));if(A)S.moleculeGraph.delete(y);S.moleculeGraph.set({upstreamMoleculeKey:_.stringKey,downstreamMoleculeKey:f.stringKey},{source:_.stringKey});let R={type:"molecule_transfer",key:f.key,from:J,to:[_.key]};if(OT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push(R);return F}function oJ(T,o,F){switch(o){case"newValue":{RW(T,F);break}case"oldValue":{iF(F,T.token);break}}}function FJ(T,o,F){switch(o){case"newValue":{iF(F,T.token);break}case"oldValue":{if(RW(T,F),T.subType==="atom")F.valueMap.set(T.token.key,T.value);break}}}function RW(T,o){let{family:F}=T.token;if(F){let A=o.families.get(F.key);if(A)i(o,A,rT(F.subKey))}}function WW(T,o,F){switch(o){case"newValue":nF(F,T.provenance,T.key);break;case"oldValue":uF(F,T.key);break}}function MW(T,o,F){switch(o){case"newValue":uF(F,T.key);break;case"oldValue":{let A=T.provenance.map(rT);nF(F,A,T.key);for(let[y,S]of T.values){let f=F.families.get(y);if(f){i(F,f,T.key);let $=`${y}(${AT(T.key)})`;F.valueMap.set($,S)}}}break}}function OW(T,o,F){switch(o){case"newValue":{let A=T.to.length===1?T.to[0]:T.to;QA(F,A,T.key,"exclusive")}break;case"oldValue":{let A=T.from.length===1?T.from[0]:T.from;QA(F,A,T.key,"exclusive")}break}}function xS(T,o,F){let A=T==="newValue"?o.updates:[...o.updates].reverse();for(let y of A)switch(y.type){case"atom_update":case"selector_update":jS(T,y,F);break;case"state_creation":oJ(y,T,F);break;case"state_disposal":FJ(y,T,F);break;case"molecule_creation":WW(y,T,F);break;case"molecule_disposal":MW(y,T,F);break;case"molecule_transfer":OW(y,T,F);break;case"transaction_update":xS(T,y,F);break}}function AJ(T,o){return T.transactionMeta.actionContinuities.getRelatedKey(o)}function WZ(T,o){return T.transactionMeta.epoch.get(o)}function XW(T,o){if(!aT(T))return;let A=AJ(T,o);if(A===void 0)return;return WZ(T,A)}function YW(T,o,F){if(aT(T)&&o)T.transactionMeta.epoch.set(o,F)}function ZW(T,o,F){if(!aT(T))return;let y=AJ(T,o);if(y!==void 0)T.transactionMeta.epoch.set(y,F)}var HW=(T,o)=>{let F=j(o),{parent:A}=F;if(A===null||!OT(F)||F.transactionMeta?.phase!=="building"){o.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}F.transactionMeta.phase="applying",F.transactionMeta.update.output=T,A.child=null,A.on.transactionApplying.next(F.transactionMeta);let{updates:y}=F.transactionMeta.update;if(o.logger.info("\uD83D\uDEC4","transaction",F.transactionMeta.update.key,`Applying transaction with ${y.length} updates:`,y),xS("newValue",F.transactionMeta.update,A),aT(A))ZW(A,F.transactionMeta.update.key,F.transactionMeta.update.epoch),JT(o,{key:F.transactionMeta.update.key,type:"transaction"})?.subject.next(F.transactionMeta.update),o.logger.info("\uD83D\uDEEC","transaction",F.transactionMeta.update.key,"Finished applying transaction.");else if(OT(A))A.transactionMeta.update.updates.push(F.transactionMeta.update);A.on.transactionApplying.next(null)};function GW(T,o,F){if(!aT(T))return;let{epoch:y,actionContinuities:S}=T.transactionMeta;if(S.set(o,F),!y.has(o))y.set(o,-1)}function wW(T){return{store:T}}function MT(T,...o){let F,A,y;if(o.length===1)F=o[0];else A=o[0],y=o[1],F=i(T,A,y);if("counterfeit"in F&&"family"in F){A=T.families.get(F.family.key);let S=F.family.subKey,f=T.disposalTraces.buffer.find(($)=>$?.key===S);switch(T.logger.error("\u274C",F.type,F.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,f?`This state was previously disposed:
60
- ${f.trace}`:"No previous disposal trace was found."),A.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(A.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(A.key))return T.defaults.get(F.family.key);let $=JT(T,A).default(S);return T.defaults.set(A.key,$),$}}}return kF(T,JT(T,F))}class uT{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,o)=>`${T}:${o}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,o){let F=this.relations.get(T),A=this.relations.get(o);if(F)F.add(o);else F=new Set([o]),this.relations.set(T,F);if(A)A.add(T);else A=new Set([T]),this.relations.set(o,A)}deleteRelation(T,o){let F=this.relations.get(T);if(F){if(F.delete(o),F.size===0)this.relations.delete(T);let A=this.relations.get(o);if(A){if(A.delete(T),A.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(T,o){this.relations.set(T,new Set(o));for(let F of o){let A=new Set().add(T);this.relations.set(F,A)}}replaceRelationsSafely(T,o){let F=this.relations.get(T),A=this.isAType?.(T)?T:void 0,y=A===void 0?T:void 0;if(F)for(let S of F){A??=S,y??=S;let f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(T);this.contents.delete(this.makeContentKey(A,y))}}this.relations.set(T,new Set(o));for(let S of o){let f=this.relations.get(S);if(f)f.add(T);else f=new Set().add(T),this.relations.set(S,f)}}getContentInternal(T){return this.contents.get(T)}setContent(T,o){this.contents.set(T,o)}deleteContent(T){this.contents.delete(T)}constructor(T,o){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!o?.externalStore)this.relations=new Map(T.relations?.map(([F,A])=>[F,new Set(A)])),this.contents=new Map(T.contents);if(this.isAType=o?.isAType??null,this.isBType=o?.isBType??null,this.isContent=o?.isContent??null,o?.makeContentKey)this.makeContentKey=o.makeContentKey;if(o?.externalStore){let F=o.externalStore;if(this.has=(A,y)=>F.has(A,y),this.addRelation=(A,y)=>{F.addRelation(A,y)},this.deleteRelation=(A,y)=>{F.deleteRelation(A,y)},this.replaceRelationsSafely=(A,y)=>{F.replaceRelationsSafely(A,y)},this.replaceRelationsUnsafely=(A,y)=>{F.replaceRelationsUnsafely(A,y)},this.getRelatedKeys=(A)=>F.getRelatedKeys(A),F.getContent)this.getContentInternal=(A)=>{return F.getContent(A)},this.setContent=(A,y)=>{F.setContent(A,y)},this.deleteContent=(A)=>{F.deleteContent(A)};for(let[A,y]of T.relations??[]){let S=this.isAType?.(A)?A:void 0,f=S===void 0?A:void 0;for(let $ of y)S??=$,f??=$,this.addRelation(S,f)}for(let[A,y]of T.contents??[])this.setContent(A,y)}if(o?.warn)this.warn=o.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,o])=>[T,[...o]]),contents:[...this.contents.entries()]}}set(...T){let o,F,A;switch(T.length){case 1:{let y=T[0];o=y[this.a],F=y[this.b],A=void 0;break}case 2:{let y=T[0];if(typeof y==="string")[o,F]=T;else o=y[this.a],F=y[this.b],A=T[1];break}default:{o=T[0],F=T[1],A=T[2];break}}switch(this.cardinality){case"1:1":{let y=this.getRelatedKey(o);if(y&&y!==F)this.delete(o,y)}case"1:n":{let y=this.getRelatedKey(F);if(y&&y!==o)this.delete(y,F)}break;case"n:n":}if(A){let y=this.makeContentKey(o,F);this.setContent(y,A)}return this.addRelation(o,F),this}delete(T,o){o=typeof o==="string"?o:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof o==="string"){let A=this.getRelatedKeys(o);if(A)for(let y of A)this.delete(y,o)}if(typeof F==="string"&&o===void 0){let A=this.getRelatedKeys(F);if(A)for(let y of A)this.delete(F,y)}if(typeof F==="string"&&typeof o==="string"){this.deleteRelation(F,o);let A=this.makeContentKey(F,o);this.deleteContent(A)}return this}getRelatedKey(T){let o=this.getRelatedKeys(T);if(o){if(o.size>1)this.warn?.(`${o.size} related keys were found for key "${T}": (${[...o].map((A)=>`"${A}"`).join(", ")}). Only one related key was expected.`);let F;for(let A of o){F=A;break}return F}}replaceRelations(T,o,F){let A=!Array.isArray(o),y=A?Object.keys(o):o;if(F?.reckless)this.replaceRelationsUnsafely(T,y);else this.replaceRelationsSafely(T,y);if(A)for(let S of y){let f=this.makeContentKey(T,S),$=o[S];this.setContent(f,$)}return this}getContent(T,o){let F=this.makeContentKey(T,o);return this.getContentInternal(F)}getRelationEntries(T){let o=T[this.a],F=T[this.b];if(o!==void 0&&F===void 0){let A=this.getRelatedKeys(o);if(A)return[...A].map((y)=>{return[y,this.getContent(o,y)]})}if(o===void 0&&F!==void 0){let A=this.getRelatedKeys(F);if(A)return[...A].map((y)=>{return[y,this.getContent(y,F)]})}return[]}has(T,o){if(o)return this.getRelatedKeys(T)?.has(o)??!1;return this.relations.has(T)}}class xo extends Map{deleted=new Set;source;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,o){return this.deleted.delete(T),super.set(T,o)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var EW=(T,o,F,A)=>{let y=j(T),S={parent:y,child:null,on:y.on,loggers:y.loggers,logger:y.logger,config:y.config,atoms:new xo(y.atoms),atomsThatAreDefault:new Set(y.atomsThatAreDefault),families:new xo(y.families),joins:new xo(y.joins),operation:{open:!1},readonlySelectors:new xo(y.readonlySelectors),timelines:new xo(y.timelines),timelineTopics:new uT(y.timelineTopics.toJSON()),trackers:new Map,transactions:new xo(y.transactions),selectorAtoms:new uT(y.selectorAtoms.toJSON()),selectorGraph:new uT(y.selectorGraph.toJSON(),{makeContentKey:(...J)=>J.sort().join(":")}),selectors:new xo(y.selectors),valueMap:new xo(y.valueMap),defaults:y.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new xo(y.molecules),moleculeGraph:new uT(y.moleculeGraph.toJSON(),{makeContentKey:y.moleculeGraph.makeContentKey}),moleculeData:new uT(y.moleculeData.toJSON(),{makeContentKey:y.moleculeData.makeContentKey}),moleculeJoins:new uT(y.moleculeJoins.toJSON(),{makeContentKey:y.moleculeJoins.makeContentKey}),miscResources:new xo(y.miscResources)},f=XW(T,o),$={phase:"building",update:{type:"transaction_update",key:o,id:A,epoch:f===void 0?Number.NaN:f+1,updates:[],params:F,output:void 0},toolkit:{get:(...J)=>MT(_,...J),set:(...J)=>{jT(_,...J)},run:(J,R=DS())=>VA(_,J,R),find:(...J)=>i(T,...J),json:(J)=>nT(_,J),dispose:(...J)=>{iF(_,...J)},env:()=>wW(_)}},_=Object.assign(S,{transactionMeta:$});return y.child=_,T.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",F),_};function yJ(T,o){let F={key:o.key,type:"transaction",run:(S,f)=>{let $=EW(T,o.key,S,f);try{let _=j(T),{toolkit:J}=$.transactionMeta,R=o.do(J,...S);return HW(R,_),R}catch(_){throw sR(A),T.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",_),_}},install:(S)=>yJ(S,o),subject:new oT},A=j(T);A.transactions.set(F.key,F);let y=Ko(F);return T.on.transactionCreation.next(y),y}function zy(T){return yJ(ST.STORE,T)}class KW{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new uT({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new uT({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new uT({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new uT({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new CS(100);molecules=new Map;moleculeJoins=new uT({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new uT({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new uT({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new oT,atomDisposal:new oT,selectorCreation:new oT,selectorDisposal:new oT,timelineCreation:new oT,transactionCreation:new oT,transactionApplying:new r$(null),operationClose:new oT,moleculeCreation:new oT,moleculeDisposal:new oT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new a$("warn",(T,o,F)=>!BF(F))];logger={error:(...T)=>{for(let o of this.loggers)o.error(...T)},info:(...T)=>{for(let o of this.loggers)o.info(...T)},warn:(...T)=>{for(let o of this.loggers)o.warn(...T)}};constructor(T,o=null){if(this.config={...o?.config,...T},o!==null){if(this.valueMap=new Map(o?.valueMap),this.operation={...o?.operation},aT(o))this.transactionMeta={epoch:new Map(o?.transactionMeta.epoch),actionContinuities:new uT(o?.transactionMeta.actionContinuities.toJSON())};for(let[,A]of o.families){if(A.internalRoles?.includes("mutable")||A.internalRoles?.includes("join"))continue;A.install(this)}let F=new Set;for(let[,A]of o.atoms){if(F.has(A.key))continue;if(A.install(this),A.type==="mutable_atom"){let y=nT(o,A),S=YF(A);F.add(y.key),F.add(S.key)}}for(let[,A]of o.readonlySelectors)A.install(this);for(let[,A]of o.selectors){if(F.has(A.key))continue;A.install(this)}for(let[,A]of o.transactions)A.install(this);for(let[,A]of o.timelines)A.install(this)}}}var ST={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new KW({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function JT(T,o){let F,A=T;while(A!==null){switch(o.type){case"atom":case"mutable_atom":F=A.atoms.get(o.key);break;case"selector":F=A.selectors.get(o.key);break;case"readonly_selector":F=A.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":F=A.families.get(o.key);break;case"timeline":F=A.timelines.get(o.key);break;case"transaction":F=A.transactions.get(o.key);break}if(F)return F;A=A.child}throw new cF(o,T)}function UW(T,o,F){let A=T.families.get(o.key);if(A===void 0)throw new cF(o,T);let y=A(F),S=j(T);if(y.family){if(aT(S))switch(y.type){case"atom":case"mutable_atom":T.on.atomCreation.next(y);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(y);break}else if(OT(S)&&S.on.transactionApplying.state===null)S.transactionMeta.update.updates.push({type:"state_creation",token:y})}return y}function zW(T,o,F){let A=AT(F),y=`${o.key}(${A})`,S=j(T),f;switch(o.type){case"atom_family":case"mutable_atom_family":f=S.atoms.get(y);break;case"selector_family":f=S.selectors.get(y);break;case"readonly_selector_family":f=S.readonlySelectors.get(y);break}if(f)return Ko(f);return f}function i(T,o,F){let A=zW(T,o,F);if(A)return A;let y=AT(F),S=T.molecules.get(y);if(!S&&T.config.lifespan==="immortal"){let f=gR(o,F);return T.logger.error("\u274C",f.type,f.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),f}if(A=UW(T,o,F),S)j(T).moleculeData.set(y,o.key);return A}function iF(T,...o){let F;if(o.length===1)F=o[0];else{let A=o[0],y=o[1];F=i(T,A,y)}try{JT(T,F)}catch(A){T.logger.error("\u274C",F.type,F.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(F.type){case"atom":case"mutable_atom":SJ(T,F);break;case"selector":case"readonly_selector":QW(T,F);break}}var bS=(T,o)=>j(T).atoms.has(o),MZ=(T,o)=>j(T).selectors.has(o),OZ=(T,o)=>j(T).readonlySelectors.has(o),VW=(T,o)=>bS(T,o)||MZ(T,o)||OZ(T,o);var qS=(T,o)=>{return j(o).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([A,{source:y}])=>y!==T).map(([A,{source:y}])=>y).filter((A)=>VW(o,A))};var fJ=(T,o,F)=>{let A=[],y=qS(T,F);while(y.length>0){let S=y.shift();if(o.has(S))continue;if(o.add(S),!bS(F,S))y.push(...qS(S,F));else if(!A.includes(S))A.push(S)}return A},DW=(T,o)=>{let F=T.key,A=qS(F,o),y=new Set;return A.flatMap((S)=>bS(o,S)?S:fJ(S,y,o))};var LW=(T,o,F,A)=>{let y=j(A);if(o.type==="atom"||o.type==="mutable_atom")y.selectorAtoms.set({selectorKey:T,atomKey:o.key}),A.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${o.key}"`);else{let S=fJ(o.key,F,A);A.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${S.map((f)=>`"${f}"`).join(", ")} ]`);for(let f of S)y.selectorAtoms=y.selectorAtoms.set({selectorKey:T,atomKey:f})}F.add(o.key)};var vS=(T,o,F)=>({get:(...A)=>{let y=j(F),S;if(A.length===2){let[_,J]=A;S=i(F,_,J)}else[S]=A;let f=JT(F,S),$=kF(F,f);return F.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${S.key}" =`,$,")"),y.selectorGraph.set({upstreamSelectorKey:S.key,downstreamSelectorKey:T},{source:S.key}),LW(T,S,o,F),$},set:(...A)=>{let y,S;if(A.length===2)y=A[0],S=A[1];else{let _=A[0],J=A[1];S=A[2],y=i(F,_,J)}let f=j(F),$=JT(f,y);pS(f,$,S)},find:(...A)=>i(F,...A),json:(A)=>nT(F,A)});var Gy=(T,o,F)=>{let A=j(T),y=new oT,S=new Set,{get:f,find:$,json:_}=vS(o.key,S,A),J=()=>{let H=o.get({get:f,find:$,json:_});return jo(j(T),o.key,H,y),S.clear(),H},R={...o,subject:y,install:(H)=>Gy(H,o,F),get:J,type:"readonly_selector",...F&&{family:F}};A.readonlySelectors.set(o.key,R);let O=J();T.logger.info("\u2728",R.type,R.key,"=",O);let Y={key:o.key,type:"readonly_selector"};if(F)Y.family=F;return Y};var Qy=(T,o,F)=>{let A=j(T),y=new oT,S=new Set,f=vS(o.key,S,A),{find:$,get:_,json:J}=f,R={find:$,get:_,json:J},O=(B=o.get,p=j(T))=>{let v=B(R);return jo(p,o.key,v,y),S.clear(),v},H={...o,subject:y,install:(B)=>Qy(B,o,F),get:O,set:(B)=>{let p=j(T),v=O(o.get,p),h=NS(B)(v);if(T.logger.info("\uD83D\uDCDD","selector",o.key,"set (",v,"->",h,")"),jo(p,o.key,h,y),DA(p,o.key),aT(p))y.next({newValue:h,oldValue:v});o.set(f,h)},type:"selector",...F&&{family:F}};A.selectors.set(o.key,H);let Q=O();T.logger.info("\u2728",H.type,H.key,"=",Q);let E={key:o.key,type:"selector"};if(F)E.family=F;return E};function MF(T,o){if("set"in o){let y=Qy(T,o,void 0);return T.on.selectorCreation.next(y),y}let A=Gy(T,o,void 0);return T.on.selectorCreation.next(A),A}function QW(T,o){let F=j(T),{key:A}=o,y=JT(F,o);if(!y.family)T.logger.error("\u274C","selector",A,"Standalone selectors cannot be disposed.");else{if(F.molecules.get(y.family.subKey))F.moleculeData.delete(y.family.subKey,y.family.key);let f;switch(o.type){case"selector":F.selectors.delete(A),f={key:y.family.key,type:"selector_family"},JT(T,f).subject.next({type:"state_disposal",subType:"selector",token:o});break;case"readonly_selector":F.readonlySelectors.delete(A),f={key:y.family.key,type:"readonly_selector_family"},JT(T,f).subject.next({type:"state_disposal",subType:"selector",token:o});break}if(F.valueMap.delete(A),F.selectorAtoms.delete(A),F.selectorGraph.delete(A),T.logger.info("\uD83D\uDD25",o.type,A,"deleted"),OT(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:o});else T.on.selectorDisposal.next(o)}}function wy(T,o,F){let A={key:o.key,type:"selector_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H=Qy(Y,{key:O,get:o.get(_),set:o.set(_)},R);return S.next({type:"state_creation",token:H}),H},A,{internalRoles:F,subject:S,install:(_)=>wy(_,o),default:(_)=>{return o.get(_)({get:(...R)=>MT(T,...R),find:(...R)=>i(T,...R),json:(R)=>nT(T,R)})}});return T.families.set(o.key,$),A}function CW(T,o,F){return wy(T,{key:`${o.key}:JSON`,get:(y)=>({get:S})=>{let f=S(o,y);return F.toJson(f)},set:(y)=>({set:S},f)=>{S(o,y,F.fromJson(f))}},["mutable","json"])}var rT=(T)=>JSON.parse(T),AT=(T)=>JSON.stringify(T),WI=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var IW=(T,o)=>{let F=j(T);if(F.operation.open)return F.operation.prev.get(o.key);return F.valueMap.get(o.key)};var _J=(T,o)=>{let F=j(T);return DW(o,T).map((y)=>{let S=F.atoms.get(y);if(S===void 0)throw new Error(`Atom "${y}", a dependency of selector "${o.key}", not found in store "${T.config.name}".`);return S.subject.subscribe(`${o.type}:${o.key}`,(f)=>{T.logger.info("\uD83D\uDCE2",o.type,o.key,"root",y,"went",f.oldValue,"->",f.newValue);let $=IW(F,o),_=kF(F,o);T.logger.info("\u2728",o.type,o.key,"went",$,"->",_),o.subject.next({newValue:_,oldValue:$})})})};function fo(T,o,F,A){function y(O){if(T.operation.open){let Y=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Y(),A(O)})}else A(O)}let S=JT(T,o);T.logger.info("\uD83D\uDC40",S.type,S.key,`Adding subscription "${F}"`);let f=S.type==="selector"||S.type==="readonly_selector",$=null,_=y;if(f)$=_J(T,S),_=(O)=>{if($)$.length=0,$.push(..._J(T,S));y(O)};let J=S.subject.subscribe(F,_);return()=>{if(T.logger.info("\uD83D\uDE48",S.type,S.key,`Removing subscription "${F}"`),J(),$)for(let O of $)O()}}var $J=(T,o,F,A)=>{let y=JT(T,o);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${F}"`);let S=y.subject.subscribe(F,A);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${F}" from timeline`),S()}};var JJ=(T,o,F,A)=>{let y=JT(T,o);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${F}"`);let S=y.subject.subscribe(F,A);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${F}"`),S()}};class dF{Update;initializeState(T,o){let F=`*${T.key}`;o.atoms.delete(F),o.valueMap.delete(F);let A=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,y=Lo(o,{key:F,default:null},A);if(o.parent?.valueMap.has(F)){let S=o.parent.valueMap.get(F);o.valueMap.set(F,S)}return y}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,o,F){let A=`tracker:${F.config.name}:${OT(F)?F.transactionMeta.update.key:"main"}:${T.key}`,y=MT(F,T);this.unsubscribeFromInnerValue=y.subscribe(A,(S)=>{jT(F,o,S)}),this.unsubscribeFromState=fo(F,T,A,(S)=>{if(S.newValue!==S.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=S.newValue.subscribe(A,(f)=>{jT(F,o,f)})})}updateCore(T,o,F){let A=`tracker:${F.config.name}:${OT(F)?F.transactionMeta.update.key:"main"}:${T.key}`;fo(F,o,A,({newValue:y,oldValue:S})=>{let f=F.timelineTopics.getRelatedKey(o.key);if(f){if(F.timelines.get(f)?.timeTraveling){let J=$J(F,{key:f,type:"timeline"},A,(R)=>{J(),jT(F,T,(O)=>{if(R==="redo"&&y)O.do(y);else if(R==="undo"&&S)O.undo(S);return O})});return}}let $=F.on.operationClose.subscribe(A,()=>{$();let _=MT(F,T),J=y===null?-1:_.getUpdateNumber(y),R=J-_.cacheUpdateNumber;if(y&&R===1)jT(F,T,(O)=>(O.do(y),O));else F.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${_.cacheUpdateNumber+1}, but got ${J}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,o){this.mutableState=T;let F=j(o);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}function Vy(T,o,F){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let A=j(T),y=A.atoms.get(o.key);if(y&&y.type==="mutable_atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Ko(y);let S=new oT,f={...o,type:"mutable_atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),Vy(J,o,F)},subject:S};if(F)f.family=F;let $=o.default();A.atoms.set(f.key,f),PS(T,o.key),jo(A,o.key,$,S);let _=Ko(f);if(o.effects){let J=0,R=[];for(let O of o.effects){let Y=O({setSelf:(H)=>{jT(T,_,H)},onSet:(H)=>fo(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}f.cleanup=()=>{for(let O of R)O()}}if(new dF(_,T),!F)tR(_,o,T);return _}class RJ{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(T,o){let F=OF(o,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=JT(o,F),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(A)=>{let{type:y,token:S}=A;if(S.family){let f=rT(S.family.subKey);switch(y){case"state_creation":this.trackers.set(f,new dF(S,o));break;case"state_disposal":{let $=this.trackers.get(f);if($)$[Symbol.dispose](),this.trackers.delete(f)}break}}})}}function Hy(T,o,F){let A={key:o.key,type:"mutable_atom_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H={key:O,default:()=>o.default(_),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)H.effects=o.effects(_);let Q=Vy(Y,H,R);return S.next({type:"state_creation",token:Q}),Q},A,{subject:S,install:(_)=>Hy(_,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:F});return T.families.set(o.key,$),CW(T,$,o),new RJ($,T),A}var WJ=(T,o)=>{let F=j(o),A=`${T.key}:JSON`;return F.families.get(A)};var nT=(T,o)=>{if(o.family){let A=j(T),S={key:`${o.family.key}:JSON`,type:"selector_family"},f=JT(A,S),$=JSON.parse(o.family.subKey);return i(T,f,$)}return{type:"selector",key:`${o.key}:JSON`}};var YF=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function SW(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function Uy(T,o,F){let A=F.valueMap.get(o.key),y=T.valueMap.get(o.key);if(A!==y)return y;if(A===void 0)return o.default();F.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let S=o.toJson(A),f=o.fromJson(S);return T.valueMap.set(o.key,f),new dF(o,F),f}function jo(T,o,F,A){let y=T.valueMap.get(o);if(y instanceof Zy)y.use(F);if(F instanceof Promise){let S=new Zy(F);return T.valueMap.set(o,S),S.then((f)=>{jo(T,o,f,A),A.next({newValue:f,oldValue:S})}).catch((f)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",f)}),S}return T.valueMap.set(o,F),F}var aR=(T,o)=>{let F=o.valueMap.get(T.key);if(T.type==="mutable_atom"&&OT(o)){let{parent:A}=o;F=Uy(o,T,A)}return F},AW=(T,o)=>{let F=o.valueMap.get(T);if(F instanceof Zy){let A=F,y=o.selectors.get(T)??o.readonlySelectors.get(T);if(y)A.use(y.get());return}if(o.operation.open)o.operation.prev.set(T,F);o.valueMap.delete(T),o.logger.info("\uD83D\uDDD1","state",T,"evicted")};var fW=(T,o)=>{return j(T).atomsThatAreDefault.has(o)},PS=(T,o)=>{let F=j(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(o)},$W=(T,o)=>{let F=j(T);F.atomsThatAreDefault=new Set(j(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(o)};function Lo(T,o,F){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let A=j(T),y=A.atoms.get(o.key);if(y&&y.type==="atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Ko(y);let S=new oT,f={...o,type:"atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),Lo(J,o,F)},subject:S};if(F)f.family=F;let $=o.default;if(o.default instanceof Function)$=o.default();A.atoms.set(f.key,f),PS(T,o.key),jo(A,o.key,$,S);let _=Ko(f);if(o.effects){let J=0,R=[];for(let O of o.effects){let Y=O({setSelf:(H)=>{jT(T,_,H)},onSet:(H)=>fo(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}f.cleanup=()=>{for(let O of R)O()}}return _}function nR(T,o){if("mutable"in o){let y=Vy(T,o,void 0);return T.on.atomCreation.next(y),y}let A=Lo(T,o,void 0);return T.on.atomCreation.next(A),A}function SJ(T,o){let F=j(T),{key:A,family:y}=o,S=JT(F,o);if(!y)T.logger.error("\u274C","atom",A,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=T.valueMap.get(S.key),$=JT(T,{key:y.key,type:"atom_family"}),_={type:"state_disposal",subType:"atom",token:o,value:f};$.subject.next(_);let J=OT(F);if(F.atoms.delete(A),F.valueMap.delete(A),F.selectorAtoms.delete(A),F.atomsThatAreDefault.delete(A),T.timelineTopics.delete(A),o.type==="mutable_atom"){let R=YF(o);SJ(T,R),T.trackers.delete(A)}if(T.logger.info("\uD83D\uDD25","atom",A,"deleted"),J&&F.transactionMeta.phase==="building"){let R=F.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([H])=>H===S.family?.key)))F.transactionMeta.update.updates.push(_)}else T.on.atomDisposal.next(o)}}class cT extends Set{mode="record";subject=new oT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,o=0){super(T);if(T instanceof cT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let o=new cT(T.members,T.cacheLimit);return o.cache=T.cache,o.cacheIdx=T.cacheIdx,o.cacheUpdateNumber=T.cacheUpdateNumber,o}add(T){let o=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${AT(T)}`);return o}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let o=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${AT(T)}`);return o}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new cT(this);let o=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let A of this.transactionUpdates)this.doStep(A);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,o){return this.subject.subscribe(T,o)}subscribe(T,o){return this.subject.subscribe(T,(F)=>{o(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let o=T.indexOf(":"),F=T.substring(0,o),A=T.substring(o+1);switch(F){case"add":this.add(JSON.parse(A));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(A));break;case"tx":for(let y of A.split(";"))this.doStep(y)}}getUpdateNumber(T){let o=T.indexOf("=");return Number(T.substring(0,o))}do(T){let o=T.indexOf("="),F=Number(T.substring(0,o)),A=F-this.cacheUpdateNumber;if(A>0){if(A===1){this.mode="playback";let S=T.substring(o+1);return this.doStep(S),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(A)<this.cacheLimit){let S=this.cacheIdx+A;if(this.cache[S]===T)return null;this.mode="playback";let $=!1;while(!$){this.cacheIdx%=this.cacheLimit;let J=this.cache[this.cacheIdx];if(this.cacheIdx--,!J)return"OUT_OF_RANGE";this.undo(J),$=this.cacheIdx===S-1}let _=T.substring(o+1);return this.doStep(_),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let o=T.indexOf(":"),F=T.substring(0,o),A=T.substring(o+1);switch(F){case"add":this.delete(JSON.parse(A));break;case"del":this.add(JSON.parse(A));break;case"clear":{let y=JSON.parse(A);for(let S of y)this.add(S);break}case"tx":{let y=A.split(";");for(let S=y.length-1;S>=0;S--)this.undoStep(y[S])}}}undo(T){let o=T.indexOf("=");if(Number(T.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let A=T.substring(o+1);return this.undoStep(A),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class Ey{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,o){let F=this.toolkit;this.toolkit=T,o(this),this.toolkit=F}store;realm;[Symbol.dispose](){}constructor(T,o,F=ST.STORE){this.store=F,this.realm=new e$(F),this.options=T,this.defaultContent=o,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...U)=>MT(F,...U),set:(...U)=>{jT(F,...U)},find:(...U)=>i(F,...U),json:(U)=>nT(F,U)};let A=T.between[0],y=T.between[1],S=Hy(F,{key:`${T.key}/relatedKeys`,default:()=>new cT,mutable:!0,fromJson:(U)=>cT.fromJSON(U),toJson:(U)=>U.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:S};let f=({get:U},V)=>U(S,V),$=({set:U},V,I)=>{if(!this.store.molecules.has(AT(V)))this.realm.allocate(T.key,V);U(S,V,(L)=>L.add(I)),U(S,I,(L)=>L.add(V))},_=({set:U},V,I)=>{U(S,V,(L)=>{return L.delete(I),L}),U(S,I,(L)=>{return L.delete(V),L})},J=(U,V,I)=>{let{find:L,get:m,set:s}=U,z=L(S,V),a=m(z);for(let t of a){if(I.includes(t))continue;s(S,t,(ZT)=>{return ZT.delete(V),ZT})}s(z,(t)=>{return t.transaction((e)=>{e.clear();for(let ZT of I){let vT=f(U,ZT),Xo=vT.has(V);if(this.relations.cardinality==="1:n"){let AF=[];for(let D of vT){if(D===V)continue;let g=f(U,D);if(g.delete(ZT),g.size===0)AF.push(D)}if(!Xo&&vT.size>0)vT.clear();for(let D of AF){let g=[ZT,D].sort(),_T=`"${g[0]}:${g[1]}"`;this.molecules.delete(_T)}}if(!Xo)vT.add(V);e.add(ZT)}return!0}),t})},R=(U,V,I)=>{let{set:L}=U;L(S,V,(m)=>{return m.transaction((s)=>{for(let z of I)s.add(z);return!0}),m});for(let m of I)L(S,m,(s)=>{return s.add(V),s});return!0},O=(U,V,I)=>{let L=f(U,V);return I?L.has(I):L.size>0},Y={getRelatedKeys:(U)=>f(this.toolkit,U),addRelation:(U,V)=>{this.store.moleculeJoins.set(U,T.key),this.store.moleculeJoins.set(V,T.key),$(this.toolkit,U,V)},deleteRelation:(U,V)=>{_(this.toolkit,U,V)},replaceRelationsSafely:(U,V)=>{J(this.toolkit,U,V)},replaceRelationsUnsafely:(U,V)=>{R(this.toolkit,U,V)},has:(U,V)=>O(this.toolkit,U,V)},H,Q;if(o){Q=OF(F,{key:`${T.key}/content`,default:o},["join","content"]);let U=({get:L},m)=>L(Q,m),V=({set:L},m,s)=>{L(Q,m,s)};H=Object.assign(Y,{getContent:(L)=>{return U(this.toolkit,L)},setContent:(L,m)=>{V(this.toolkit,L,m)},deleteContent:(L)=>{this.realm.deallocate(L)}})}else H=Y;let E=new uT(T,{externalStore:H,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...U)=>{let[V,I]=U,L=U.sort(),m=`${L[0]}:${L[1]}`,s=F.molecules.get(AT(V)),z=F.molecules.get(AT(I));if(!s)this.realm.allocate(T.key,V);if(!z)this.realm.allocate(T.key,I);return this.realm.allocate(V,m,"all"),this.realm.claim(I,m),this.store.moleculeJoins.set(m,T.key),m}}),B=()=>XF(F,{key:`${T.key}/singleRelatedKey`,get:(U)=>({get:V})=>{let I=V(S,U);for(let L of I)return L;return null}},["join","keys"]),p=()=>{return XF(F,{key:`${T.key}/multipleRelatedKeys`,get:(U)=>({get:V})=>{let I=WJ(S,F);return V(I,U).members}},["join","keys"])},v=()=>XF(F,{key:`${T.key}/singleRelatedEntry`,get:(U)=>({get:V})=>{let I=V(S,U);for(let L of I){let m=E.isAType?.(U)?U:void 0,s=m===void 0?U:void 0;m??=L,s??=L;let z=E.makeContentKey(m,s),a=V(Q,z);return[L,a]}return null}},["join","entries"]),h=()=>XF(F,{key:`${T.key}/multipleRelatedEntries`,get:(U)=>({get:V})=>{let I=WJ(S,F);return V(I,U).members.map((m)=>{let s=E.isAType?.(U)?U:void 0,z=s===void 0?U:void 0;s??=m,z??=m;let a=E.makeContentKey(s,z),t=V(Q,a);return[m,t]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let U=B(),V=`${A}KeyOf${XT(y)}`,I=`${y}KeyOf${XT(A)}`,L={[V]:U,[I]:U},m;if(o){let s=v(),z=`${A}EntryOf${XT(y)}`,a=`${y}EntryOf${XT(A)}`,t={[z]:s,[a]:s};m=Object.assign(L,t)}else m=L;this.relations=E,this.states=m;break}case"1:n":{let U=B(),V=p(),I=`${A}KeyOf${XT(y)}`,L=`${y}KeysOf${XT(A)}`,m={[I]:U,[L]:V},s;if(o){let z=v(),a=h(),t=`${A}EntryOf${XT(y)}`,e=`${y}EntriesOf${XT(A)}`,ZT={[t]:z,[e]:a};s=Object.assign(m,ZT)}else s=m;this.relations=E,this.states=s;break}case"n:n":{let U=p(),V=`${A}KeysOf${XT(y)}`,I=`${y}KeysOf${XT(A)}`,L={[V]:U,[I]:U},m;if(o){let s=h(),z=`${A}EntriesOf${XT(y)}`,a=`${y}EntriesOf${XT(A)}`,t={[z]:s,[a]:s};m=Object.assign(L,t)}else m=L;this.relations=E,this.states=m}}}}function LA(T,o){let F=o.joins.get(T.key);if(F===void 0){let y=ST.STORE.joins.get(T.key);if(y===void 0)throw new Error(`Join "${T.key}" not found in store "${o.config.name}"`);F=new Ey(y.options,y.defaultContent,o),o.joins.set(T.key,F)}return F}function Ky(T,o,F){let A=LA(T,F),y=j(F);if(OT(y)){let{toolkit:S}=y.transactionMeta;A.transact(S,({relations:f})=>{o(f)})}else o(A.relations)}function kS(T,o,F){let A=LA(T,F),y;switch(T.cardinality){case"1:1":{let S=`${T.a}KeyOf${XT(T.b)}`,f=`${T.b}KeyOf${XT(T.a)}`;y={get[S](){let _=A.states[S];return i(F,_,o)},get[f](){let _=A.states[f];return i(F,_,o)}};let $=`${T.a}EntryOf${XT(T.b)}`;if($ in A.states){let _=`${T.b}EntryOf${XT(T.a)}`;Object.assign(y,{get[$](){let J=A.states[$];return i(F,J,o)},get[_](){let J=A.states[_];return i(F,J,o)}})}break}case"1:n":{let S=`${T.a}KeyOf${XT(T.b)}`,f=`${T.b}KeysOf${XT(T.a)}`;y={get[S](){let _=A.states[S];return i(F,_,o)},get[f](){let _=A.states[f];return i(F,_,o)}};let $=`${T.a}EntryOf${XT(T.b)}`;if($ in A.states){let _=`${T.b}EntriesOf${XT(T.a)}`;Object.assign(y,{get[$](){let J=A.states[$];return i(F,J,o)},get[_](){let J=A.states[_];return i(F,J,o)}})}break}case"n:n":{let S=`${T.a}KeysOf${XT(T.b)}`,f=`${T.b}KeysOf${XT(T.a)}`;y={get[S](){let _=A.states[S];return i(F,_,o)},get[f](){let _=A.states[f];return i(F,_,o)}};let $=`${T.a}EntriesOf${XT(T.b)}`;if($ in A.states){let _=`${T.b}EntriesOf${XT(T.a)}`;Object.assign(y,{get[$](){let J=A.states[$];return i(F,J,o)},get[_](){let J=A.states[_];return i(F,J,o)}})}}}return y}function iR(T,o){return LA(T,o).core.relatedKeysAtoms}function BF(T){return T.startsWith("\uD83D\uDD0D ")}var MJ=(T)=>{let o=Lo(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let F=new Map;for(let[A,y]of T.atoms){if(BF(A))continue;let S=Ko(y);if(y.family){let f=F.get(y.family.key);if(!f||!("familyMembers"in f))f={key:y.family.key,familyMembers:new Map},F.set(y.family.key,f);f.familyMembers.set(y.family.subKey,S)}else F.set(A,S)}return F},effects:[({setSelf:F})=>{T.on.atomCreation.subscribe("introspection",(A)=>{if(BF(A.key))return;F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($===void 0||!("familyMembers"in $))$={key:S,familyMembers:new Map},y.set(S,$);$.familyMembers.set(f,A)}else y.set(A.key,A);return y})}),T.on.atomDisposal.subscribe("introspection",(A)=>{F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($&&"familyMembers"in $){if($.familyMembers.delete(f),$.familyMembers.size===0)y.delete(S)}}else y.delete(A.key);return y})})}]},void 0);return MF(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:F})=>F(o)})};var OJ=(T)=>{let o=Lo(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let F=new Map;for(let A of[T.readonlySelectors,T.selectors])for(let[y,S]of A){if(BF(y))continue;let f=Ko(S);if(S.family){let $=F.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},F.set(S.family.key,$);$.familyMembers.set(S.family.subKey,f)}else F.set(y,f)}return F},effects:[({setSelf:F})=>{T.on.selectorCreation.subscribe("introspection",(A)=>{if(BF(A.key))return;F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($===void 0||!("familyMembers"in $))$={key:S,familyMembers:new Map},y.set(S,$);$.familyMembers.set(f,A)}else y.set(A.key,A);return y})}),T.on.selectorDisposal.subscribe("introspection",(A)=>{F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($&&"familyMembers"in $){if($.familyMembers.delete(f),$.familyMembers.size===0)y.delete(S)}}else y.delete(A.key);return y})})}]},void 0);return MF(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:F})=>F(o)})};class mS{supported;constructor(T){this.supported=T}refine(T){for(let[o,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:o,data:T}}catch(A){try{if(T instanceof F)return{type:o,data:T}}catch(y){}}return null}}var XJ=new mS({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function YJ(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var ZJ=new mS({object:YJ,array:(T)=>Array.isArray(T)}),XZ=new mS({...XJ.supported,...ZJ.supported}),CA=(T)=>{if(T===void 0)return"undefined";let o=XZ.refine(T);if(o)return o.type;return Object.getPrototypeOf(T).constructor.name};class kW{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=ST.STORE){this.store=T,this.atomIndex=MJ(this.store),this.selectorIndex=OJ(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=kW.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let o=l$(this.atomIndex),F=l$(this.selectorIndex),A=[...o.values()].filter(($)=>("familyMembers"in $)),y=[...F.values()].filter(($)=>("familyMembers"in $)),S=performance.now(),f=[];if(T.atomFamilies)for(let $ of A){let _=$.familyMembers.values();for(let J of _){let O=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=S-O;f.push([J,Y])}}if(T.selectorFamilies)for(let $ of y){let _=$.familyMembers.values();for(let J of _){let O=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=S-O;f.push([J,Y])}}return f}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var HJ=(T,o)=>{let F=(A,y)=>{let f=((_,J)=>{let R=o(_,J);if(R)return R;return null})(A,y);if(f?.jobComplete??f?.pathComplete)return f;let $=Array.isArray(y)?y.map((_,J)=>[J,_]):YJ(y)?Object.entries(y):[];for(let[_,J]of $){let R=F([...A,_],J);if(R?.jobComplete)return R}return{}};F([],T)};function YZ(T,o){return{summary:`${T<o?"+":"-"}${Math.abs(T-o)} (${T} \u2192 ${o})`}}function ZZ(T,o){return{summary:`${T.length<o.length?"+":"-"}${Math.abs(T.length-o.length)} ("${T}" \u2192 "${o}")`}}function HZ(T,o){return{summary:`${T} \u2192 ${o}`}}function BW(T,o,F){let A="",y=[],S=[],f=[];return HJ(T,($,_)=>{let J;for(J of $){let R=o[J];if(R===void 0)S.push([J,JSON.stringify(_)]);else{let O=F(_,R);if(O.summary!=="No Change")f.push([J,O])}}}),HJ(o,($,_)=>{let J;for(J of $)if(T[J]===void 0)y.push([J,JSON.stringify(_)])}),A=`\uFF5E${f.length} \uFF0B${y.length} \uFF0D${S.length}`,{summary:A,added:y,removed:S,changed:f}}function GZ(T,o,F){return BW(T,o,F)}class NW{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,o,F){this.leafRefinery=T,this.treeRefinery=o,this.leafDiffers={},this.treeDiffers={};for(let A of Object.keys(T.supported)){let y=F[A];this.leafDiffers[A]=y}for(let A of Object.keys(o.supported)){let y=F[A];this.treeDiffers[A]=y}}diff(T,o){if(T===o)return{summary:"No Change"};let F=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),A=this.leafRefinery.refine(o)??this.treeRefinery.refine(o);if(F!==null&&A!==null){if(F.type===A.type){if(F.type in this.leafDiffers)return this.leafDiffers[F.type](F.data,A.data);if(F.type in this.treeDiffers)return this.treeDiffers[F.type](F.data,A.data,($,_)=>this.diff($,_))}}let y=CA(T),S=CA(o);if(y===S)return{summary:`${y} \u2192 ${S}`};return{summary:`Type change: ${y} \u2192 ${S}`}}}var _p=new NW(XJ,ZJ,{number:YZ,string:ZZ,boolean:HZ,null:()=>({summary:"No Change"}),object:BW,array:GZ});class pW extends Map{set(T,o){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:o}),this;return super.set(T,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class tS{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(T){this.key=T}static existing=new pW;static create(T,o){let F=new tS(T),{type:A,globals:y,actions:S,perspectives:f}=o(F),$={type:A,key:T,globals:y,actions:S,perspectives:f};return tS.existing.set(T,$),$}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":case"mutable_atom_family":{let[F,A]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:F,viewAtoms:A})}break}return this}}function Gp(T){let{key:o,config:F}=T,A=tS.create(o,F),{actions:y}=A;for(let S of y)GW(ST.STORE,o,S.key);return YW(ST.STORE,o,-1),A}var Up=zA({key:"usersInRoomIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),GJ=zA({key:"roomIndex",default:()=>new cT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),wZ={enteredAtEpoch:0},Dy=IS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},wZ),zp=BS({key:"usersInMyRoomView",get:(T)=>({find:o})=>{let F=cR(Dy);return[o(F,T)]}});import{spawn as EZ}from"child_process";class IA{listeners;globalListeners;handleEvent(T,...o){for(let A of this.globalListeners)A(T,...o);let F=this.listeners.get(T);if(F)for(let A of F)A(...o)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,o){let F=this.listeners.get(T);if(F)F.add(o);else this.listeners.set(T,new Set([o]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,o){let F=this.listeners.get(T);if(F)if(o)F.delete(o);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class wJ extends IA{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[o,...F]=T;switch(o){case"i":this.logger.info(...F);break;case"w":this.logger.warn(...F);break;case"e":this.logger.error(...F);break;default:return}}}constructor(T,o,F){super((A,...y)=>{let S=JSON.stringify([A,...y])+"\x03",f=($)=>{if($.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",f)};return this.process.stdin.once("error",f),this.process.stdin.write(S),this});if(this.process=T,this.key=o,this.logger=F??{info:(...A)=>{console.info(this.id,this.key,...A)},warn:(...A)=>{console.warn(this.id,this.key,...A)},error:(...A)=>{console.error(this.id,this.key,...A)}},this.process.stdout.on("data",(A)=>{let y=A.toString();if(y==="ALIVE")return;this.unprocessedEvents.push(...y.split("\x03"));let S=this.unprocessedEvents.shift();this.incompleteData+=S??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let f=rT(this.incompleteData);this.handleEvent(...f);while(this.unprocessedEvents.length>0){let $=this.unprocessedEvents.shift();if($){if(this.unprocessedEvents.length===0)this.incompleteData=$;f=rT($),this.handleEvent(...f)}}this.incompleteData=""}catch(f){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(f)}}),this.process.stderr.on("data",(A)=>{let y=A.toString();this.unprocessedLogs.push(...y.split("\x03"));let S=this.unprocessedLogs.shift();this.incompleteLog+=S??"";try{let f=rT(this.incompleteLog);this.handleLog(f);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)f=rT(this.incompleteLog),this.handleLog(f)}catch(f){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(f),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class jW extends IA{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...o)=>{return this.out.next(o),this});this.id=T,this.in=new oT,this.out=new oT,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let T of this.disposalFunctions)T()}}class EJ extends IA{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(AT(T.map((o)=>o instanceof cT?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...o)=>{let F=JSON.stringify([T,...o]);return this.process.stdout.write(F+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let o=T.toString();this.unprocessedEvents.push(...o.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let A=rT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",A),this.handleEvent(...A);while(this.unprocessedEvents.length>0){let y=this.unprocessedEvents.shift();if(y){if(this.unprocessedEvents.length===0)this.incompleteData=y;let S=rT(y);this.handleEvent(...S)}}this.incompleteData=""}catch(A){if(A instanceof Error)this.logger.error("\u2757",A.message,A.cause,A.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let o=new jW(`user:${T}`);this.relays.set(T,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let A=F(o);if(A)o.disposalFunctions.push(A)}this.on(`user:${T}`,(...F)=>{o.in.next(F)}),o.out.subscribe("socket",(F)=>{this.emit(...F)})}),this.on("user-leaves",(T)=>{let o=this.relays.get(T);if(this.off(`relay:${T}`),o)o.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var KJ=gF({key:"roomArguments",default:["echo",["Hello World!"]]}),xW=BS({key:"room",get:(T)=>async({get:o,find:F})=>{let A=F(KJ,T),y=o(A),[S,f]=y,$=await new Promise((_)=>{let J=EZ(S,f,{env:process.env}),R=(O)=>{if(O.toString()==="ALIVE")J.stdout.off("data",R),_(J)};J.stdout.on("data",R)});return new wJ($,T)}});var lp=zy({key:"createRoom",do:({get:T,set:o,find:F},A,y,S)=>{let f=S?[y,S]:[y],$=F(KJ,A);o($,f),o(GJ,(R)=>R.add(A));let _=F(xW,A);return T(_)}}),sp=zy({key:"joinRoom",do:(T,o,F,A)=>{let y={enteredAtEpoch:A};return Ky(Dy,(S)=>{S.set({room:o,user:F},y)},T.env().store),y}}),ap=zy({key:"leaveRoom",do:(T,o,F)=>{Ky(Dy,(A)=>{A.delete({room:o,user:F})},T.env().store)}}),ep=zy({key:"destroyRoom",do:(T,o)=>{Ky(Dy,(F)=>{F.delete({room:o})},T.env().store),T.set(GJ,(F)=>(F.delete(o),F))}});function UJ(T,o){return o.map((F)=>{switch(F.type){case"transaction_update":{let A=UJ(T,F.updates);return{...F,updates:A}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return F}}).filter((F)=>{switch(F.type){case"atom_update":case"selector_update":return T.includes(F.key);case"state_creation":case"state_disposal":return T.includes(F.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var Fj=gF({key:"redactor",default:{occlude:(T)=>T}}),kA=gF({key:"unacknowledgedUpdates",default:()=>[]});var bW=gF({key:"sockets",default:null}),fj=zA({key:"socketsIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),$j=zA({key:"usersIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),zJ=IS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function qW(T,o,F,A){let y=o.key;return function S(){let f=[];for(let _ of o.globals){let J=_.type==="mutable_atom"?nT(T,_):_,R=MT(T,J);f.push(J,R)}for(let _ of o.perspectives){let{viewAtoms:J,resourceAtoms:R}=_,O=i(T,J,F),Y=MT(T,O);T.logger.info("\uD83D\uDC41","atom",R.key,`${F} can see`,{viewAtoms:J,resourceAtoms:R,userView:Y});for(let H of Y){let Q=H.type==="mutable_atom"?nT(T,H):H,E=MT(T,Q);f.push(Q,E)}}let $=aT(T)?T.transactionMeta.epoch.get(y)??null:null;A?.emit(`continuity-init:${y}`,$,f)}}function vW(T,o,F){let A=o.key;return function y(S){T.logger.info("\uD83D\uDECE\uFE0F","continuity",A,"received",S);let{key:f,id:$}=S,_=`tx-run:${f}:${$}`,J=`${_}:start`,R=`${_}:end`;performance.mark(J);try{VA(T,{type:"transaction",key:f},$)(...S.params)}catch(Y){if(Y instanceof Error)T.logger.error("\u274C","continuity",A,`failed to run transaction ${f} from ${F} with update ${$}`,Y.message)}performance.mark(R);let O=performance.measure(_,J,R);T?.logger.info("\uD83D\uDE80","transaction",f,$,F,O.duration)}}function PW(T,o,F,A){let y=o.key;return function S(f){if(T.logger.info("\uD83D\uDC4D","continuity",y,`${F} acknowledged epoch ${f}`),A[0]?.epoch===f)jT(T,kA,F,(_)=>{return _.shift(),T.logger.info("\uD83D\uDC4D","continuity",y,`${F} unacknowledged update queue now has`,_.length,"items"),_})}}function mW(T,o,F,A){let y=o.key,S=[];for(let f of o.actions){let $=JJ(T,f,`sync-continuity:${y}:${F}`,(_)=>{try{let J=o.globals.map((Y)=>{if(Y.type==="atom")return Y.key;return YF(Y).key}).concat(o.perspectives.flatMap((Y)=>{let{viewAtoms:H}=Y,Q=i(T,H,F);return MT(T,Q).map((B)=>{return B.type==="mutable_atom"?"*"+B.key:B.key})})),R=UJ(J,_.updates),O={..._,updates:R};jT(T,kA,F,(Y)=>{if(O)Y.push(O),Y.sort((H,Q)=>H.epoch-Q.epoch),T.logger.info("\uD83D\uDC4D","continuity",y,`${F} unacknowledged update queue now has`,Y.length,"items");return Y}),A?.emit(`tx-new:${y}`,O)}catch(J){if(J instanceof Error)T.logger.error("\u274C","continuity",y,`${F} failed to send update from transaction ${f.key} to ${F}`,J.message)}});S.push($)}return S}function tW(T,o,F,A){let y=o.key,S=[];for(let f of o.perspectives){let{viewAtoms:$}=f,_=i(T,$,F),J=fo(T,_,`sync-continuity:${y}:${F}:perspective:${f.resourceAtoms.key}`,({oldValue:R,newValue:O})=>{let Y=R.map((B)=>B.key),H=O.map((B)=>B.key),Q=R.filter((B)=>!H.includes(B.key)),E=O.filter((B)=>!Y.includes(B.key)).flatMap((B)=>{let p=B.type==="mutable_atom"?nT(T,B):B,v=MT(T,p);return[p,v]});if(T.logger.info("\uD83D\uDC41","atom",f.resourceAtoms.key,`${F} has a new perspective`,{oldKeys:Y,newKeys:H,revealed:E,concealed:Q}),E.length>0)A?.emit(`reveal:${y}`,E);if(Q.length>0)A?.emit(`conceal:${y}`,Q)});S.push(J)}return S}function bj({socket:T,store:o=ST.STORE}){return function F(A){let y=T,S=A.key,f=kS(zJ,`socket::${y.id}`,o).userKeyOfSocket,$=MT(o,f);if(!$)return o.logger.error("\u274C","continuity",S,`Tried to create a synchronizer for a socket (${y.id}) that is not connected to a user.`),()=>{};let _=kS(zJ,$,o).socketKeyOfUser,J=fo(o,_,`sync-continuity:${S}:${$}`,({newValue:p})=>{if(o.logger.info("\uD83D\uDC4B","continuity",S,`seeing ${$} on new socket ${p}`),p===null){o.logger.warn("\u274C","continuity",S,`User (${$}) is not connected to a socket, waiting for them to reappear.`);return}let v=i(o,bW,p);y=MT(o,v);for(let U of R)y?.emit(`tx-new:${S}`,U)}),R=MT(o,kA,$),O=[],Y=tW(o,A,$,y),H=mW(o,A,$,y);O.push(...Y,...H);let Q=qW(o,A,$,T);y.off(`get:${S}`,Q),y.on(`get:${S}`,Q);let E=vW(o,A,$);y.off(`tx-run:${S}`,E),y.on(`tx-run:${S}`,E);let B=PW(o,A,$,R);return y?.on(`ack:${S}`,B),()=>{for(let p of O)p();y?.off(`ack:${S}`,B),y?.off(`get:${S}`,Q),y?.off(`tx-run:${S}`,E)}}}var{file:G4,serve:xH}=globalThis.Bun;import{readFileSync as uW}from"fs";import{createServer as QZ}from"http";import{createServer as VZ}from"https";import{resolve as QJ}from"path";function hW(T,o){if(T instanceof Promise)throw new Error(o)}function KZ(T,o){let F={},A=[];for(let y in T){let S=T[y]["~standard"].validate(o[y]);if(hW(S,`Validation must be synchronous, but ${y} returned a Promise.`),S.issues){A.push(...S.issues.map((f)=>({...f,path:[y,...f.path??[]]})));continue}F[y]=S.value}if(A.length)return{issues:A};return{value:F}}function gW(T){let o=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[v,h]of Object.entries(o))if(h==="")delete o[v]}if(!!T.skipValidation)return o;let y=typeof T.client==="object"?T.client:{},S=typeof T.server==="object"?T.server:{},f=typeof T.shared==="object"?T.shared:{},$=T.isServer??(typeof window==="undefined"||("Deno"in window)),_=$?{...S,...f,...y}:{...y,...f},J=T.createFinalSchema?.(_,$)["~standard"].validate(o)??KZ(_,o);hW(J,"Validation must be synchronous");let R=T.onValidationError??((v)=>{throw console.error("\u274C Invalid environment variables:",v),new Error("Invalid environment variables")}),O=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return R(J.issues);let Y=(v)=>{if(!T.clientPrefix)return!0;return!v.startsWith(T.clientPrefix)&&!(v in f)},H=(v)=>{return $||!Y(v)},Q=(v)=>{return v==="__esModule"||v==="$$typeof"},E=(T.extends??[]).reduce((v,h)=>{return Object.assign(v,h)},{}),B=Object.assign(E,J.value);return new Proxy(B,{get(v,h){if(typeof h!=="string")return;if(Q(h))return;if(!H(h))return O(h);return Reflect.get(v,h)}})}var UZ="__vite_start_time"in globalThis,zZ=typeof window!=="undefined",Wx="vitest"in globalThis,ZF=Eo("string"),nW=Eo('"true" | "false" | undefined'),uo=gW({isServer:!UZ&&!zZ,server:{CI:Eo("string | undefined").pipe(Boolean),POSTGRES_USER:ZF,POSTGRES_PASSWORD:ZF,POSTGRES_DATABASE:ZF,POSTGRES_HOST:ZF,POSTGRES_PORT:ZF.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:ZF.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:nW.pipe((T)=>T==="true"),FRONTEND_PORT:ZF.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:ZF.pipe.try((T)=>JSON.parse(T),Eo("string[]")),API_KEY_OPENAI:Eo("string | undefined"),API_KEY_RESEND:Eo("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:ZF,VITE_DEV_FRONTEND_HOST:Eo("string | undefined"),VITE_DEV_HTTPS:nW.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var cW=QJ(import.meta.dirname,"../dev"),hS=uo.VITE_DEV_HTTPS?{cert:uW(QJ(cW,"./cert.pem"),"utf-8"),key:uW(QJ(cW,"./key.pem"),"utf-8")}:void 0;function Gx(T){if(hS)return VZ(hS,T);return QZ({},T)}import IH from"path";var M=Symbol.for("drizzle:entityKind"),Ex=Symbol.for("drizzle:hasOwnEntityKind");function w(T,o){if(!T||typeof T!=="object")return!1;if(T instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,M))throw new Error(`Class "${o.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 F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(M in F&&F[M]===o[M])return!0;F=Object.getPrototypeOf(F)}return!1}class GT{constructor(T,o){this.table=T,this.config=o,this.name=o.name,this.keyAsName=o.keyAsName,this.notNull=o.notNull,this.default=o.default,this.defaultFn=o.defaultFn,this.onUpdateFn=o.onUpdateFn,this.hasDefault=o.hasDefault,this.primary=o.primaryKey,this.isUnique=o.isUnique,this.uniqueName=o.uniqueName,this.uniqueType=o.uniqueType,this.dataType=o.dataType,this.columnType=o.columnType,this.generated=o.generated,this.generatedIdentity=o.generatedIdentity}static[M]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class VJ{static[M]="ColumnBuilder";config;constructor(T,o,F){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:o,columnType:F,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var co=Symbol.for("drizzle:Name");class DJ{static[M]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,o){if(this.reference=()=>{let{name:F,columns:A,foreignColumns:y}=T();return{name:F,columns:A,foreignTable:y[0].table,foreignColumns:y}},o)this._onUpdate=o.onUpdate,this._onDelete=o.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new iW(T,this)}}class iW{constructor(T,o){this.table=T,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[M]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:o,foreignColumns:F}=this.reference(),A=o.map((f)=>f.name),y=F.map((f)=>f.name),S=[this.table[co],...A,F[0].table[co],...y];return T??`${S.join("_")}_fk`}}function gS(T,...o){return T(...o)}function dW(T,o){return`${T[co]}_${o.join("_")}_unique`}function rW(T,o,F){for(let A=o;A<T.length;A++){let y=T[A];if(y==="\\"){A++;continue}if(y==='"')return[T.slice(o,A).replace(/\\/g,""),A+1];if(F)continue;if(y===","||y==="}")return[T.slice(o,A).replace(/\\/g,""),A]}return[T.slice(o).replace(/\\/g,""),T.length]}function lW(T,o=0){let F=[],A=o,y=!1;while(A<T.length){let S=T[A];if(S===","){if(y||A===o)F.push("");y=!0,A++;continue}if(y=!1,S==="\\"){A+=2;continue}if(S==='"'){let[_,J]=rW(T,A+1,!0);F.push(_),A=J;continue}if(S==="}")return[F,A+1];if(S==="{"){let[_,J]=lW(T,A+1);F.push(_),A=J;continue}let[f,$]=rW(T,A,!1);F.push(f),A=$}return[F,A]}function sW(T){let[o]=lW(T,1);return o}function LJ(T){return`{${T.map((o)=>{if(Array.isArray(o))return LJ(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class q extends VJ{foreignKeyConfigs=[];static[M]="PgColumnBuilder";array(T){return new eW(this.config.name,this,T)}references(T,o={}){return this.foreignKeyConfigs.push({ref:T,actions:o}),this}unique(T,o){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=o?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,o){return this.foreignKeyConfigs.map(({ref:F,actions:A})=>{return gS((y,S)=>{let f=new DJ(()=>{let $=y();return{columns:[T],foreignColumns:[$]}});if(S.onUpdate)f.onUpdate(S.onUpdate);if(S.onDelete)f.onDelete(S.onDelete);return f.build(o)},F,A)})}buildExtraConfigColumn(T){return new aW(T,this.config)}}class C extends GT{constructor(T,o){if(!o.uniqueName)o.uniqueName=dW(T,[o.name]);super(T,o);this.table=T}static[M]="PgColumn"}class aW extends C{static[M]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class Ly{static[M]="IndexedColumn";constructor(T,o,F,A){this.name=T,this.keyAsName=o,this.type=F,this.indexConfig=A}name;keyAsName;type;indexConfig}class eW extends q{static[M]="PgArrayBuilder";constructor(T,o,F){super(T,"array","PgArray");this.config.baseBuilder=o,this.config.size=F}build(T){let o=this.config.baseBuilder.build(T);return new CJ(T,this.config,o)}}class CJ extends C{constructor(T,o,F,A){super(T,o);this.baseColumn=F,this.range=A,this.size=o.size}size;static[M]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=sW(T);return T.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(T,o=!1){let F=T.map((A)=>A===null?null:w(this.baseColumn,CJ)?this.baseColumn.mapToDriverValue(A,!0):this.baseColumn.mapToDriverValue(A));if(o)return F;return LJ(F)}}class TM extends q{static[M]="PgEnumObjectColumnBuilder";constructor(T,o){super(T,"string","PgEnumObjectColumn");this.config.enum=o}build(T){return new oM(T,this.config)}}class oM extends C{static[M]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,o){super(T,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}var nS=Symbol.for("drizzle:isPgEnum");function FM(T){return!!T&&typeof T==="function"&&nS in T&&T[nS]===!0}class AM extends q{static[M]="PgEnumColumnBuilder";constructor(T,o){super(T,"string","PgEnumColumn");this.config.enum=o}build(T){return new yM(T,this.config)}}class yM extends C{static[M]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,o){super(T,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}function Cy(T,o){return Array.isArray(o)?DZ(T,[...o],void 0):LZ(T,o,void 0)}function DZ(T,o,F){let A=Object.assign((y)=>new AM(y??"",A),{enumName:T,enumValues:o,schema:F,[nS]:!0});return A}function LZ(T,o,F){let A=Object.assign((y)=>new TM(y??"",A),{enumName:T,enumValues:Object.values(o),schema:F,[nS]:!0});return A}class iT{static[M]="Subquery";constructor(T,o,F,A=!1){this._={brand:"Subquery",sql:T,selectedFields:o,alias:F,isWith:A}}}class Iy extends iT{static[M]="WithSubquery"}var SM="0.43.1";var IJ,kJ,wT={startActiveSpan(T,o){if(!IJ)return o();if(!kJ)kJ=IJ.trace.getTracer("drizzle-orm",SM);return gS((F,A)=>A.startActiveSpan(T,(y)=>{try{return o(y)}catch(S){throw y.setStatus({code:F.SpanStatusCode.ERROR,message:S instanceof Error?S.message:"Unknown error"}),S}finally{y.end()}}),IJ,kJ)}};var QT=Symbol.for("drizzle:ViewBaseConfig");var uS=Symbol.for("drizzle:Schema"),cS=Symbol.for("drizzle:Columns"),fM=Symbol.for("drizzle:ExtraConfigColumns"),BJ=Symbol.for("drizzle:OriginalName"),NJ=Symbol.for("drizzle:BaseName"),ky=Symbol.for("drizzle:IsAlias"),$M=Symbol.for("drizzle:ExtraConfigBuilder"),CZ=Symbol.for("drizzle:IsDrizzleTable");class x{static[M]="Table";static Symbol={Name:co,Schema:uS,OriginalName:BJ,Columns:cS,ExtraConfigColumns:fM,BaseName:NJ,IsAlias:ky,ExtraConfigBuilder:$M};[co];[BJ];[uS];[cS];[fM];[NJ];[ky]=!1;[CZ]=!0;[$M]=void 0;constructor(T,o,F){this[co]=this[BJ]=T,this[uS]=o,this[NJ]=F}}function lT(T){return T[co]}function rF(T){return`${T[uS]??"public"}.${T[co]}`}function pJ(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function IZ(T){let o={sql:"",params:[]};for(let F of T)if(o.sql+=F.sql,o.params.push(...F.params),F.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...F.typings)}return o}class dT{static[M]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new b([this])}}class b{constructor(T){this.queryChunks=T}static[M]="SQL";decoder=_M;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return wT.startActiveSpan("drizzle.buildSQL",(o)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return o?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,o){let F=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:A,escapeName:y,escapeParam:S,prepareTyping:f,inlineParams:$,paramStartIndex:_}=F;return IZ(T.map((J)=>{if(w(J,dT))return{sql:J.value.join(""),params:[]};if(w(J,iS))return{sql:y(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let R=[new dT("(")];for(let[O,Y]of J.entries())if(R.push(Y),O<J.length-1)R.push(new dT(", "));return R.push(new dT(")")),this.buildQueryFromSourceParams(R,F)}if(w(J,b))return this.buildQueryFromSourceParams(J.queryChunks,{...F,inlineParams:$||J.shouldInlineParams});if(w(J,x)){let R=J[x.Symbol.Schema],O=J[x.Symbol.Name];return{sql:R===void 0||J[ky]?y(O):y(R)+"."+y(O),params:[]}}if(w(J,GT)){let R=A.getColumnCasing(J);if(o.invokeSource==="indexes")return{sql:y(R),params:[]};let O=J.table[x.Symbol.Schema];return{sql:J.table[ky]||O===void 0?y(J.table[x.Symbol.Name])+"."+y(R):y(O)+"."+y(J.table[x.Symbol.Name])+"."+y(R),params:[]}}if(w(J,Uo)){let R=J[QT].schema,O=J[QT].name;return{sql:R===void 0||J[QT].isAlias?y(O):y(R)+"."+y(O),params:[]}}if(w(J,Co)){if(w(J.value,NF))return{sql:S(_.value++,J),params:[J],typings:["none"]};let R=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(w(R,b))return this.buildQueryFromSourceParams([R],F);if($)return{sql:this.mapInlineParam(R,F),params:[]};let O=["none"];if(f)O=[f(J.encoder)];return{sql:S(_.value++,R),params:[R],typings:O}}if(w(J,NF))return{sql:S(_.value++,J),params:[J],typings:["none"]};if(w(J,b.Aliased)&&J.fieldAlias!==void 0)return{sql:y(J.fieldAlias),params:[]};if(w(J,iT)){if(J._.isWith)return{sql:y(J._.alias),params:[]};return this.buildQueryFromSourceParams([new dT("("),J._.sql,new dT(") "),new iS(J._.alias)],F)}if(FM(J)){if(J.schema)return{sql:y(J.schema)+"."+y(J.enumName),params:[]};return{sql:y(J.enumName),params:[]}}if(pJ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],F);return this.buildQueryFromSourceParams([new dT("("),J.getSQL(),new dT(")")],F)}if($)return{sql:this.mapInlineParam(J,F),params:[]};return{sql:S(_.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(T,{escapeString:o}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return o(T);if(typeof T==="object"){let F=T.toString();if(F==="[object Object]")return o(JSON.stringify(T));return o(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new b.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class iS{constructor(T){this.value=T}static[M]="Name";brand;getSQL(){return new b([this])}}function JM(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var _M={mapFromDriverValue:(T)=>T},RM={mapToDriverValue:(T)=>T},Jb={..._M,...RM};class Co{constructor(T,o=RM){this.value=T,this.encoder=o}static[M]="Param";brand;getSQL(){return new b([this])}}function X(T,...o){let F=[];if(o.length>0||T.length>0&&T[0]!=="")F.push(new dT(T[0]));for(let[A,y]of o.entries())F.push(y,new dT(T[A+1]));return new b(F)}((T)=>{function o(){return new b([])}T.empty=o;function F(_){return new b(_)}T.fromList=F;function A(_){return new b([new dT(_)])}T.raw=A;function y(_,J){let R=[];for(let[O,Y]of _.entries()){if(O>0&&J!==void 0)R.push(J);R.push(Y)}return new b(R)}T.join=y;function S(_){return new iS(_)}T.identifier=S;function f(_){return new NF(_)}T.placeholder=f;function $(_,J){return new Co(_,J)}T.param=$})(X||(X={}));((T)=>{class o{constructor(F,A){this.sql=F,this.fieldAlias=A}static[M]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}T.Aliased=o})(b||(b={}));class NF{constructor(T){this.name=T}static[M]="Placeholder";getSQL(){return new b([this])}}function jJ(T,o){return T.map((F)=>{if(w(F,NF)){if(!(F.name in o))throw new Error(`No value for placeholder "${F.name}" was provided`);return o[F.name]}if(w(F,Co)&&w(F.value,NF)){if(!(F.value.name in o))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(o[F.value.name])}return F})}var kZ=Symbol.for("drizzle:IsDrizzleView");class Uo{static[M]="View";[QT];[kZ]=!0;constructor({name:T,schema:o,selectedFields:F,query:A}){this[QT]={name:T,originalName:T,schema:o,selectedFields:F,query:A,isExisting:!A,isAlias:!1}}getSQL(){return new b([this])}}GT.prototype.getSQL=function(){return new b([this])};x.prototype.getSQL=function(){return new b([this])};iT.prototype.getSQL=function(){return new b([this])};class BA{constructor(T){this.table=T}static[M]="ColumnAliasProxyHandler";get(T,o){if(o==="table")return this.table;return T[o]}}class By{constructor(T,o){this.alias=T,this.replaceOriginalName=o}static[M]="TableAliasProxyHandler";get(T,o){if(o===x.Symbol.IsAlias)return!0;if(o===x.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===x.Symbol.OriginalName)return this.alias;if(o===QT)return{...T[QT],name:this.alias,isAlias:!0};if(o===x.Symbol.Columns){let A=T[x.Symbol.Columns];if(!A)return A;let y={};return Object.keys(A).map((S)=>{y[S]=new Proxy(A[S],new BA(new Proxy(T,this)))}),y}let F=T[o];if(w(F,GT))return new Proxy(F,new BA(new Proxy(T,this)));return F}}function dS(T,o){return new Proxy(T,new By(o,!1))}function oF(T,o){return new Proxy(T,new BA(new Proxy(T.table,new By(o,!1))))}function xJ(T,o){return new b.Aliased(Ny(T.sql,o),T.fieldAlias)}function Ny(T,o){return X.join(T.queryChunks.map((F)=>{if(w(F,GT))return oF(F,o);if(w(F,b))return Ny(F,o);if(w(F,b.Aliased))return xJ(F,o);return F}))}class rS extends Error{static[M]="DrizzleError";constructor({message:T,cause:o}){super(T);this.name="DrizzleError",this.cause=o}}class bJ extends rS{static[M]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class WM{static[M]="ConsoleLogWriter";write(T){console.log(T)}}class qJ{static[M]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new WM}logQuery(T,o){let F=o.map((y)=>{try{return JSON.stringify(y)}catch{return String(y)}}),A=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${A}`)}}class vJ{static[M]="NoopLogger";logQuery(){}}class Wo{static[M]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}then(T,o){return this.execute().then(T,o)}}function MM(T,o,F){let A={},y=T.reduce((S,{path:f,field:$},_)=>{let J;if(w($,GT))J=$;else if(w($,b))J=$.decoder;else J=$.sql.decoder;let R=S;for(let[O,Y]of f.entries())if(O<f.length-1){if(!(Y in R))R[Y]={};R=R[Y]}else{let H=o[_],Q=R[Y]=H===null?null:J.mapFromDriverValue(H);if(F&&w($,GT)&&f.length===2){let E=f[0];if(!(E in A))A[E]=Q===null?lT($.table):!1;else if(typeof A[E]==="string"&&A[E]!==lT($.table))A[E]=!1}}return S},{});if(F&&Object.keys(A).length>0){for(let[S,f]of Object.entries(A))if(typeof f==="string"&&!F[f])y[S]=null}return y}function bo(T,o){return Object.entries(T).reduce((F,[A,y])=>{if(typeof A!=="string")return F;let S=o?[...o,A]:[A];if(w(y,GT)||w(y,b)||w(y,b.Aliased))F.push({path:S,field:y});else if(w(y,x))F.push(...bo(y[x.Symbol.Columns],S));else F.push(...bo(y,S));return F},[])}function py(T,o){let F=Object.keys(T),A=Object.keys(o);if(F.length!==A.length)return!1;for(let[y,S]of F.entries())if(S!==A[y])return!1;return!0}function lS(T,o){let F=Object.entries(o).filter(([,A])=>A!==void 0).map(([A,y])=>{if(w(y,b)||w(y,GT))return[A,y];else return[A,new Co(y,T[x.Symbol.Columns][A])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function OM(T,o){for(let F of o)for(let A of Object.getOwnPropertyNames(F.prototype)){if(A==="constructor")continue;Object.defineProperty(T.prototype,A,Object.getOwnPropertyDescriptor(F.prototype,A)||Object.create(null))}}function XM(T){return T[x.Symbol.Columns]}function HF(T){return w(T,iT)?T._.alias:w(T,Uo)?T[QT].name:w(T,b)?void 0:T[x.Symbol.IsAlias]?T[x.Symbol.Name]:T[x.Symbol.BaseName]}function fT(T,o){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:o}}function YM(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let o=typeof T.logger;if(o!=="boolean"&&(o!=="object"||typeof T.logger.logQuery!=="function")&&o!=="undefined")return!1;return!0}if("schema"in T){let o=typeof T.schema;if(o!=="object"&&o!=="undefined")return!1;return!0}if("casing"in T){let o=typeof T.casing;if(o!=="string"&&o!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let o=typeof T.connection;if(o!=="string"&&o!=="object"&&o!=="undefined")return!1;return!0}if("client"in T){let o=typeof T.client;if(o!=="object"&&o!=="function"&&o!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class pF extends q{static[M]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:o,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:o,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class ZM extends pF{static[M]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new HM(T,this.config)}}class HM extends C{static[M]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class GM extends pF{static[M]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new wM(T,this.config)}}class wM extends C{static[M]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function EM(T,o){let{name:F,config:A}=fT(T,o);if(A.mode==="number")return new ZM(F);return new GM(F)}class KM extends q{static[M]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new UM(T,this.config)}}class UM extends C{static[M]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class zM extends q{static[M]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new QM(T,this.config)}}class QM extends C{static[M]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function VM(T,o){let{name:F,config:A}=fT(T,o);if(A.mode==="number")return new KM(F);return new zM(F)}class DM extends q{static[M]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new LM(T,this.config)}}class LM extends C{static[M]="PgBoolean";getSQLType(){return"boolean"}}function jy(T){return new DM(T??"")}class CM extends q{static[M]="PgCharBuilder";constructor(T,o){super(T,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new IM(T,this.config)}}class IM extends C{static[M]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function kM(T,o={}){let{name:F,config:A}=fT(T,o);return new CM(F,A)}class BM extends q{static[M]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new NM(T,this.config)}}class NM extends C{static[M]="PgCidr";getSQLType(){return"cidr"}}function pM(T){return new BM(T??"")}class jM extends q{static[M]="PgCustomColumnBuilder";constructor(T,o,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=F}build(T){return new xM(T,this.config)}}class xM extends C{static[M]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,o){super(T,o);this.sqlName=o.customTypeParams.dataType(o.fieldConfig),this.mapTo=o.customTypeParams.toDriver,this.mapFrom=o.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function bM(T){return(o,F)=>{let{name:A,config:y}=fT(o,F);return new jM(A,y,T)}}class GF extends q{static[M]="PgDateColumnBaseBuilder";defaultNow(){return this.default(X`now()`)}}class qM extends GF{static[M]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new sS(T,this.config)}}class sS extends C{static[M]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class vM extends GF{static[M]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new aS(T,this.config)}}class aS extends C{static[M]="PgDateString";getSQLType(){return"date"}}function PM(T,o){let{name:F,config:A}=fT(T,o);if(A?.mode==="date")return new qM(F);return new vM(F)}class mM extends q{static[M]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new tM(T,this.config)}}class tM extends C{static[M]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function hM(T){return new mM(T??"")}class gM extends q{static[M]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new nM(T,this.config)}}class nM extends C{static[M]="PgInet";getSQLType(){return"inet"}}function uM(T){return new gM(T??"")}class cM extends pF{static[M]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new iM(T,this.config)}}class iM extends C{static[M]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function xy(T){return new cM(T??"")}class dM extends q{static[M]="PgIntervalBuilder";constructor(T,o){super(T,"string","PgInterval");this.config.intervalConfig=o}build(T){return new rM(T,this.config)}}class rM extends C{static[M]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",o=this.precision?`(${this.precision})`:"";return`interval${T}${o}`}}function lM(T,o={}){let{name:F,config:A}=fT(T,o);return new dM(F,A)}class sM extends q{static[M]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new eS(T,this.config)}}class eS extends C{static[M]="PgJson";constructor(T,o){super(T,o)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function aM(T){return new sM(T??"")}class eM extends q{static[M]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new Tf(T,this.config)}}class Tf extends C{static[M]="PgJsonb";constructor(T,o){super(T,o)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function TO(T){return new eM(T??"")}class oO extends q{static[M]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new FO(T,this.config)}}class FO extends C{static[M]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[o,F,A]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(F),Number.parseFloat(A)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class AO extends q{static[M]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new yO(T,this.config)}}class yO extends C{static[M]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[o,F,A]=T.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(F),c:Number.parseFloat(A)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function SO(T,o){let{name:F,config:A}=fT(T,o);if(!A?.mode||A.mode==="tuple")return new oO(F);return new AO(F)}class fO extends q{static[M]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new $O(T,this.config)}}class $O extends C{static[M]="PgMacaddr";getSQLType(){return"macaddr"}}function JO(T){return new fO(T??"")}class _O extends q{static[M]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new RO(T,this.config)}}class RO extends C{static[M]="PgMacaddr8";getSQLType(){return"macaddr8"}}function WO(T){return new _O(T??"")}class MO extends q{static[M]="PgNumericBuilder";constructor(T,o,F){super(T,"string","PgNumeric");this.config.precision=o,this.config.scale=F}build(T){return new of(T,this.config)}}class of extends C{static[M]="PgNumeric";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}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 OO extends q{static[M]="PgNumericNumberBuilder";constructor(T,o,F){super(T,"number","PgNumericNumber");this.config.precision=o,this.config.scale=F}build(T){return new XO(T,this.config)}}class XO extends C{static[M]="PgNumericNumber";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}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 YO extends q{static[M]="PgNumericBigIntBuilder";constructor(T,o,F){super(T,"bigint","PgNumericBigInt");this.config.precision=o,this.config.scale=F}build(T){return new ZO(T,this.config)}}class ZO extends C{static[M]="PgNumericBigInt";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.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 HO(T,o){let{name:F,config:A}=fT(T,o),y=A?.mode;return y==="number"?new OO(F,A?.precision,A?.scale):y==="bigint"?new YO(F,A?.precision,A?.scale):new MO(F,A?.precision,A?.scale)}class GO extends q{static[M]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new wO(T,this.config)}}class wO extends C{static[M]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,F]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class EO extends q{static[M]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new KO(T,this.config)}}class KO extends C{static[M]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function UO(T,o){let{name:F,config:A}=fT(T,o);if(!A?.mode||A.mode==="tuple")return new GO(F);return new EO(F)}function BZ(T){let o=[];for(let F=0;F<T.length;F+=2)o.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(o)}function zO(T,o){let F=new ArrayBuffer(8),A=new DataView(F);for(let y=0;y<8;y++)A.setUint8(y,T[o+y]);return A.getFloat64(0,!0)}function PJ(T){let o=BZ(T),F=0,A=o[F];F+=1;let y=new DataView(o.buffer),S=y.getUint32(F,A===1);F+=4;let f;if(S&536870912)f=y.getUint32(F,A===1),F+=4;if((S&65535)===1){let $=zO(o,F);F+=8;let _=zO(o,F);return F+=8,[$,_]}throw new Error("Unsupported geometry type")}class QO extends q{static[M]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new VO(T,this.config)}}class VO extends C{static[M]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return PJ(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class DO extends q{static[M]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new LO(T,this.config)}}class LO extends C{static[M]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let o=PJ(T);return{x:o[0],y:o[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function CO(T,o){let{name:F,config:A}=fT(T,o);if(!A?.mode||A.mode==="tuple")return new QO(F);return new DO(F)}class IO extends q{static[M]="PgRealBuilder";constructor(T,o){super(T,"number","PgReal");this.config.length=o}build(T){return new kO(T,this.config)}}class kO extends C{static[M]="PgReal";constructor(T,o){super(T,o)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function BO(T){return new IO(T??"")}class NO extends q{static[M]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new pO(T,this.config)}}class pO extends C{static[M]="PgSerial";getSQLType(){return"serial"}}function jO(T){return new NO(T??"")}class xO extends pF{static[M]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new bO(T,this.config)}}class bO extends C{static[M]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function qO(T){return new xO(T??"")}class vO extends q{static[M]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new PO(T,this.config)}}class PO extends C{static[M]="PgSmallSerial";getSQLType(){return"smallserial"}}function mO(T){return new vO(T??"")}class tO extends q{static[M]="PgTextBuilder";constructor(T,o){super(T,"string","PgText");this.config.enumValues=o.enum}build(T){return new hO(T,this.config)}}class hO extends C{static[M]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function gO(T,o={}){let{name:F,config:A}=fT(T,o);return new tO(F,A)}class nO extends GF{constructor(T,o,F){super(T,"string","PgTime");this.withTimezone=o,this.precision=F,this.config.withTimezone=o,this.config.precision=F}static[M]="PgTimeBuilder";build(T){return new Ff(T,this.config)}}class Ff extends C{static[M]="PgTime";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function uO(T,o={}){let{name:F,config:A}=fT(T,o);return new nO(F,A.withTimezone??!1,A.precision)}class cO extends GF{static[M]="PgTimestampBuilder";constructor(T,o,F){super(T,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=F}build(T){return new Af(T,this.config)}}class Af extends C{static[M]="PgTimestamp";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class iO extends GF{static[M]="PgTimestampStringBuilder";constructor(T,o,F){super(T,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=F}build(T){return new yf(T,this.config)}}class yf extends C{static[M]="PgTimestampString";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function io(T,o={}){let{name:F,config:A}=fT(T,o);if(A?.mode==="string")return new iO(F,A.withTimezone??!1,A.precision);return new cO(F,A?.withTimezone??!1,A?.precision)}class dO extends q{static[M]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(X`gen_random_uuid()`)}build(T){return new Sf(T,this.config)}}class Sf extends C{static[M]="PgUUID";getSQLType(){return"uuid"}}function qo(T){return new dO(T??"")}class rO extends q{static[M]="PgVarcharBuilder";constructor(T,o){super(T,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new lO(T,this.config)}}class lO extends C{static[M]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function Mo(T,o={}){let{name:F,config:A}=fT(T,o);return new rO(F,A)}class sO extends q{static[M]="PgBinaryVectorBuilder";constructor(T,o){super(T,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(T){return new aO(T,this.config)}}class aO extends C{static[M]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function eO(T,o){let{name:F,config:A}=fT(T,o);return new sO(F,A)}class T2 extends q{static[M]="PgHalfVectorBuilder";constructor(T,o){super(T,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(T){return new o2(T,this.config)}}class o2 extends C{static[M]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function F2(T,o){let{name:F,config:A}=fT(T,o);return new T2(F,A)}class A2 extends q{static[M]="PgSparseVectorBuilder";constructor(T,o){super(T,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(T){return new y2(T,this.config)}}class y2 extends C{static[M]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function S2(T,o){let{name:F,config:A}=fT(T,o);return new A2(F,A)}class f2 extends q{static[M]="PgVectorBuilder";constructor(T,o){super(T,"array","PgVector");this.config.dimensions=o.dimensions}build(T){return new $2(T,this.config)}}class $2 extends C{static[M]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function J2(T,o){let{name:F,config:A}=fT(T,o);return new f2(F,A)}function _2(){return{bigint:EM,bigserial:VM,boolean:jy,char:kM,cidr:pM,customType:bM,date:PM,doublePrecision:hM,inet:uM,integer:xy,interval:lM,json:aM,jsonb:TO,line:SO,macaddr:JO,macaddr8:WO,numeric:HO,point:UO,geometry:CO,real:BO,serial:jO,smallint:qO,smallserial:mO,text:gO,time:uO,timestamp:io,uuid:qo,varchar:Mo,bit:eO,halfvec:F2,sparsevec:S2,vector:J2}}var mJ=Symbol.for("drizzle:PgInlineForeignKeys"),R2=Symbol.for("drizzle:EnableRLS");class eT extends x{static[M]="PgTable";static Symbol=Object.assign({},x.Symbol,{InlineForeignKeys:mJ,EnableRLS:R2});[mJ]=[];[R2]=!1;[x.Symbol.ExtraConfigBuilder]=void 0;[x.Symbol.ExtraConfigColumns]={}}function NZ(T,o,F,A,y=T){let S=new eT(T,A,y),f=typeof o==="function"?o(_2()):o,$=Object.fromEntries(Object.entries(f).map(([R,O])=>{let Y=O;Y.setName(R);let H=Y.build(S);return S[mJ].push(...Y.buildForeignKeys(H,S)),[R,H]})),_=Object.fromEntries(Object.entries(f).map(([R,O])=>{let Y=O;Y.setName(R);let H=Y.buildExtraConfigColumn(S);return[R,H]})),J=Object.assign(S,$);if(J[x.Symbol.Columns]=$,J[x.Symbol.ExtraConfigColumns]=_,F)J[eT.Symbol.ExtraConfigBuilder]=F;return Object.assign(J,{enableRLS:()=>{return J[eT.Symbol.EnableRLS]=!0,J}})}var jF=(T,o,F)=>{return NZ(T,o,F,void 0)};function W2(...T){if(T[0].columns)return new by(T[0].columns,T[0].name);return new by(T)}class by{static[M]="PgPrimaryKeyBuilder";columns;name;constructor(T,o){this.columns=T,this.name=o}build(T){return new M2(T,this.columns,this.name)}}class M2{constructor(T,o,F){this.table=T,this.columns=o,this.name=F}static[M]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[eT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function zo(T,o){if(JM(o)&&!pJ(T)&&!w(T,Co)&&!w(T,NF)&&!w(T,GT)&&!w(T,x)&&!w(T,Uo))return new Co(T,o);return T}var ff=(T,o)=>{return X`${T} = ${zo(o,T)}`},O2=(T,o)=>{return X`${T} <> ${zo(o,T)}`};function qy(...T){let o=T.filter((F)=>F!==void 0);if(o.length===0)return;if(o.length===1)return new b(o);return new b([new dT("("),X.join(o,new dT(" and ")),new dT(")")])}function X2(...T){let o=T.filter((F)=>F!==void 0);if(o.length===0)return;if(o.length===1)return new b(o);return new b([new dT("("),X.join(o,new dT(" or ")),new dT(")")])}function Y2(T){return X`not ${T}`}var Z2=(T,o)=>{return X`${T} > ${zo(o,T)}`},H2=(T,o)=>{return X`${T} >= ${zo(o,T)}`},G2=(T,o)=>{return X`${T} < ${zo(o,T)}`},w2=(T,o)=>{return X`${T} <= ${zo(o,T)}`};function E2(T,o){if(Array.isArray(o)){if(o.length===0)return X`false`;return X`${T} in ${o.map((F)=>zo(F,T))}`}return X`${T} in ${zo(o,T)}`}function K2(T,o){if(Array.isArray(o)){if(o.length===0)return X`true`;return X`${T} not in ${o.map((F)=>zo(F,T))}`}return X`${T} not in ${zo(o,T)}`}function U2(T){return X`${T} is null`}function z2(T){return X`${T} is not null`}function Q2(T){return X`exists ${T}`}function V2(T){return X`not exists ${T}`}function D2(T,o,F){return X`${T} between ${zo(o,T)} and ${zo(F,T)}`}function L2(T,o,F){return X`${T} not between ${zo(o,T)} and ${zo(F,T)}`}function C2(T,o){return X`${T} like ${o}`}function I2(T,o){return X`${T} not like ${o}`}function k2(T,o){return X`${T} ilike ${o}`}function B2(T,o){return X`${T} not ilike ${o}`}function N2(T){return X`${T} asc`}function p2(T){return X`${T} desc`}class tJ{constructor(T,o,F){this.sourceTable=T,this.referencedTable=o,this.relationName=F,this.referencedTableName=o[x.Symbol.Name]}static[M]="Relation";referencedTableName;fieldName}class j2{constructor(T,o){this.table=T,this.config=o}static[M]="Relations"}class xF extends tJ{constructor(T,o,F,A){super(T,o,F?.relationName);this.config=F,this.isNullable=A}static[M]="One";withFieldName(T){let o=new xF(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=T,o}}class vy extends tJ{constructor(T,o,F){super(T,o,F?.relationName);this.config=F}static[M]="Many";withFieldName(T){let o=new vy(this.sourceTable,this.referencedTable,this.config);return o.fieldName=T,o}}function x2(){return{and:qy,between:D2,eq:ff,exists:Q2,gt:Z2,gte:H2,ilike:k2,inArray:E2,isNull:U2,isNotNull:z2,like:C2,lt:G2,lte:w2,ne:O2,not:Y2,notBetween:L2,notExists:V2,notLike:I2,notIlike:B2,notInArray:K2,or:X2,sql:X}}function b2(){return{sql:X,asc:N2,desc:p2}}function q2(T,o){if(Object.keys(T).length===1&&"default"in T&&!w(T.default,x))T=T.default;let F={},A={},y={};for(let[S,f]of Object.entries(T))if(w(f,x)){let $=rF(f),_=A[$];F[$]=S,y[S]={tsName:S,dbName:f[x.Symbol.Name],schema:f[x.Symbol.Schema],columns:f[x.Symbol.Columns],relations:_?.relations??{},primaryKey:_?.primaryKey??[]};for(let R of Object.values(f[x.Symbol.Columns]))if(R.primary)y[S].primaryKey.push(R);let J=f[x.Symbol.ExtraConfigBuilder]?.(f[x.Symbol.ExtraConfigColumns]);if(J){for(let R of Object.values(J))if(w(R,by))y[S].primaryKey.push(...R.columns)}}else if(w(f,j2)){let $=rF(f.table),_=F[$],J=f.config(o(f.table)),R;for(let[O,Y]of Object.entries(J))if(_){let H=y[_];if(H.relations[O]=Y,R)H.primaryKey.push(...R)}else{if(!($ in A))A[$]={relations:{},primaryKey:R};A[$].relations[O]=Y}}return{tables:y,tableNamesMap:F}}function pZ(T){return function o(F,A){return new xF(T,F,A,A?.fields.reduce((y,S)=>y&&S.notNull,!0)??!1)}}function jZ(T){return function o(F,A){return new vy(T,F,A)}}function v2(T,o,F){if(w(F,xF)&&F.config)return{fields:F.config.fields,references:F.config.references};let A=o[rF(F.referencedTable)];if(!A)throw new Error(`Table "${F.referencedTable[x.Symbol.Name]}" not found in schema`);let y=T[A];if(!y)throw new Error(`Table "${A}" not found in schema`);let S=F.sourceTable,f=o[rF(S)];if(!f)throw new Error(`Table "${S[x.Symbol.Name]}" not found in schema`);let $=[];for(let _ of Object.values(y.relations))if(F.relationName&&F!==_&&_.relationName===F.relationName||!F.relationName&&_.referencedTable===F.sourceTable)$.push(_);if($.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${A}"`):new Error(`There are multiple relations between "${A}" and "${F.sourceTable[x.Symbol.Name]}". Please specify relation name`);if($[0]&&w($[0],xF)&&$[0].config)return{fields:$[0].config.references,references:$[0].config.fields};throw new Error(`There is not enough information to infer relation "${f}.${F.fieldName}"`)}function P2(T){return{one:pZ(T),many:jZ(T)}}function $f(T,o,F,A,y=(S)=>S){let S={};for(let[f,$]of A.entries())if($.isJson){let _=o.relations[$.tsKey],J=F[f],R=typeof J==="string"?JSON.parse(J):J;S[$.tsKey]=w(_,xF)?R&&$f(T,T[$.relationTableTsKey],R,$.selection,y):R.map((O)=>$f(T,T[$.relationTableTsKey],O,$.selection,y))}else{let _=y(F[f]),J=$.field,R;if(w(J,GT))R=J;else if(w(J,b))R=J.decoder;else R=J.sql.decoder;S[$.tsKey]=_===null?null:R.mapFromDriverValue(_)}return S}import yH from"os";import SH from"fs";var Jf=new Map,hJ=new Map,gJ=Symbol("OriginError"),NA={};class vo extends Promise{constructor(T,o,F,A,y={}){let S,f;super(($,_)=>{S=$,f=_});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=o,this.handler=F,this.canceller=A,this.options=y,this.state=null,this.statement=null,this.resolve=($)=>(this.active=!1,S($)),this.reject=($)=>(this.active=!1,f($)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[gJ]=this.handler.debug?new Error:this.tagged&&xZ(this.strings)}get origin(){return(this.handler.debug?this[gJ].stack:this.tagged&&hJ.has(this.strings)?hJ.get(this.strings):hJ.set(this.strings,this[gJ].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,o){if(this.options.simple=!1,typeof T==="function")o=T,T=1;if(this.cursorRows=T,typeof o==="function")return this.cursorFn=o,this;let F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let A=new Promise((y,S)=>{this.cursorFn=(f)=>{return y({value:f,done:!1}),new Promise(($)=>F=$)},this.resolve=()=>(this.active=!1,y({done:!0})),this.reject=(f)=>(this.active=!1,S(f))});return this.execute(),A},return(){return F&&F(NA),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function xZ(T){if(Jf.has(T))return Jf.get(T);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,Jf.set(T,new Error),Error.stackTraceLimit=o,Jf.get(T)}class pA extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var qT={connection:m2,postgres:t2,generic:h2,notSupported:g2};function m2(T,o,F){let{host:A,port:y}=F||o,S=Object.assign(new Error("write "+T+" "+(o.path||A+":"+y)),{code:T,errno:T,address:o.path||A},o.path?{}:{port:y});return Error.captureStackTrace(S,m2),S}function t2(T){let o=new pA(T);return Error.captureStackTrace(o,t2),o}function h2(T,o){let F=Object.assign(new Error(T+": "+o),{code:T});return Error.captureStackTrace(F,h2),F}function g2(T){let o=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(o,g2),o}var bZ={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class Wf{then(){nJ()}catch(){nJ()}finally(){nJ()}}class hy extends Wf{constructor(T){super();this.value=Xf(T)}}class FF extends Wf{constructor(T,o,F){super();this.value=T,this.type=o,this.array=F}}class Mf extends Wf{constructor(T,o){super();this.first=T,this.rest=o}build(T,o,F,A){let y=qZ.map(([S,f])=>({fn:f,i:T.search(S)})).sort((S,f)=>S.i-f.i).pop();return y.i===-1?rJ(this.first,A):y.fn(this.first,this.rest,o,F,A)}}function Of(T,o,F,A){let y=T instanceof FF?T.value:T;if(y===void 0){if(T instanceof FF?T.value=A.transform.undefined:y=T=A.transform.undefined,y===void 0)throw qT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof FF?(o.push(T.value),T.array?T.array[T.type||Rf(T.value)]||T.type||i2(T.value):T.type):(o.push(T),Rf(T)))}var u2=r2(bZ);function iJ(T,o,F,A,y,S){for(let f=1;f<T.strings.length;f++)o+=dJ(o,F,A,y,S)+T.strings[f],F=T.args[f];return o}function dJ(T,o,F,A,y){return o instanceof Mf?o.build(T,F,A,y):o instanceof vo?cJ(o,F,A,y):o instanceof hy?o.value:o&&o[0]instanceof vo?o.reduce((S,f)=>S+" "+cJ(f,F,A,y),""):Of(o,F,A,y)}function cJ(T,o,F,A){return T.fragment=!0,iJ(T,T.strings[0],T.args[0],o,F,A)}function c2(T,o,F,A,y){return T.map((S)=>"("+A.map((f)=>dJ("values",S[f],o,F,y)).join(",")+")").join(",")}function n2(T,o,F,A,y){let S=Array.isArray(T[0]),f=o.length?o.flat():Object.keys(S?T[0]:T);return c2(S?T:[T],F,A,f,y)}function _f(T,o,F,A,y){if(typeof T==="string"&&(T=[T].concat(o)),Array.isArray(T))return rJ(T,y);let S;return(o.length?o.flat():Object.keys(T)).map(($)=>{return S=T[$],(S instanceof vo?cJ(S,F,A,y):S instanceof hy?S.value:Of(S,F,A,y))+" as "+Xf(y.transform.column.to?y.transform.column.to($):$)}).join(",")}var qZ=Object.entries({values:n2,in:(...T)=>{let o=n2(...T);return o==="()"?"(null)":o},select:_f,as:_f,returning:_f,"\\(":_f,update(T,o,F,A,y){return(o.length?o.flat():Object.keys(T)).map((S)=>Xf(y.transform.column.to?y.transform.column.to(S):S)+"="+dJ("values",T[S],F,A,y))},insert(T,o,F,A,y){let S=o.length?o.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+rJ(S,y)+")values"+c2(Array.isArray(T)?T:[T],F,A,S,y)}}).map(([T,o])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function nJ(){throw qT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:vZ,parsers:PZ}=u2;function i2(T){if(Array.isArray(T))return i2(T[0]);return typeof T==="string"?1009:0}var d2=function(T){let o=r2(T||{});return{serializers:Object.assign({},vZ,o.serializers),parsers:Object.assign({},PZ,o.parsers)}};function r2(T){return Object.keys(T).reduce((o,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((A)=>o.parsers[A]=T[F].parse),T[F].serialize)o.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((A)=>o.serializers[A]=T[F].serialize);return o},{parsers:{},serializers:{}})}function rJ(T,{transform:{column:o}}){return T.map((F)=>Xf(o.to?o.to(F):F)).join(",")}var Xf=function T(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Rf=function T(o){return o instanceof FF?o.type:o instanceof Date?1184:o instanceof Uint8Array?17:o===!0||o===!1?16:typeof o==="bigint"?20:Array.isArray(o)?T(o[0]):0},mZ=/\\/g,tZ=/"/g;function hZ(T){return T.replace(mZ,"\\\\").replace(tZ,"\\\"")}var l2=function T(o,F,A,y){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let S=o[0],f=y===1020?";":",";if(Array.isArray(S)&&!S.type)return"{"+o.map(($)=>T($,F,A,y)).join(f)+"}";return"{"+o.map(($)=>{if($===void 0){if($=A.transform.undefined,$===void 0)throw qT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return $===null?"null":'"'+hZ(F?F($.type?$.value:$):""+$)+'"'}).join(f)+"}"},uJ={i:0,char:null,str:"",quoted:!1,last:0},s2=function T(o,F,A){return uJ.i=uJ.last=0,a2(uJ,o,F,A)};function a2(T,o,F,A){let y=[],S=A===1020?";":",";for(;T.i<o.length;T.i++){if(T.char=o[T.i],T.quoted)if(T.char==="\\")T.str+=o[++T.i];else if(T.char==='"')y.push(F?F(T.str):T.str),T.str="",T.quoted=o[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,y.push(a2(T,o,F,A));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&y.push(F?F(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===S&&T.p!=="}"&&T.p!=='"')y.push(F?F(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&y.push(F?F(o.slice(T.last,T.i+1)):o.slice(T.last,T.i+1)),y}var lF=(T)=>{let o=T[0];for(let F=1;F<T.length;F++)o+=T[F]==="_"?T[++F].toUpperCase():T[F];return o},sF=(T)=>{let o=T[0].toUpperCase();for(let F=1;F<T.length;F++)o+=T[F]==="_"?T[++F].toUpperCase():T[F];return o},aF=(T)=>T.replace(/_/g,"-"),Py=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),my=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),ty=(T)=>T.replace(/-/g,"_");function lJ(T){return function o(F,A){return typeof F==="object"&&F!==null&&(A.type===114||A.type===3802)?Array.isArray(F)?F.map((y)=>o(y,A)):Object.entries(F).reduce((y,[S,f])=>Object.assign(y,{[T(S)]:o(f,A)}),{}):F}}lF.column={from:lF};lF.value={from:lJ(lF)};Py.column={to:Py};var sJ={...lF};sJ.column.to=Py;sF.column={from:sF};sF.value={from:lJ(sF)};my.column={to:my};var aJ={...sF};aJ.column.to=my;aF.column={from:aF};aF.value={from:lJ(aF)};ty.column={to:ty};var eJ={...aF};eJ.column.to=ty;import e2 from"net";import cZ from"tls";import gy from"crypto";import T_ from"stream";import{performance as T4}from"perf_hooks";class eF 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 Io=gZ;function gZ(T=[]){let o=T.slice(),F=0;return{get length(){return o.length-F},remove:(A)=>{let y=o.indexOf(A);return y===-1?null:(o.splice(y,1),A)},push:(A)=>(o.push(A),A),shift:()=>{let A=o[F++];if(F===o.length)F=0,o=[];else o[F-1]=void 0;return A}}}var $o=Buffer.allocUnsafe(256),nZ="BCcDdEFfHPpQSX".split("").reduce((T,o)=>{let F=o.charCodeAt(0);return T[o]=()=>{return $o[0]=F,YT.i=5,YT},T},{}),YT=Object.assign(uZ,nZ,{N:String.fromCharCode(0),i:0,inc(T){return YT.i+=T,YT},str(T){let o=Buffer.byteLength(T);return Yf(o),YT.i+=$o.write(T,YT.i,o,"utf8"),YT},i16(T){return Yf(2),$o.writeUInt16BE(T,YT.i),YT.i+=2,YT},i32(T,o){if(o||o===0)return $o.writeUInt32BE(T,o),YT;return Yf(4),$o.writeUInt32BE(T,YT.i),YT.i+=4,YT},z(T){return Yf(T),$o.fill(0,YT.i,YT.i+T),YT.i+=T,YT},raw(T){return $o=Buffer.concat([$o.subarray(0,YT.i),T]),YT.i=$o.length,YT},end(T=1){$o.writeUInt32BE(YT.i-T,T);let o=$o.subarray(0,YT.i);return YT.i=0,$o=Buffer.allocUnsafe(256),o}}),u=YT;function Yf(T){if($o.length-YT.i<T){let o=$o,F=o.length;$o=Buffer.allocUnsafe(F+(F>>1)+T),o.copy($o)}}function uZ(){return YT.i=0,YT}var A_=A4,iZ=1,bF=u().S().end(),o4=u().H().end(),dZ=u().i32(8).i32(80877103).end(8),rZ=Buffer.concat([u().E().str(u.N).i32(0).end(),bF]),lZ=u().D().str("S").str(u.N).end(),jA=()=>{},sZ=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),aZ={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 A4(T,o={},{onopen:F=jA,onend:A=jA,onclose:y=jA}={}){let{ssl:S,max:f,user:$,host:_,port:J,database:R,parsers:O,transform:Y,onnotice:H,onnotify:Q,onparameter:E,max_pipeline:B,keep_alive:p,backoff:v,target_session_attrs:h}=T,U=Io(),V=iZ++,I={pid:null,secret:null},L=F_(Cf,T.idle_timeout),m=F_(Cf,T.max_lifetime),s=F_(V4,T.connect_timeout),z=null,a,t=new eF,e=Buffer.alloc(0),ZT=T.fetch_types,vT={},Xo={},AF=Math.random().toString(36).slice(2),D=1,g=0,_T=0,IT=0,PT=0,FT=0,ET=0,xT=0,kT=null,VT=null,To=!1,KT=null,Po=null,oo=null,wF=null,mT=null,DT=null,mo=null,ro=null,N=null,vA=null,Fo={queue:o.closed,idleTimer:L,connect(W){oo=W||!0,I_()},terminate:mA,execute:PA,cancel:K4,end:Cf,count:0,id:V};return o.closed&&o.closed.push(Fo),Fo;async function E4(){let W;try{W=T.socket?await Promise.resolve(T.socket(T)):new e2.Socket}catch(Z){AA(Z);return}return W.on("error",AA),W.on("close",k_),W.on("drain",L_),W}async function K4({pid:W,secret:Z},c,RT){try{a=u().i32(16).i32(80877102).i32(W).i32(Z).end(16),await C_(),z.once("error",RT),z.once("close",c)}catch(NT){RT(NT)}}function PA(W){if(To)return ly(W,qT.connection("CONNECTION_DESTROYED",T));if(W.cancelled)return;try{return W.state=I,N?U.push(W):(N=W,N.active=!0),Q4(W),sT(U4(W))&&!W.describeFirst&&!W.cursorFn&&U.length<B&&(!W.options.onexecute||W.options.onexecute(Fo))}catch(Z){return U.length===0&&sT(bF),lo(Z),!0}}function U4(W){if(W.parameters.length>=65534)throw qT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return W.options.simple?u().Q().str(W.statement.string+u.N).end():W.describeFirst?Buffer.concat([Q_(W),o4]):W.prepare?W.prepared?ry(W):Buffer.concat([Q_(W),ry(W)]):z4(W)}function Q_(W){return Buffer.concat([N_(W.statement.string,W.parameters,W.statement.types,W.statement.name),_X("S",W.statement.name)])}function ry(W){return Buffer.concat([JX(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?p_("",W.cursorRows):rZ])}function z4(W){return Buffer.concat([N_(W.statement.string,W.parameters,W.statement.types),lZ,ry(W)])}function Q4(W){let Z=[],c=[],RT=iJ(W,W.strings[0],W.args[0],Z,c,T);!W.tagged&&W.args.forEach((NT)=>Of(NT,Z,c,T)),W.prepare=T.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=RT,W.signature=W.prepare&&c+RT,W.onlyDescribe&&delete Xo[W.signature],W.parameters=W.parameters||Z,W.prepared=W.prepare&&W.signature in Xo,W.describeFirst=W.onlyDescribe||Z.length&&!W.prepared,W.statement=W.prepared?Xo[W.signature]:{string:RT,types:c,name:W.prepare?AF+D++:""},typeof T.debug==="function"&&T.debug(V,RT,Z,c)}function sT(W,Z){if(DT=DT?Buffer.concat([DT,W]):Buffer.from(W),Z||DT.length>=1024)return V_(Z);return VT===null&&(VT=setImmediate(V_)),!0}function V_(W){let Z=z.write(DT,W);return VT!==null&&clearImmediate(VT),DT=VT=null,Z}function V4(){lo(qT.connection("CONNECT_TIMEOUT",T,z)),z.destroy()}async function D_(){if(sT(dZ),!await new Promise((Z)=>z.once("data",(c)=>Z(c[0]===83)))&&S==="prefer")return FA();z.removeAllListeners(),z=cZ.connect({socket:z,servername:e2.isIP(z.host)?void 0:z.host,...S==="require"||S==="allow"||S==="prefer"?{rejectUnauthorized:!1}:S==="verify-full"?{}:typeof S==="object"?S:{}}),z.on("secureConnect",FA),z.on("error",AA),z.on("close",k_),z.on("drain",L_)}function L_(){!N&&F(Fo)}function Lf(W){if(KT){if(KT.push(W),_T-=W.length,_T>=0)return}e=KT?Buffer.concat(KT,FT-_T):e.length===0?W:Buffer.concat([e,W],e.length+W.length);while(e.length>4){if(FT=e.readUInt32BE(1),FT>=e.length){_T=FT-e.length,KT=[e];break}try{D4(e.subarray(0,FT+1))}catch(Z){N&&(N.cursorFn||N.describeFirst)&&sT(bF),lo(Z)}e=e.subarray(FT+1),_T=0,KT=null}}async function C_(){if(To=!1,vT={},z||(z=await E4()),!z)return;if(s.start(),T.socket)return S?D_():FA();if(z.on("connect",S?D_:FA),T.path)return z.connect(T.path);z.ssl=S,z.connect(J[IT],_[IT]),z.host=_[IT],z.port=J[IT],IT=(IT+1)%J.length}function I_(){setTimeout(C_,g?g+ET-T4.now():0)}function FA(){try{Xo={},ZT=T.fetch_types,AF=Math.random().toString(36).slice(2),D=1,m.start(),z.on("data",Lf),p&&z.setKeepAlive&&z.setKeepAlive(!0,1000*p);let W=WX();sT(W)}catch(W){AA(W)}}function AA(W){if(Fo.queue===o.connecting&&T.host[PT+1])return;lo(W);while(U.length)ly(U.shift(),W)}function lo(W){mT&&(mT.destroy(W),mT=null),N&&ly(N,W),oo&&(ly(oo,W),oo=null)}function ly(W,Z){"query"in Z||"parameters"in Z||Object.defineProperties(Z,{stack:{value:Z.stack+W.origin.replace(/.*\n/,`
61
- `),enumerable:T.debug},query:{value:W.string,enumerable:T.debug},parameters:{value:W.parameters,enumerable:T.debug},args:{value:W.args,enumerable:T.debug},types:{value:W.statement&&W.statement.types,enumerable:T.debug}}),W.reject(Z)}function Cf(){return wF||(!Fo.reserved&&A(Fo),!Fo.reserved&&!oo&&!N&&U.length===0?(mA(),new Promise((W)=>z&&z.readyState!=="closed"?z.once("close",W):W())):wF=new Promise((W)=>mo=W))}function mA(){if(To=!0,mT||N||oo||U.length)AA(qT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(VT),z)z.removeListener("data",Lf),z.removeListener("connect",FA),z.readyState==="open"&&z.end(u().X().end());mo&&(mo(),wF=mo=null)}async function k_(W){if(e=Buffer.alloc(0),_T=0,KT=null,clearImmediate(VT),z.removeListener("data",Lf),z.removeListener("connect",FA),L.cancel(),m.cancel(),s.cancel(),z.removeAllListeners(),z=null,oo)return I_();!W&&(N||U.length)&&AA(qT.connection("CONNECTION_CLOSED",T,z)),g=T4.now(),W&&T.shared.retries++,ET=(typeof v==="function"?v(T.shared.retries):v)*1000,y(Fo,qT.connection("CONNECTION_CLOSED",T,z))}function D4(W,Z=W[0]){(Z===68?L4:Z===100?TX:Z===65?d4:Z===83?C4:Z===90?I4:Z===67?k4:Z===50?B_:Z===49?B4:Z===116?N4:Z===84?p4:Z===82?j4:Z===110?m4:Z===75?t4:Z===69?c4:Z===115?r4:Z===51?l4:Z===71?s4:Z===78?FX:Z===72?a4:Z===99?oX:Z===73?AX:Z===86?yX:Z===118?SX:Z===87?e4:fX)(W)}function L4(W){let Z=7,c,RT,NT,Ao=N.isRaw?new Array(N.statement.columns.length):{};for(let Jo=0;Jo<N.statement.columns.length;Jo++)RT=N.statement.columns[Jo],c=W.readInt32BE(Z),Z+=4,NT=c===-1?null:N.isRaw===!0?W.subarray(Z,Z+=c):RT.parser===void 0?W.toString("utf8",Z,Z+=c):RT.parser.array===!0?RT.parser(W.toString("utf8",Z+1,Z+=c)):RT.parser(W.toString("utf8",Z,Z+=c)),N.isRaw?Ao[Jo]=N.isRaw===!0?NT:Y.value.from?Y.value.from(NT,RT):NT:Ao[RT.name]=Y.value.from?Y.value.from(NT,RT):NT;N.forEachFn?N.forEachFn(Y.row.from?Y.row.from(Ao):Ao,t):t[xT++]=Y.row.from?Y.row.from(Ao):Ao}function C4(W){let[Z,c]=W.toString("utf8",5,W.length-1).split(u.N);if(vT[Z]=c,T.parameters[Z]!==c)T.parameters[Z]=c,E&&E(Z,c)}function I4(W){if(N&&N.options.simple&&N.resolve(Po||t),N=Po=null,t=new eF,s.cancel(),oo){if(h){if(!vT.in_hot_standby||!vT.default_transaction_read_only)return u4();else if(n4(h,vT))return mA()}if(ZT)return oo===!0&&(oo=null),h4();oo!==!0&&PA(oo),T.shared.retries=PT=0,oo=null;return}while(U.length&&(N=U.shift())&&(N.active=!0,N.cancelled))A4(T).cancel(N.state,N.cancelled.resolve,N.cancelled.reject);if(N)return;Fo.reserved?!Fo.reserved.release&&W[5]===73?wF?mA():(Fo.reserved=null,F(Fo)):Fo.reserved():wF?mA():F(Fo)}function k4(W){xT=0;for(let Z=W.length-1;Z>0;Z--){if(W[Z]===32&&W[Z+1]<58&&t.count===null)t.count=+W.toString("utf8",Z+1,W.length-1);if(W[Z-1]>=65){t.command=W.toString("utf8",5,Z),t.state=I;break}}if(vA&&(vA(),vA=null),t.command==="BEGIN"&&f!==1&&!Fo.reserved)return lo(qT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(N.options.simple)return B_();if(N.cursorFn)t.count&&N.cursorFn(t),sT(bF);N.resolve(t)}function B4(){N.parsing=!1}function B_(){!t.statement&&(t.statement=N.statement),t.columns=N.statement.columns}function N4(W){let Z=W.readUInt16BE(5);for(let c=0;c<Z;++c)!N.statement.types[c]&&(N.statement.types[c]=W.readUInt32BE(7+c*4));N.prepare&&(Xo[N.signature]=N.statement),N.describeFirst&&!N.onlyDescribe&&(sT(ry(N)),N.describeFirst=!1)}function p4(W){if(t.command)Po=Po||[t],Po.push(t=new eF),t.count=null,N.statement.columns=null;let Z=W.readUInt16BE(5),c=7,RT;N.statement.columns=Array(Z);for(let NT=0;NT<Z;++NT){RT=c;while(W[c++]!==0);let Ao=W.readUInt32BE(c),Jo=W.readUInt16BE(c+4),EF=W.readUInt32BE(c+6);N.statement.columns[NT]={name:Y.column.from?Y.column.from(W.toString("utf8",RT,c-1)):W.toString("utf8",RT,c-1),parser:O[EF],table:Ao,number:Jo,type:EF},c+=18}if(t.statement=N.statement,N.onlyDescribe)return N.resolve(N.statement),sT(bF)}async function j4(W,Z=W.readUInt32BE(5)){(Z===3?x4:Z===5?b4:Z===10?q4:Z===11?v4:Z===12?P4:Z!==0?$X:jA)(W,Z)}async function x4(){let W=await If();sT(u().p().str(W).z(1).end())}async function b4(W){let Z="md5"+await F4(Buffer.concat([Buffer.from(await F4(await If()+$)),W.subarray(9)]));sT(u().p().str(Z).z(1).end())}async function q4(){ro=(await gy.randomBytes(18)).toString("base64"),u().p().str("SCRAM-SHA-256"+u.N);let W=u.i;sT(u.inc(4).str("n,,n=*,r="+ro).i32(u.i-W-4,W).end())}async function v4(W){let Z=W.toString("utf8",9).split(",").reduce((Jo,EF)=>(Jo[EF[0]]=EF.slice(2),Jo),{}),c=await gy.pbkdf2Sync(await If(),Buffer.from(Z.s,"base64"),parseInt(Z.i),32,"sha256"),RT=await Zf(c,"Client Key"),NT="n=*,r="+ro+",r="+Z.r+",s="+Z.s+",i="+Z.i+",c=biws,r="+Z.r;kT=(await Zf(await Zf(c,"Server Key"),NT)).toString("base64");let Ao="c=biws,r="+Z.r+",p="+TH(RT,Buffer.from(await Zf(await eZ(RT),NT))).toString("base64");sT(u().p().str(Ao).end())}function P4(W){if(W.toString("utf8",9).split(u.N,1)[0].slice(2)===kT)return;lo(qT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),z.destroy()}function If(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function m4(){if(t.statement=N.statement,t.statement.columns=[],N.onlyDescribe)return N.resolve(N.statement),sT(bF)}function t4(W){I.pid=W.readUInt32BE(5),I.secret=W.readUInt32BE(9)}async function h4(){ZT=!1,(await new vo([`
47
+ `)+"}");class xW{config;resolvedConfig;name;get[iT](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,F){if(this.config=I_(w.config,F),this.resolvedConfig=I_(w.resolvedConfig,F),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(g2).length}`,this.name in g2)z(`A Scope already named ${this.name} already exists`);g2[this.name]=this;let _=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,J]of _){let $=W;if(W[0]==="#"){if($=W.slice(1),$ in this.aliases)z(G$($));this.aliases[$]=J}else{if($ in this.aliases)z(G$(W));this.aliases[$]=J,this.exportedNames.push($)}if(!q(J,"module")&&!q(J,"generic")&&!WF(J)){let Y=this.preparseOwnDefinitionFormat(J,{alias:$});this.resolutions[$]=q(Y,"root")?this.bindReference(Y):this.createParseContext(Y).id}}H$??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[H$.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=w.intrinsic?m(w.intrinsic,(W,J)=>W.startsWith("json")?[]:[W,this.bindReference(J)]):{}}cacheGetter(T,F){return Object.defineProperty(this,T,{value:F}),F}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let F=this;return(_,W)=>new XF(T,W?new kW(_):_,F,F,W??null)};units=(T,F)=>{let _=[];for(let J of T)if(!_.includes(J))_.push(J);let W=_.map((J)=>this.node("unit",{unit:J},F));return this.node("union",W,{...F,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,F){let _=this.node("alias",{reference:F??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(_);return _}schema=(T,F)=>this.finalize(this.parseSchema(T,F));parseSchema=(T,F)=>this.node(B_(T),T,F);preparseNode(T,F,_){let W=typeof T==="string"?T:B_(F,T);if(OT(F)&&F.kind===W)return F;if(W==="alias"&&!_?.prereduced){let{reference:Y}=v_.implementation.normalize(F,this);if(Y.startsWith("$")){let Z=this.resolveRoot(Y.slice(1));F=Z,W=Z.kind}}else if(W==="union"&&eT(F,"object")){let Y=o9(F);if(Y?.length===1)F=Y[0],W=B_(F)}if(OT(F)&&F.kind===W)return F;let $=cF[W].normalize?.(F,this)??F;if(OT($))return $.kind===W?$:u9(W,$.kind);return{..._,$:this,kind:W,def:$,prefix:_.alias??W}}bindReference(T){let F;if(OT(T))F=T.$===this?T:new T.constructor(T.attachments,this);else F=T.$===this?T:new XF(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,F.referencesById);return F}resolveRoot(T){return this.maybeResolveRoot(T)??z(u2(T))}maybeResolveRoot(T){let F=this.maybeResolve(T);if(q(F,"generic"))return;return F}maybeResolveSubalias(T){return m2(this.aliases,T)??m2(this.ambient,T)}get ambient(){return w.ambient}maybeResolve(T){let F=this.resolutions[T];if(F){if(typeof F!=="string")return this.bindReference(F);let W=tT[F];if(q(W,"root"))return this.resolutions[T]=W;if(q(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return a(`Unexpected resolved context for was uncached by its scope: ${o(W)}`);W.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",tT[J.id]=J,tT[W.id]=J,this.resolutions[T]=J}return a(`Unexpected nodesById entry for ${F}: ${o(W)}`)}let _=this.aliases[T]??this.ambient?.[T];if(!_)return this.maybeResolveSubalias(T);if(_=this.normalizeRootScopeValue(_),q(_,"generic"))return this.resolutions[T]=this.bindReference(_);if(q(_,"module")){if(!_.root)z(R$(T));return this.resolutions[T]=this.bindReference(_.root)}return this.resolutions[T]=this.parse(_,{alias:T})}createParseContext(T){let F=T.id??L2(T.prefix);return tT[F]=Object.assign(T,{[iT]:"context",$:this,id:F,phase:"unresolved"})}traversal(T){return new B0(T,this.resolvedConfig)}import(...T){return new iF(m(this.export(...T),(F,_)=>[`#${F}`,_]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let _ of this.exportedNames){let W=this.aliases[_];this._exports[_]=q(W,"module")?p2(W,this):O$(this.maybeResolve(_))}for(let _ of this.lazyResolutions)_.resolution;if(this._exportedResolutions=E$(this,this._exports),this._json=z$(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let _=Q$(this.references);this.precompilation=_.write(U$,4),M$(this.references,_)}this.resolved=!0}let F=T.length?T:this.exportedNames;return new iF(m(F,(_,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,F,_={})=>{let W=this.preparseNode(T,F,_);if(OT(W))return this.bindReference(W);let J=this.createParseContext(W),$=S2(J),Y=this.bindReference($);return tT[J.id]=Y};parse=(T,F={})=>this.finalize(this.parseDefinition(T,F));parseDefinition(T,F={}){if(q(T,"root"))return this.bindReference(T);let _=this.preparseOwnDefinitionFormat(T,F);if(q(_,"root"))return this.bindReference(_);let W=this.createParseContext(_);tT[W.id]=W;let J=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(J.isCyclic)J=h8(J,W.id);return tT[W.id]=J,J}finalize(T){if(O$(T),!T.precompilation&&!this.resolvedConfig.jitless)c9(T.references);return T}}class o2 extends xW{parseOwnDefinitionFormat(T,F){return S2(F)}preparseOwnDefinitionFormat(T,F){return this.preparseNode(B_(T),T,F)}preparseOwnAliasEntry(T,F){return[T,F]}normalizeRootScopeValue(T){return T}}var O$=(T)=>{let F=T.references.filter((_)=>_.hasKind("alias"));for(let _ of F){Object.assign(_.referencesById,_.resolution.referencesById);for(let W of T.references)if(_.id in W.referencesById)Object.assign(W.referencesById,_.referencesById)}return T},z$=(T)=>m(T,(F,_)=>[F,q(_,"root")||q(_,"generic")?_.json:q(_,"module")?z$(_):a(`Unexpected resolution ${o(_)}`)]),m2=(T,F)=>{let _=F.indexOf(".");if(_===-1)return;let W=F.slice(0,_),J=T[W];if(J===void 0)return;if(!q(J,"module"))return z(d9(W));let $=F.slice(_+1),Y=J[$];if(Y===void 0)return m2(J,$);if(q(Y,"root")||q(Y,"generic"))return Y;if(q(Y,"module"))return Y.root??z(R$(F));a(`Unexpected resolution for alias '${F}': ${o(Y)}`)},bW=(T,F)=>new o2(T,F),h_=new o2({});var E$=(T,F)=>{let _={};for(let W in F){let J=F[W];if(q(J,"module")){let $=E$(T,J),Y=m($,(Z,A)=>[`${W}.${Z}`,A]);Object.assign(_,Y)}else if(q(J,"root")||q(J,"generic"))_[W]=J;else a(`Unexpected scope resolution ${o(J)}`)}return _},u2=(T)=>`'${T}' is unresolvable`,d9=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,R$=(T)=>`Reference to submodule '${T}' must specify an alias`;h_.export();var{schema:_T,node:tF,defineSchema:rR,generic:K0}=h_;var c2="^(?:0|[1-9]\\d*)$",l9=new RegExp(c2),eR=VT(l9);var w$=bW({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();w.intrinsic={...w$};var K$=bW({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:c2}},{prereducedAliases:!0}).export();Object.assign(w.intrinsic,K$);var i9=bW({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),v={...w$,...K$,...i9,emptyStructure:tF("structure",{},{prereduced:!0})};w.intrinsic={...v};var D$=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],V$=(T)=>T.toString()!=="Invalid Date",L$=(T)=>T.slice(2,-1),d2=(T)=>`'${T}' could not be parsed by the Date constructor`,S$=(T,F)=>t9(T,F),t9=(T,F)=>{let _=new Date(T);if(V$(_))return _;let W=_8(T);if(W!==void 0){let J=new Date(W);if(V$(J))return J}return F?z(F===!0?d2(T):F):void 0};var l2=(T,F)=>{let _=T.scanner.shiftUntil(n9[N$[F]]);if(T.scanner.lookahead==="")return T.error(s9(_,F));if(T.scanner.shift(),F==="/"){try{new RegExp(_)}catch(W){z(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:_},{prereduced:!0})}else if(qT(F,i2))T.root=T.ctx.$.node("unit",{unit:_});else{let W=S$(_,d2(_));T.root=T.ctx.$.node("unit",{meta:_,unit:W})}},i2={"'":1,'"':1},I$={"/":1,"'":1,'"':1},N$={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},n9={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},r9={'"':"double-quote","'":"single-quote","/":"forward slash"},s9=(T,F)=>`${F}${T} requires a closing ${r9[N$[F]]}`;var C$=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,hW="Optional definitions like 'string?' are only valid as properties in an object or tuple",pW="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var k$={">":!0,">=":!0},B$={"<":!0,"<=":!0};var nF={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},f$=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,gW=(T)=>`Missing ${T}`,q$=(T,F)=>`Left bounds are only valid when paired with right bounds (try ...${F}${T})`,mW=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,j$=(T,F,_,W)=>`An expression may have at most one left bound (parsed ${T}${nF[F]}, ${_}${nF[W]})`;var y$=(T,F,_)=>P$(T,F,_,[]),P$=(T,F,_,W)=>{let J=_.parseUntilFinalizer();if(W.push(J.root),J.finalizer===">"){if(W.length!==F.params.length)return _.error(t2(T,F.names,W.map(($)=>$.expression)));return W}if(J.finalizer===",")return P$(T,F,_,W);return J.error(gW(">"))},t2=(T,F,_)=>`${T}<${F.join(", ")}> requires exactly ${F.length} args (got ${_.length}${_.length===0?"":`: ${_.join(", ")}`})`;var n2=(T)=>{let F=T.scanner.shiftUntilNextTerminator();if(F==="keyof")T.addPrefix("keyof");else T.root=e9(T,F)},a9=(T,F,_)=>{if(_.scanner.shiftUntilNonWhitespace(),_.scanner.shift()!=="<")return _.error(t2(T,F.names,[]));let J=y$(T,F,_);return F(...J)},e9=(T,F)=>T7(T,F)??F7(T,F)??T.error(F===""?T.scanner.lookahead==="#"?C$(T.shiftedByOne().scanner.shiftUntilNextTerminator()):r2(T):u2(F)),T7=(T,F)=>{if(T.ctx.args?.[F]){let W=T.ctx.args[F];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let _=T.ctx.$.maybeResolve(F);if(q(_,"root"))return _;if(_===void 0)return;if(q(_,"generic"))return a9(F,_,T);return z(`Unexpected resolution ${o(_)}`)},F7=(T,F)=>{let _=W8(F);if(_!==void 0)return T.ctx.$.node("unit",{unit:_});let W=$8(F);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},r2=(T)=>{let F=T.previousOperator();return F?s2(F,T.scanner.unscanned):_7(T.scanner.unscanned)},s2=(T,F="")=>`Token '${T}' requires a right operand${F?` before '${F}'`:""}`,_7=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var a2=(T)=>T.scanner.lookahead===""?T.error(r2(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(I$)?l2(T,T.scanner.shift()):T.scanner.lookaheadIsIn(JF)?a2(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in i2?l2(T,`${T.scanner.shift()}${T.scanner.shift()}`):n2(T):n2(T);class r0 extends W2{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in r0.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...JF};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,F)=>T===">"?F[0]==="="?F[1]==="=":F.trimStart()===""||qT(F.trimStart()[0],r0.terminatingChars):T==="="?F[0]!=="=":T===","||T==="?"}var x$=(T,F)=>{let _=W7(T,F);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,_),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,_);return}}return $7(T,_)},b$={"<":1,">":1,"=":1},W7=(T,F)=>T.scanner.lookaheadIs("=")?`${F}${T.scanner.shift()}`:F;var v$=(T,F,_,W)=>{if(_.extends(w.intrinsic.number)){if(typeof F!=="number")return z(e2(T,F,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(_.extends(w.intrinsic.lengthBoundable)){if(typeof F!=="number")return z(e2(T,F,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(_.extends(w.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return z(I8(_.expression))},J7=(T)=>({rule:D$(T.limit)?L$(T.limit):T.limit,exclusive:T.comparator.length===1}),$7=(T,F)=>{let _=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let J=T.unsetRoot(),$=T.scanner.sliceChars(W,T.scanner.location);if(T.root=_,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return T.error(e2(F,$,"right"));let Y=J.unit,Z=F.length===1,A=v$(F,typeof Y==="number"?Y:$,_,"right");for(let O of A)T.constrainRoot(O,F==="=="?{rule:Y}:{rule:Y,exclusive:Z});if(!T.branches.leftBound)return;if(!qT(F,B$))return T.error(mW(F));let X=v$(T.branches.leftBound.comparator,T.branches.leftBound.limit,_,"left");T.constrainRoot(X[0],J7(T.branches.leftBound)),T.branches.leftBound=null},e2=(T,F,_)=>`Comparator ${_==="left"?nF[T]:T} must be ${_==="left"?"preceded":"followed"} by a corresponding literal (was ${F})`;var h$=(T)=>{T.scanner.shiftUntilNonWhitespace();let F=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(F)};var g$=(T)=>{let F=T.scanner.shiftUntilNextTerminator(),_=J8(F,{errorOnFail:p$(F)});if(_===0)T.error(p$(0));T.root=T.root.constrain("divisor",_)},p$=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var T4=(T)=>{let F=T.scanner.shift();return F===""?T.finalize(""):F==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(Y7):F==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(F):F==="&"?T.pushRootToBranch(F):F===")"?T.finalizeGroup():r0.lookaheadIsFinalizing(F,T.scanner.unscanned)?T.finalize(F):qT(F,b$)?x$(T,F):F==="%"?g$(T):F==="#"?h$(T):(F in JF)?T4(T):T.error(oW(F))},oW=(T,F="")=>`'${T}' is not allowed here${F&&` (should be ${F})`}`,Y7="Missing expected ']'";var m$=(T)=>{let F=T.unsetRoot();T.parseOperand();let _=T.unsetRoot();if(!_.hasKind("unit"))return T.error(Z7(_.expression));let W=_.unit instanceof Date?()=>new Date(_.unit):_.unit;return[F,"=",W]},Z7=(T)=>`Default value '${T}' must a literal value`;var F4=(T,F)=>{let _=F.$.maybeResolveRoot(T);if(_)return _;if(T.endsWith("[]")){let $=F.$.maybeResolveRoot(T.slice(0,-2));if($)return $.array()}let W=new rF(new r0(T),F),J=X7(W);if(W.finalizer===">")z(oW(">"));return J},X7=(T)=>{T.parseOperand();let F=p_(T).root;if(!F)return a(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")F=m$(T);else if(T.finalizer==="?")F=[F,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)z(oW(T.scanner.lookahead));return F},p_=(T)=>{while(T.finalizer===void 0)A7(T);return T},A7=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class rF{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,F){this.scanner=T,this.ctx=F}error(T){return z(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(gW(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,F){let _=nF[F];if(!qT(_,k$))return this.error(mW(F));if(this.branches.leftBound)return this.error(j$(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,_));this.branches.leftBound={comparator:_,limit:T}}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 T=this.groups.pop();if(!T)return this.error(f$(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():a(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let F=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(F)??F,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return p_(new rF(this.scanner,this.ctx))}parseOperator(){return T4(this)}parseOperand(){return a2(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(q$(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 G7="An empty string is not a valid generic parameter name",uW=(T,F,_)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&F.length)return F;return z(G7)}return T.shiftUntilNonWhitespace(),H7(T,W,F,_)},o$="extends ",H7=(T,F,_,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(o$))T.jumpForward(o$.length);else{if(T.lookahead===",")T.shift();return _.push(F),uW(T,_,W)}let J=p_(new rF(T,W));return _.push([F,J.root]),uW(T,_,W)};class _4 extends k0{$;constructor(T){super((...F)=>new g_(T)(...F),{bind:T});this.$=T}in(T){return new g_(this.$,T===void 0?void 0:this.$.parse(T))}at(T,F){return new g_(this.$).at(T,F)}case(T,F){return new g_(this.$).case(T,F)}}class g_ extends k0{$;in;key;branches=[];constructor(T,F){super((_)=>this.caseEntries(Object.entries(_).map(([W,J])=>W==="default"?[W,J]:[this.$.parse(W),J])));this.$=T,this.in=F}at(T,F){if(this.key)z(U7);if(this.branches.length)z(O7);return this.key=T,F?this.match(F):this}case(T,F){return this.caseEntry(this.$.parse(T),F)}caseEntry(T,F){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe(F);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([F,_])=>F==="default"?[F,_]:[this.$.node("unit",{unit:F}),_]))}caseEntries(T){for(let F=0;F<T.length;F++){let[_,W]=T[F];if(_==="default"){if(F!==T.length-1)z("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return z(`Value for case "${_}" must be a function (was ${fT(W)})`);this.caseEntry(_,W)}return this}default(T){if(typeof T==="function")this.case(v.unknown,T);let F={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")F.meta={onFail:u$};let _=this.$.node("union",F);if(!this.in)return this.$.finalize(_);let W=this.in.pipe(_);if(T==="never"||T==="assert")W=W.configureReferences({onFail:u$},"self");return this.$.finalize(W)}}var u$=(T)=>T.throw(),O7="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",U7="At most one key matcher may be specified per expression";var cW=(T,F)=>{if(YT(T)){if(T[1]==="=")return[F.$.parseOwnDefinitionFormat(T[0],F),"=",T[2]];if(T[1]==="?")return[F.$.parseOwnDefinitionFormat(T[0],F),"?"]}return dW(T,F)},c$="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",d$="Only required keys may specify default values, e.g. { value: 'number = 0' }";var l$=(T,F)=>{let _,W={},J=wF(T);for(let[Y,Z]of J){let A=z7(Y);if(A.kind==="spread"){if(!b0(W))return z(Q7);let K=F.$.parseOwnDefinitionFormat(Z,F);if(K.equals(v.object))continue;if(!K.hasKind("intersection")||!K.basis?.equals(v.object))return z(E7(K.expression));_=K.structure;continue}if(A.kind==="undeclared"){if(Z!=="reject"&&Z!=="delete"&&Z!=="ignore")z(M7(Z));W.undeclared=Z;continue}let X=cW(Z,F),O=A;if(A.kind==="required"){if(!YT(X))W4(W,"required",{key:A.normalized,value:X},F);else W4(W,"optional",X[1]==="="?{key:A.normalized,value:X[0],default:X[2]}:{key:A.normalized,value:X[0]},F);continue}if(YT(X)){if(X[1]==="?")z(c$);if(X[1]==="=")z(d$)}if(A.kind==="optional"){W4(W,"optional",{key:A.normalized,value:X},F);continue}let M=F.$.parseOwnDefinitionFormat(O.normalized,F),E=vW(M,X,F.$);if(E.index)W.index=r(W.index,E.index);if(E.required)W.required=r(W.required,E.required)}let $=F.$.node("structure",W);return F.$.parseSchema({domain:"object",structure:_?.merge($)??$})},W4=(T,F,_,W)=>{T[F]=r(T[F],W.$.node(F,_))},M7=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${o(T)})`,Q7="Spread operator may only be used as the first key in an object",z7=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===R_?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===R_&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},E7=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var t$=(T,F)=>C7(T)?a$[T[0]](T,F):I7(T)?s$[T[1]](T,F):null,R7=(T,F)=>F.$.parseOwnDefinitionFormat(T[1],F).keyof(),J4=(T,F)=>{if(T[2]===void 0)return z(s2(T[1],""));let _=F.$.parseOwnDefinitionFormat(T[0],F),W=F.$.parseOwnDefinitionFormat(T[2],F);if(T[1]==="|")return F.$.node("union",{branches:[_,W]});let J=T[1]==="&"?W0(_,W,F.$):k_(_,W,F.$);if(J instanceof I)return J.throw();return J},w7=(T,F)=>F.$.parseOwnDefinitionFormat(T[0],F).array(),K7=(T,F)=>{if(typeof T[2]!=="function")return z(n$("=>",T[2]));return F.$.parseOwnDefinitionFormat(T[0],F).pipe(T[2])},n$=(T,F)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof F})`,V7=(T,F)=>{if(typeof T[2]!=="function")return z(n$(":",T[2]));return F.$.parseOwnDefinitionFormat(T[0],F).constrain("predicate",T[2])},D7=(T,F)=>F.$.parseOwnDefinitionFormat(T[0],F).configureReferences(T[2],"shallow"),r$=(T)=>T,L7=r$({"[]":w7,"?":()=>z(hW)}),S7=r$({"|":J4,"&":J4,":":V7,"=>":K7,"|>":J4,"@":D7,"=":()=>z(pW)}),s$={...L7,...S7},I7=(T)=>s$[T[1]]!==void 0,N7=(T)=>T,a$=N7({keyof:R7,instanceof:(T,F)=>{if(typeof T[1]!=="function")return z(i$(z_(T[1])));let _=T.slice(1).map((W)=>typeof W==="function"?F.$.node("proto",{proto:W}):z(i$(z_(W))));return _.length===1?_[0]:F.$.node("union",{branches:_})},"===":(T,F)=>F.$.units(T.slice(1))}),C7=(T)=>a$[T[0]]!==void 0,i$=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var F6=(T,F)=>{let _=[{}],W=0;while(W<T.length){let J=!1;if(T[W]==="..."&&W<T.length-1)J=!0,W++;let $=cW(T[W],F),[Y,Z,A]=!YT($)?[$]:$;if(W++,J){if(!Y.extends(w.intrinsic.Array))return z(f7(Y.expression));_=_.flatMap((X)=>Y.distribute((O)=>B7(SW(X),O)))}else _=_.map((X)=>{if(Z==="?")return _6(X,Y);if(Z==="=")return k7(X,Y,A);return $4(X,Y)})}return F.$.parseSchema(_.map((J)=>b0(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},$4=(T,F)=>{if(T.defaultables||T.optionals)return z(T.variadic?x2:q7);if(T.variadic)T.postfix=r(T.postfix,F);else T.prefix=r(T.prefix,F);return T},_6=(T,F)=>{if(T.variadic)return z(W6);return T.optionals=r(T.optionals,F),T},k7=(T,F,_)=>{if(T.variadic)return z(W6);if(T.optionals)return z(j7);return T.defaultables=r(T.defaultables,[[F,_]]),T},e$=(T,F)=>{if(T.postfix)z(T6);if(T.variadic){if(!T.variadic.equals(F))z(T6)}else T.variadic=F.internal;return T},B7=(T,F)=>{let _=F.select({method:"find",kind:"sequence"});if(!_)return e$(T,w.intrinsic.unknown);if(_.prefix)for(let W of _.prefix)$4(T,W);if(_.optionals)for(let W of _.optionals)_6(T,W);if(_.variadic)e$(T,_.variadic);if(_.postfix)for(let W of _.postfix)$4(T,W);return T},f7=(T)=>`Spread element must be an array (was ${T})`,T6="A tuple may have at most one variadic element",q7="A required element may not follow an optional element",W6="An optional element may not follow a variadic element";var j7="A defaultable element may not follow an optional element without a default";var y7={},dW=(T,F)=>{if(typeof T==="string"){if(F.args&&Object.keys(F.args).some((W)=>T.includes(W)))return F4(T,F);let _=y7[F.$.name]??={};return _[T]??=F4(T,F)}return eT(T,"object")?P7(T,F):z(Y4(fT(T)))},P7=(T,F)=>{let _=Q_(T);switch(_){case void 0:if(q(T,"root"))return T;return l$(T,F);case"Array":return v7(T,F);case"RegExp":return F.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=WF(T)?T():T;if(q(W,"root"))return W;return z(Y4("Function"))}default:return z(Y4(_??o(T)))}},v7=(T,F)=>t$(T,F)??F6(T,F),Y4=(T)=>`Type definitions must be strings or objects (was ${T})`;class Z4 extends k0{constructor(T){let F=Object.assign({errors:F0,hkt:uT,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((..._)=>{if(_.length===1)return T.parse(_[0]);if(_.length===2&&typeof _[0]==="string"&&_[0][0]==="<"&&_[0].at(-1)===">"){let W=_[0].slice(1,-1),J=T.parseGenericParams(W,{});return new XF(J,_[1],T,T,null)}return T.parse(_)},{bind:T,attach:F})}}var sF=w;class lW extends xW{get ambientAttachments(){if(!sF.typeAttachments)return;return this.cacheGetter("ambientAttachments",m(sF.typeAttachments,(T,F)=>[T,this.bindReference(F)]))}preparseOwnAliasEntry(T,F){let _=T.indexOf("<");if(_===-1){if(q(F,"module")||q(F,"generic"))return[T,F];let $=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,Y=this.resolvedConfig.keywords?.[$];if(Y)F=[F,"@",Y];return[T,F]}if(T.at(-1)!==">")z("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,_),J=T.slice(_+1,-1);return[W,()=>{let $=this.parseGenericParams(J,{alias:W});return D8($,F,this)}]}parseGenericParams(T,F){return uW(new r0(T),[],this.createParseContext({...F,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(WF(T)&&!q(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,F){return{...F,def:T,prefix:F.alias??"type"}}parseOwnDefinitionFormat(T,F){if(!(F.alias&&(F.alias in this.aliases))&&!F.args)F.args={this:F.id};let W=dW(T,F);if(YT(W)){if(W[1]==="=")return z(pW);if(W[1]==="?")return z(hW)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(oJ(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((F)=>this.parse(F)));and=(...T)=>T.reduce((F,_)=>F.and(this.parse(_)),this.intrinsic.unknown);merge=(...T)=>T.reduce((F,_)=>F.merge(this.parse(_)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new _4(this);declare=()=>({type:this.type});define(T){return T}type=new Z4(this);static scope=(T,F={})=>new lW(T,F);static module=(T,F={})=>this.scope(T,F).export()}var X4=Object.assign(lW.scope,{define:(T)=>T}),t=lW;class J6 extends uT{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var x7=K0(["base",v.object],["props",v.object])((T)=>T.base.merge(T.props),J6),$6=t.module({Key:v.key,Merge:x7});class Y6 extends uT{}var b7=K0("element")((T)=>{let F=T.element.exclude(v.Array),_=F.array();return F.rawOr(_).pipe(_F).distribute((W)=>W.assertHasKind("morph").declareOut(_),_T)},Y6),Z6=t.module({root:v.Array,readonly:"root",index:v.nonNegativeIntegerString,liftFrom:b7},{name:"Array"});var A4=_T(["string",VF.FileConstructor]),h7=A4.rawOr(A4.array()),X6=_T({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:h7}}),A6=t.module({root:["instanceof",FormData],value:A4,parsed:X6,parse:_T({in:FormData,morphs:(T)=>{let F={};for(let[_,W]of T)if(_ in F){let J=F[_];if(typeof J==="string"||J instanceof VF.FileConstructor)F[_]=[J,W];else J.push(W)}else F[_]=W;return F},declaredOut:X6})},{name:"FormData"});var G6=t.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 p7={Boolean:1,Number:1,String:1},H6=t.module({...m({...n1,...s1},(T,F)=>(T in p7)?[]:[T,["instanceof",F]]),Array:Z6,TypedArray:G6,FormData:A6});var g7=_T({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"}),m7=_T({domain:"number",divisor:1}),iW=t.module({root:v.number,integer:m7,epoch:g7,safe:_T({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 RT=(T,F,_)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:F}};if(_)W.meta={format:_};return tF("intersection",W)},O6=RT(w_,"a well-formed integer string"),S6=t.module({root:O6,parse:_T({in:O6,morphs:(T,F)=>{let _=Number.parseInt(T);return Number.isSafeInteger(_)?_:F.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:v.integer})},{name:"string.integer"}),o7=RT(/^[\dA-Fa-f]+$/,"hex characters only"),u7=t.module({root:RT(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:RT(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),U6=RT(/^[A-Z].*$/,"capitalized"),c7=t.module({root:_T({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:U6}),preformatted:U6},{name:"string.capitalize"}),d7=(T)=>{let F=T.replaceAll(/[ -]+/g,""),_=0,W,J,$=!1;for(let Y=F.length-1;Y>=0;Y--){if(W=F.substring(Y,Y+1),J=Number.parseInt(W,10),$)J*=2,_+=J>=10?J%10+1:J;else _+=J;$=!$}return!!(_%10===0?F:!1)},l7=/^(?: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}))$/,i7=_T({domain:"string",pattern:{meta:"a credit card number",rule:l7.source},predicate:{meta:"a credit card number",predicate:d7}});var t7=/^([+-]?\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 n7=(T)=>!Number.isNaN(new Date(T).valueOf()),M6=_T({domain:"string",predicate:{meta:"a parsable date",predicate:n7}}).assertHasKind("intersection"),Q6=S6.root.internal.narrow((T,F)=>{let _=Number.parseInt(T),W=iW.epoch(_);if(W instanceof F0)return F.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),r7=t.module({root:Q6,parse:_T({in:Q6,morphs:(T)=>new Date(T),declaredOut:v.Date})},{name:"string.date.epoch"}),z6=RT(t7,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),s7=t.module({root:z6,parse:_T({in:z6,morphs:(T)=>new Date(T),declaredOut:v.Date})},{name:"string.date.iso"}),a7=t.module({root:M6,parse:_T({declaredIn:M6,in:"string",morphs:(T,F)=>{let _=new Date(T);if(Number.isNaN(_.valueOf()))return F.error("a parsable date");return _},declaredOut:v.Date}),iso:s7,epoch:r7},{name:"string.date"}),e7=RT(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),E6="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",AF=`(${E6}[.]){3}${E6}`,T3=new RegExp(`^${AF}$`),NT="(?:[0-9a-fA-F]{1,4})",F3=new RegExp(`^((?:${NT}:){7}(?:${NT}|:)|(?:${NT}:){6}(?:${AF}|:${NT}|:)|(?:${NT}:){5}(?::${AF}|(:${NT}){1,2}|:)|(?:${NT}:){4}(?:(:${NT}){0,1}:${AF}|(:${NT}){1,3}|:)|(?:${NT}:){3}(?:(:${NT}){0,2}:${AF}|(:${NT}){1,4}|:)|(?:${NT}:){2}(?:(:${NT}){0,3}:${AF}|(:${NT}){1,5}|:)|(?:${NT}:){1}(?:(:${NT}){0,4}:${AF}|(:${NT}){1,6}|:)|(?::((?::${NT}){0,5}:${AF}|(?::${NT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),_3=t.module({root:["v4 | v6","@","an IP address"],v4:RT(T3,"an IPv4 address","ipv4"),v6:RT(F3,"an IPv6 address","ipv6")},{name:"string.ip"}),aF="a JSON string",I6=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${aF} (${T})`},W3=_T({meta:aF,domain:"string",predicate:{meta:aF,predicate:(T,F)=>{try{return JSON.parse(T),!0}catch(_){return F.reject({code:"predicate",expected:aF,problem:I6(_)})}}}}),J3=(T,F)=>{if(T.length===0)return F.error({code:"predicate",expected:aF,actual:"empty"});try{return JSON.parse(T)}catch(_){return F.error({code:"predicate",expected:aF,problem:I6(_)})}},$3=t.module({root:W3,parse:_T({meta:"safe JSON string parser",in:"string",morphs:J3,declaredOut:v.jsonObject})},{name:"string.json"}),R6=RT(/^[a-z]*$/,"only lowercase letters"),Y3=t.module({root:_T({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:R6}),preformatted:R6},{name:"string.lower"}),N6=["NFC","NFD","NFKC","NFKD"],m_=m(N6,(T,F)=>[F,_T({domain:"string",predicate:(_)=>_.normalize(F)===_,meta:`${F}-normalized unicode`})]),tW=m(N6,(T,F)=>[F,_T({in:"string",morphs:(_)=>_.normalize(F),declaredOut:m_[F]})]),Z3=t.module({root:tW.NFC,preformatted:m_.NFC},{name:"string.normalize.NFC"}),X3=t.module({root:tW.NFD,preformatted:m_.NFD},{name:"string.normalize.NFD"}),A3=t.module({root:tW.NFKC,preformatted:m_.NFKC},{name:"string.normalize.NFKC"}),G3=t.module({root:tW.NFKD,preformatted:m_.NFKD},{name:"string.normalize.NFKD"}),H3=t.module({root:"NFC",NFC:Z3,NFD:X3,NFKC:A3,NFKD:G3},{name:"string.normalize"}),w6=RT(VW,"a well-formed numeric string"),O3=t.module({root:w6,parse:_T({in:w6,morphs:(T)=>Number.parseFloat(T),declaredOut:v.number})},{name:"string.numeric"}),K6="a regex pattern",U3=_T({domain:"string",predicate:{meta:K6,predicate:(T,F)=>{try{return new RegExp(T),!0}catch(_){return F.reject({code:"predicate",expected:K6,problem:String(_)})}}},meta:{format:"regex"}}),M3=/^(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-]+)*))?$/,Q3=RT(M3,"a semantic version (see https://semver.org/)"),V6=RT(/^\S.*\S$|^\S?$/,"trimmed"),z3=t.module({root:_T({in:"string",morphs:(T)=>T.trim(),declaredOut:V6}),preformatted:V6},{name:"string.trim"}),D6=RT(/^[A-Z]*$/,"only uppercase letters"),E3=t.module({root:_T({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:D6}),preformatted:D6},{name:"string.upper"}),R3=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},L6=_T({domain:"string",predicate:{meta:"a URL string",predicate:R3},meta:{format:"uri"}}),w3=t.module({root:L6,parse:_T({declaredIn:L6,in:"string",morphs:(T,F)=>{try{return new URL(T)}catch{return F.error("a URL string")}},declaredOut:_T(URL)})},{name:"string.url"}),K3=t.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:RT(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:RT(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:RT(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:RT(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:RT(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:RT(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:RT(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:RT(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),C6=t.module({root:v.string,alpha:RT(/^[A-Za-z]*$/,"only letters"),alphanumeric:RT(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:o7,base64:u7,capitalize:c7,creditCard:i7,date:a7,digits:RT(/^\d*$/,"only digits 0-9"),email:e7,integer:S6,ip:_3,json:$3,lower:Y3,normalize:H3,numeric:O3,regex:U3,semver:Q3,trim:z3,upper:E3,url:w3,uuid:K3},{name:"string"});var k6=t.module({bigint:v.bigint,boolean:v.boolean,false:v.false,never:v.never,null:v.null,number:v.number,object:v.object,string:v.string,symbol:v.symbol,true:v.true,unknown:v.unknown,undefined:v.undefined}),B6=t.module({root:v.unknown,any:v.unknown},{name:"unknown"}),V3=t.module({root:v.jsonObject,stringify:tF("morph",{in:v.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:v.string})},{name:"object.json"}),f6=t.module({root:v.object,json:V3},{name:"object"});class q6 extends uT{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var D3=K0(["K",v.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),q6);class j6 extends uT{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var L3=K0(["T",v.object],["K",v.key])((T)=>T.T.pick(T.K),j6);class y6 extends uT{description='omit a set of properties from an object like `Omit(User, "age")`'}var S3=K0(["T",v.object],["K",v.key])((T)=>T.T.omit(T.K),y6);class P6 extends uT{description="make all named properties of an object optional like `Partial(User)`"}var I3=K0(["T",v.object])((T)=>T.T.partial(),P6);class v6 extends uT{description="make all named properties of an object required like `Required(User)`"}var N3=K0(["T",v.object])((T)=>T.T.required(),v6);class x6 extends uT{description='exclude branches of a union like `Exclude("boolean", "true")`'}var C3=K0("T","U")((T)=>T.T.exclude(T.U),x6);class b6 extends uT{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var k3=K0("T","U")((T)=>T.T.extract(T.U),b6),h6=t.module({Exclude:C3,Extract:k3,Omit:S3,Partial:I3,Pick:L3,Record:D3,Required:N3});var GF=X4({...k6,...h6,...H6,...$6,string:C6,number:iW,object:f6,unknown:B6},{prereducedAliases:!0,name:"ark"}),jT=GF.export();Object.assign(sF.ambient,jT);sF.typeAttachments={string:jT.string.root,number:jT.number.root,bigint:jT.bigint,boolean:jT.boolean,symbol:jT.symbol,undefined:jT.undefined,null:jT.null,object:jT.object.root,unknown:jT.unknown.root,false:jT.false,true:jT.true,never:jT.never,arrayIndex:jT.Array.index,Key:jT.Key,Record:jT.Record,Array:jT.Array.root,Date:jT.Date};var J0=Object.assign(GF.type,sF.typeAttachments),B3=GF.match,f3=GF.generic,VD=GF.schema,q3=GF.define,j3=GF.declare;class o_ extends Promise{fate;resolve;reject;done=!1;constructor(T){let F,_;super((W,J)=>{F=W,_=J});this.resolve=F,this.reject=_,this.use(T instanceof Promise?T:new Promise(T))}pass(T,F){if(T===this.fate)this.resolve(F),this.done=!0}fail(T,F){if(T===this.fate)this.reject(F),this.done=!0}use(T){if(T instanceof Promise){let F=T;this.fate=F,F.then((_)=>{this.pass(F,_)},(_)=>{this.fail(F,_)})}else this.resolve(T),this.fate=void 0}}var pD=(T,F,_=g6.STORE)=>{return p6(_,{key:`${T.key}:JSON`,get:({get:W})=>F.toJson(W(T)),set:({set:W},J)=>{W(T,F.fromJson(J))}})};function oD(T,F,_){return G4(T,{key:`${F.key}:JSON`,get:(J)=>({get:$})=>{let Y=$(F,J);return _.toJson(Y)},set:(J)=>({set:$},Y)=>{$(F,J,_.fromJson(Y))}},["mutable","json"])}var u_=(T)=>JSON.parse(T),nT=(T)=>JSON.stringify(T),cD=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function i(T){while(T.child!==null)T=T.child;return T}class nW{_buffer;_index=0;constructor(T){let F;if(typeof T==="number")F=T;else F=T.length;this._buffer=Array.from({length:F})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new nW([...this._buffer]);return T._index=this._index,T}}var y3={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function m6(T,F){let _=nT(F),W=`${T.key}(${_})`,J=y3[T.type],$={key:W,type:J};return Object.assign($,{family:{key:T.key,subKey:_}}),Object.assign($,{counterfeit:!0}),$}function c_(T){let F={key:T.key,type:T.type};if("family"in T)F.family=T.family;return F}var H4=(T)=>(F,_,W,J,...$)=>{console[T](`${F} ${_} "${W}" ${J}`,...$)},P3={error:H4("error"),info:H4("info"),warn:H4("warn")};class O4{logLevel;filter;logger;constructor(T,F,_=P3){this.logLevel=T,this.filter=F,this.logger=_}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}class p0{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,F)=>`${T}:${F}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,F){let _=this.relations.get(T),W=this.relations.get(F);if(_)_.add(F);else _=new Set([F]),this.relations.set(T,_);if(W)W.add(T);else W=new Set([T]),this.relations.set(F,W)}deleteRelation(T,F){let _=this.relations.get(T);if(_){if(_.delete(F),_.size===0)this.relations.delete(T);let W=this.relations.get(F);if(W){if(W.delete(T),W.size===0)this.relations.delete(F)}}}replaceRelationsUnsafely(T,F){this.relations.set(T,new Set(F));for(let _ of F){let W=new Set().add(T);this.relations.set(_,W)}}replaceRelationsSafely(T,F){let _=this.relations.get(T),W=this.isAType?.(T)?T:void 0,J=W===void 0?T:void 0;if(_)for(let $ of _){W??=$,J??=$;let Y=this.relations.get($);if(Y){if(Y.size===1)this.relations.delete($);else Y.delete(T);this.contents.delete(this.makeContentKey(W,J))}}this.relations.set(T,new Set(F));for(let $ of F){let Y=this.relations.get($);if(Y)Y.add(T);else Y=new Set().add(T),this.relations.set($,Y)}}getContentInternal(T){return this.contents.get(T)}setContent(T,F){this.contents.set(T,F)}deleteContent(T){this.contents.delete(T)}constructor(T,F){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!F?.externalStore)this.relations=new Map(T.relations?.map(([_,W])=>[_,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=F?.isAType??null,this.isBType=F?.isBType??null,this.isContent=F?.isContent??null,F?.makeContentKey)this.makeContentKey=F.makeContentKey;if(F?.externalStore){let _=F.externalStore;if(this.has=(W,J)=>_.has(W,J),this.addRelation=(W,J)=>{_.addRelation(W,J)},this.deleteRelation=(W,J)=>{_.deleteRelation(W,J)},this.replaceRelationsSafely=(W,J)=>{_.replaceRelationsSafely(W,J)},this.replaceRelationsUnsafely=(W,J)=>{_.replaceRelationsUnsafely(W,J)},this.getRelatedKeys=(W)=>_.getRelatedKeys(W),_.getContent)this.getContentInternal=(W)=>{return _.getContent(W)},this.setContent=(W,J)=>{_.setContent(W,J)},this.deleteContent=(W)=>{_.deleteContent(W)};for(let[W,J]of T.relations??[]){let $=this.isAType?.(W)?W:void 0,Y=$===void 0?W:void 0;for(let Z of J)$??=Z,Y??=Z,this.addRelation($,Y)}for(let[W,J]of T.contents??[])this.setContent(W,J)}if(F?.warn)this.warn=F.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,F])=>[T,[...F]]),contents:[...this.contents.entries()]}}set(...T){let F,_,W;switch(T.length){case 1:{let J=T[0];F=J[this.a],_=J[this.b],W=void 0;break}case 2:{let J=T[0];if(typeof J==="string")[F,_]=T;else F=J[this.a],_=J[this.b],W=T[1];break}default:{F=T[0],_=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey(F);if(J&&J!==_)this.delete(F,J)}case"1:n":{let J=this.getRelatedKey(_);if(J&&J!==F)this.delete(J,_)}break;case"n:n":}if(W){let J=this.makeContentKey(F,_);this.setContent(J,W)}return this.addRelation(F,_),this}delete(T,F){F=typeof F==="string"?F:T[this.b];let _=typeof T==="string"?T:T[this.a];if(_===void 0&&typeof F==="string"){let W=this.getRelatedKeys(F);if(W)for(let J of W)this.delete(J,F)}if(typeof _==="string"&&F===void 0){let W=this.getRelatedKeys(_);if(W)for(let J of W)this.delete(_,J)}if(typeof _==="string"&&typeof F==="string"){this.deleteRelation(_,F);let W=this.makeContentKey(_,F);this.deleteContent(W)}return this}getRelatedKey(T){let F=this.getRelatedKeys(T);if(F){if(F.size>1)this.warn?.(`${F.size} related keys were found for key "${T}": (${[...F].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let _;for(let W of F){_=W;break}return _}}replaceRelations(T,F,_){let W=!Array.isArray(F),J=W?Object.keys(F):F;if(_?.reckless)this.replaceRelationsUnsafely(T,J);else this.replaceRelationsSafely(T,J);if(W)for(let $ of J){let Y=this.makeContentKey(T,$),Z=F[$];this.setContent(Y,Z)}return this}getContent(T,F){let _=this.makeContentKey(T,F);return this.getContentInternal(_)}getRelationEntries(T){let F=T[this.a],_=T[this.b];if(F!==void 0&&_===void 0){let W=this.getRelatedKeys(F);if(W)return[...W].map((J)=>{return[J,this.getContent(F,J)]})}if(F===void 0&&_!==void 0){let W=this.getRelatedKeys(_);if(W)return[...W].map((J)=>{return[J,this.getContent(J,_)]})}return[]}has(T,F){if(F)return this.getRelatedKeys(T)?.has(F)??!1;return this.relations.has(T)}}class ZT{Subscriber;subscribers=new Map;subscribe(T,F){return this.subscribers.set(T,F),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let F=this.subscribers.values();for(let _ of F)_(T)}}class U4 extends ZT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function eF(T){return"epoch"in T.transactionMeta}function U0(T){return"phase"in T.transactionMeta}function o6(T){return T[0].toUpperCase()+T.slice(1)}function rW(T){return T.type.split("_").map(o6).join(" ")}class d_ extends Error{constructor(T,F){super(`${rW(T)} ${nT(T.key)} not found in store "${F.config.name}".`)}}var sW=(T)=>(F)=>T instanceof Function?T(F):T;var HF=(T,F)=>{if(T.valueMap.has(F.key))return T.logger.info("\uD83D\uDCD6",F.type,F.key,"reading cached value"),u6(F,T);switch(F.type){case"selector":case"readonly_selector":return T.logger.info("\uD83E\uDDEE",F.type,F.key,"computing value"),F.get();case"atom":case"mutable_atom":{let _=F.default,W;if(_ instanceof Function)W=_();else W=_;return T.logger.info("\uD83D\uDC81","atom",F.key,"could not find cached value; using default",W),W}}};var c6=(T,F)=>{if(T.operation.open){let _=performance.now();return T.logger.info("\u2757",F.type,F.key,`deferring setState at T-${_} until setState for "${T.operation.token.key}" is done`),_}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:F},T.logger.info("\u2B55",F.type,F.key,`operation start in store "${T.config.name}"${!U0(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},d6=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},l6=(T,F)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",F,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(F)},T_=(T,F)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",F,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(F)};var i6=(T,F,_)=>{switch(F.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",F.type,F.key,"is now (",_.newValue,") subscribers:",F.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":T.logger.info("\uD83D\uDCE2",F.type,F.key,"went (",_.oldValue,"->",_.newValue,") subscribers:",F.subject.subscribers)}F.subject.next(_)};var M4=(T,F)=>{let _=i(T),W=_.selectorAtoms.getRelatedKeys(F.key);if(_.logger.info("\uD83E\uDDF9",F.type,F.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(_.operation.open)_.logger.info("\uD83E\uDDF9",F.type,F.key,`[ ${[..._.operation.done].join(", ")} ] already done`);for(let J of W){if(l6(_,J))continue;t6(J,_),T_(_,J)}}};var n6=(T,F,_)=>{let W=HF(T,F),J=W;if(F.type==="mutable_atom"&&U0(T)){let{parent:Y}=T;J=l_(T,F,Y)}if(J=sW(_)(J),T.logger.info("\uD83D\uDCDD","atom",F.key,"set to",J),J=g0(T,F.key,J,F.subject),s6(T,F.key))a6(T,F.key);T_(T,F.key),M4(T,F);let $={oldValue:W,newValue:J};if(!U0(T)){i6(T,F,$);return}if(T.on.transactionApplying.state===null){let{key:Y}=F;if(r6($.newValue))return;let Z={type:"atom_update",key:Y,...$};if(F.family)Z.family=F.family;T.transactionMeta.update.updates.push(Z),T.logger.info("\uD83D\uDCC1","atom",Y,"stowed (",$.oldValue,"->",$.newValue,")")}else if(F.key.startsWith("*")){let Y=F.key.slice(1),Z=T.atoms.get(Y),A=T.valueMap.get(Y);if(Z.type==="mutable_atom"&&U0(T)){let{parent:O}=T;A=l_(T,Z,O)}if(A.do($.newValue)===null)M4(T,Z)}};var aW=(T,F,_)=>{switch(F.type){case"atom":case"mutable_atom":n6(T,F,_);break;case"selector":F.set(_);break}};var eW=(T,F)=>i(T).atoms.has(F),v3=(T,F)=>i(T).selectors.has(F),x3=(T,F)=>i(T).readonlySelectors.has(F),e6=(T,F)=>eW(T,F)||v3(T,F)||x3(T,F);var T1=(T,F)=>{return i(F).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([W,{source:J}])=>J!==T).map(([W,{source:J}])=>J).filter((W)=>e6(F,W))};var Q4=(T,F,_)=>{let W=[],J=T1(T,_);while(J.length>0){let $=J.shift();if(F.has($))continue;if(F.add($),!eW(_,$))J.push(...T1($,_));else if(!W.includes($))W.push($)}return W},TY=(T,F)=>{let _=T.key,W=T1(_,F),J=new Set;return W.flatMap(($)=>eW(F,$)?$:Q4($,J,F))};var FY=(T,F,_,W)=>{let J=i(W);if(F.type==="atom"||F.type==="mutable_atom")J.selectorAtoms.set({selectorKey:T,atomKey:F.key}),W.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${F.key}"`);else{let $=Q4(F.key,_,W);W.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${$.map((Y)=>`"${Y}"`).join(", ")} ]`);for(let Y of $)J.selectorAtoms=J.selectorAtoms.set({selectorKey:T,atomKey:Y})}_.add(F.key)};var F1=(T,F,_)=>({get:(...W)=>{let J=i(_),$;if(W.length===2){let[A,X]=W;$=M0(_,A,X)}else[$]=W;let Y=$0(_,$),Z=HF(_,Y);return _.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${$.key}" =`,Z,")"),J.selectorGraph.set({upstreamSelectorKey:$.key,downstreamSelectorKey:T},{source:$.key}),FY(T,$,F,_),Z},set:(...W)=>{let J,$;if(W.length===2)J=W[0],$=W[1];else{let A=W[0],X=W[1];$=W[2],J=M0(_,A,X)}let Y=i(_),Z=$0(Y,J);aW(Y,Z,$)},find:(...W)=>M0(_,...W),json:(W)=>F_(_,W)});var z4=(T,F,_)=>{let W=i(T),J=new ZT,$=new Set,{get:Y,find:Z,json:A}=F1(F.key,$,W),X=()=>{let K=F.get({get:Y,find:Z,json:A});return g0(i(T),F.key,K,J),$.clear(),K},O={...F,subject:J,install:(K)=>z4(K,F,_),get:X,type:"readonly_selector",..._&&{family:_}};W.readonlySelectors.set(F.key,O);let M=X();T.logger.info("\u2728",O.type,O.key,"=",M);let E={key:F.key,type:"readonly_selector"};if(_)E.family=_;return E};var i_=(T,F,_)=>{let W=i(T),J=new ZT,$=new Set,Y=F1(F.key,$,W),{find:Z,get:A,json:X}=Y,O={find:Z,get:A,json:X},M=(P=F.get,f=i(T))=>{let y=P(O);return g0(f,F.key,y,J),$.clear(),y},K={...F,subject:J,install:(P)=>i_(P,F,_),get:M,set:(P)=>{let f=i(T),y=M(F.get,f),h=sW(P)(y);if(T.logger.info("\uD83D\uDCDD","selector",F.key,"set (",y,"->",h,")"),g0(f,F.key,h,J),T_(f,F.key),eF(f))J.next({newValue:h,oldValue:y});F.set(Y,h)},type:"selector",..._&&{family:_}};W.selectors.set(F.key,K);let j=M();T.logger.info("\u2728",K.type,K.key,"=",j);let S={key:F.key,type:"selector"};if(_)S.family=_;return S};function p6(T,F){if("set"in F){let J=i_(T,F,void 0);return T.on.selectorCreation.next(J),J}let W=z4(T,F,void 0);return T.on.selectorCreation.next(W),W}function G4(T,F,_){let W={key:F.key,type:"selector_family"},J=T.families.get(F.key);if(J)T.logger.error("\u2757","selector_family",F.key,`Overwriting an existing ${rW(J)} "${J.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new ZT,Z=Object.assign((A)=>{let X=nT(A),O={key:F.key,subKey:X},M=`${F.key}(${X})`,E=i(T),K=i_(E,{key:M,get:F.get(A),set:F.set(A)},O);return $.next({type:"state_creation",token:K}),K},W,{internalRoles:_,subject:$,install:(A)=>G4(A,F),default:(A)=>{return F.get(A)({get:(...O)=>t_(T,...O),find:(...O)=>M0(T,...O),json:(O)=>F_(T,O)})}});return T.families.set(F.key,Z),W}function _Y(T,F,_){let W=T.families.get(F.key);if(W===void 0)throw new d_(F,T);let J=W(_),$=i(T);if(J.family){if(eF($))switch(J.type){case"atom":case"mutable_atom":T.on.atomCreation.next(J);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(J);break}else if(U0($)&&$.on.transactionApplying.state===null)$.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function WY(T,F,_){let W=nT(_),J=`${F.key}(${W})`,$=i(T),Y;switch(F.type){case"atom_family":case"mutable_atom_family":Y=$.atoms.get(J);break;case"selector_family":Y=$.selectors.get(J);break;case"readonly_selector_family":Y=$.readonlySelectors.get(J);break}if(Y)return c_(Y);return Y}function M0(T,F,_){let W=WY(T,F,_);if(W)return W;let J=nT(_),$=T.molecules.get(J);if(!$&&T.config.lifespan==="immortal"){let Y=m6(F,_);return T.logger.error("\u274C",Y.type,Y.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),Y}if(W=_Y(T,F,_),$)i(T).moleculeData.set(J,F.key);return W}function JY(T,F){if(F.family){let _=T.families.get(F.family.key);if(_)return _}}function OF(T,...F){let _,W,J,$;if(F.length===2){if(_=F[0],$=F[1],W=JY(T,_)??null,W)J=_.family?u_(_.family.subKey):null,_=M0(T,W,J)}else W=F[0],J=F[1],$=F[2],_=M0(T,W,J);if("counterfeit"in _&&"family"in _){let A=_.family.subKey,X=T.disposalTraces.buffer.find((O)=>O?.key===A);T.logger.error("\u274C",_.type,_.key,`could not be set because it was not found in the store "${T.config.name}".`,X?`This state was previously disposed:
48
+ ${X.trace}`:"No previous disposal trace was found.");return}let Y=c6(T,_);if(Y){let A=T.on.operationClose.subscribe(`waiting to set "${_.key}" at T-${Y}`,()=>{A(),T.logger.info("\uD83D\uDFE2",_.type,_.key,`resuming deferred setState from T-${Y}`),OF(T,_,$)});return}let Z=$0(T,_);aW(T,Z,$),d6(T)}function t_(T,...F){let _,W,J;if(F.length===1)_=F[0];else W=F[0],J=F[1],_=M0(T,W,J);if("counterfeit"in _&&"family"in _){W=T.families.get(_.family.key);let $=_.family.subKey,Y=T.disposalTraces.buffer.find((Z)=>Z?.key===$);switch(T.logger.error("\u274C",_.type,_.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,Y?`This state was previously disposed:
49
+ ${Y.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(_.family.key);let Z=$0(T,W).default($);return T.defaults.set(W.key,Z),Z}}}return HF(T,$0(T,_))}class $Y{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new p0({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new p0({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new p0({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new p0({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new nW(100);molecules=new Map;moleculeJoins=new p0({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new p0({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new p0({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new ZT,atomDisposal:new ZT,selectorCreation:new ZT,selectorDisposal:new ZT,timelineCreation:new ZT,transactionCreation:new ZT,transactionApplying:new U4(null),operationClose:new ZT,moleculeCreation:new ZT,moleculeDisposal:new ZT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new O4("warn",(T,F,_)=>!ZY(_))];logger={error:(...T)=>{for(let F of this.loggers)F.error(...T)},info:(...T)=>{for(let F of this.loggers)F.info(...T)},warn:(...T)=>{for(let F of this.loggers)F.warn(...T)}};constructor(T,F=null){if(this.config={...F?.config,...T},F!==null){if(this.valueMap=new Map(F?.valueMap),this.operation={...F?.operation},eF(F))this.transactionMeta={epoch:new Map(F?.transactionMeta.epoch),actionContinuities:new p0(F?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of F.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let _=new Set;for(let[,W]of F.atoms){if(_.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let J=F_(F,W),$=YY(W);_.add(J.key),_.add($.key)}}for(let[,W]of F.readonlySelectors)W.install(this);for(let[,W]of F.selectors){if(_.has(W.key))continue;W.install(this)}for(let[,W]of F.transactions)W.install(this);for(let[,W]of F.timelines)W.install(this)}}}var g6={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new $Y({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $0(T,F){let _,W=T;while(W!==null){switch(F.type){case"atom":case"mutable_atom":_=W.atoms.get(F.key);break;case"selector":_=W.selectors.get(F.key);break;case"readonly_selector":_=W.readonlySelectors.get(F.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":_=W.families.get(F.key);break;case"timeline":_=W.timelines.get(F.key);break;case"transaction":_=W.transactions.get(F.key);break}if(_)return _;W=W.child}throw new d_(F,T)}var XY=(T,F)=>{let _=i(T);if(_.operation.open)return _.operation.prev.get(F.key);return _.valueMap.get(F.key)};var E4=(T,F)=>{let _=i(T);return TY(F,T).map((J)=>{let $=_.atoms.get(J);if($===void 0)throw new Error(`Atom "${J}", a dependency of selector "${F.key}", not found in store "${T.config.name}".`);return $.subject.subscribe(`${F.type}:${F.key}`,(Y)=>{T.logger.info("\uD83D\uDCE2",F.type,F.key,"root",J,"went",Y.oldValue,"->",Y.newValue);let Z=XY(_,F),A=HF(_,F);T.logger.info("\u2728",F.type,F.key,"went",Z,"->",A),F.subject.next({newValue:A,oldValue:Z})})})};function n_(T,F,_,W){function J(M){if(T.operation.open){let E=T.on.operationClose.subscribe(`state subscription ${_}`,()=>{E(),W(M)})}else W(M)}let $=$0(T,F);T.logger.info("\uD83D\uDC40",$.type,$.key,`Adding subscription "${_}"`);let Y=$.type==="selector"||$.type==="readonly_selector",Z=null,A=J;if(Y)Z=E4(T,$),A=(M)=>{if(Z)Z.length=0,Z.push(...E4(T,$));J(M)};let X=$.subject.subscribe(_,A);return()=>{if(T.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${_}"`),X(),Z)for(let M of Z)M()}}var AY=(T,F,_,W)=>{let J=$0(T,F);T.logger.info("\uD83D\uDC40","timeline",F.key,`Adding subscription "${_}"`);let $=J.subject.subscribe(_,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",F.key,`Removing subscription "${_}" from timeline`),$()}};class R4{initializeState(T,F){let _=`*${T.key}`;F.atoms.delete(_),F.valueMap.delete(_);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,J=w4(F,{key:_,default:null},W);if(F.parent?.valueMap.has(_)){let $=F.parent.valueMap.get(_);F.valueMap.set(_,$)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,F,_){let W=`tracker:${_.config.name}:${U0(_)?_.transactionMeta.update.key:"main"}:${T.key}`,J=t_(_,T);this.unsubscribeFromInnerValue=J.subscribe(W,($)=>{OF(_,F,$)}),this.unsubscribeFromState=n_(_,T,W,($)=>{if($.newValue!==$.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=$.newValue.subscribe(W,(Y)=>{OF(_,F,Y)})})}updateCore(T,F,_){let W=`tracker:${_.config.name}:${U0(_)?_.transactionMeta.update.key:"main"}:${T.key}`;n_(_,F,W,({newValue:J,oldValue:$})=>{let Y=_.timelineTopics.getRelatedKey(F.key);if(Y){if(_.timelines.get(Y)?.timeTraveling){let X=AY(_,{key:Y,type:"timeline"},W,(O)=>{X(),OF(_,T,(M)=>{if(O==="redo"&&J)M.do(J);else if(O==="undo"&&$)M.undo($);return M})});return}}let Z=_.on.operationClose.subscribe(W,()=>{Z();let A=t_(_,T),X=J===null?-1:A.getUpdateNumber(J),O=X-A.cacheUpdateNumber;if(J&&O===1)OF(_,T,(M)=>(M.do(J),M));else _.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${A.cacheUpdateNumber+1}, but got ${X}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,F){this.mutableState=T;let _=i(F);this.latestUpdateState=this.initializeState(T,_),this.observeCore(T,this.latestUpdateState,_),this.updateCore(T,this.latestUpdateState,_),_.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),_.trackers.delete(T.key)}}}var F_=(T,F)=>{if(F.family){let W=i(T),$={key:`${F.family.key}:JSON`,type:"selector_family"},Y=$0(W,$),Z=JSON.parse(F.family.subKey);return M0(T,Y,Z)}return{type:"selector",key:`${F.key}:JSON`}};var YY=(T)=>{let _={type:"atom",key:`*${T.key}`};if(T.family)_.family={key:`*${T.family.key}`,subKey:T.family.subKey};return _};function r6(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function l_(T,F,_){let W=_.valueMap.get(F.key),J=T.valueMap.get(F.key);if(W!==J)return J;if(W===void 0)return F.default();_.logger.info("\uD83D\uDCC3","atom",F.key,"copying");let $=F.toJson(W),Y=F.fromJson($);return T.valueMap.set(F.key,Y),new R4(F,_),Y}function g0(T,F,_,W){let J=T.valueMap.get(F);if(J instanceof o_)J.use(_);if(_ instanceof Promise){let $=new o_(_);return T.valueMap.set(F,$),$.then((Y)=>{g0(T,F,Y,W),W.next({newValue:Y,oldValue:$})}).catch((Y)=>{T.logger.error("\uD83D\uDCA5","state",F,"rejected:",Y)}),$}return T.valueMap.set(F,_),_}var u6=(T,F)=>{let _=F.valueMap.get(T.key);if(T.type==="mutable_atom"&&U0(F)){let{parent:W}=F;_=l_(F,T,W)}return _},t6=(T,F)=>{let _=F.valueMap.get(T);if(_ instanceof o_){let W=_,J=F.selectors.get(T)??F.readonlySelectors.get(T);if(J)W.use(J.get());return}if(F.operation.open)F.operation.prev.set(T,_);F.valueMap.delete(T),F.logger.info("\uD83D\uDDD1","state",T,"evicted")};var s6=(T,F)=>{return i(T).atomsThatAreDefault.has(F)},GY=(T,F)=>{let _=i(T);_.atomsThatAreDefault=new Set(_.atomsThatAreDefault).add(F)},a6=(T,F)=>{let _=i(T);_.atomsThatAreDefault=new Set(i(T).atomsThatAreDefault),_.atomsThatAreDefault.delete(F)};function w4(T,F,_){T.logger.info("\uD83D\uDD28","atom",F.key,`creating in store "${T.config.name}"`);let W=i(T),J=W.atoms.get(F.key);if(J&&J.type==="atom")return T.logger.error("\u274C","atom",F.key,"Tried to create atom, but it already exists in the store."),c_(J);let $=new ZT,Y={...F,type:"atom",install:(X)=>{return X.logger.info("\uD83D\uDEE0\uFE0F","atom",F.key,`installing in store "${X.config.name}"`),w4(X,F,_)},subject:$};if(_)Y.family=_;let Z=F.default;if(F.default instanceof Function)Z=F.default();W.atoms.set(Y.key,Y),GY(T,F.key),g0(W,F.key,Z,$);let A=c_(Y);if(F.effects){let X=0,O=[];for(let M of F.effects){let E=M({setSelf:(K)=>{OF(T,A,K)},onSet:(K)=>n_(T,A,`effect[${X}]`,K)});if(E)O.push(E);++X}Y.cleanup=()=>{for(let M of O)M()}}return A}class __ extends Set{mode="record";subject=new ZT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,F=0){super(T);if(T instanceof __)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(F)this.cacheLimit=F,this.cache=new Array(F),this.subscribe("auto cache",(_)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=_})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let F=new __(T.members,T.cacheLimit);return F.cache=T.cache,F.cacheIdx=T.cacheIdx,F.cacheUpdateNumber=T.cacheUpdateNumber,F}add(T){let F=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${nT(T)}`);return F}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let F=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${nT(T)}`);return F}parent=null;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new __(this);let F=this.child._subscribe("transaction",(_)=>{this.transactionUpdates?.push(_)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(_){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",_),_}finally{F(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,F){return this.subject.subscribe(T,F)}subscribe(T,F){return this.subject.subscribe(T,(_)=>{F(`${this.cacheUpdateNumber}=${_}`)})}emit(T){this.subject.next(T)}doStep(T){let F=T.indexOf(":"),_=T.substring(0,F),W=T.substring(F+1);switch(_){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let J of W.split(";"))this.doStep(J)}}getUpdateNumber(T){let F=T.indexOf("=");return Number(T.substring(0,F))}do(T){let F=T.indexOf("="),_=Number(T.substring(0,F)),W=_-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let $=T.substring(F+1);return this.doStep($),this.mode="record",this.cacheUpdateNumber=_,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let $=this.cacheIdx+W;if(this.cache[$]===T)return null;this.mode="playback";let Z=!1;while(!Z){this.cacheIdx%=this.cacheLimit;let X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),Z=this.cacheIdx===$-1}let A=T.substring(F+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=_,null}return"OUT_OF_RANGE"}undoStep(T){let F=T.indexOf(":"),_=T.substring(0,F),W=T.substring(F+1);switch(_){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let J=JSON.parse(W);for(let $ of J)this.add($);break}case"tx":{let J=W.split(";");for(let $=J.length-1;$>=0;$--)this.undoStep(J[$])}}}undo(T){let F=T.indexOf("=");if(Number(T.substring(0,F))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring(F+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function ZY(T){return T.startsWith("\uD83D\uDD0D ")}class _1{supported;constructor(T){this.supported=T}refine(T){for(let[F,_]of Object.entries(this.supported))try{if(_(T)===!0&&_!==Boolean)return{type:F,data:T}}catch(W){try{if(T instanceof _)return{type:F,data:T}}catch(J){}}return null}}var b3=new _1({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function h3(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var p3=new _1({object:h3,array:(T)=>Array.isArray(T)}),g3=new _1({...b3.supported,...p3.supported}),HY=(T)=>{if(T===void 0)return"undefined";let F=g3.refine(T);if(F)return F.type;return Object.getPrototypeOf(T).constructor.name};class W1{listeners;globalListeners;handleEvent(T,...F){for(let W of this.globalListeners)W(T,...F);let _=this.listeners.get(T);if(_)for(let W of _)W(...F)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,F){let _=this.listeners.get(T);if(_)_.add(F);else this.listeners.set(T,new Set([F]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,F){let _=this.listeners.get(T);if(_)if(F)_.delete(F);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class OY extends W1{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...F)=>{return this.out.next(F),this});this.id=T,this.in=new ZT,this.out=new ZT,this.in.subscribe("socket",(F)=>{this.handleEvent(...F)})}dispose(){for(let T of this.disposalFunctions)T()}}class K4 extends W1{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(nT(T.map((F)=>F instanceof __?`{ ${F.toJSON().members.join(" | ")} }`:F))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...F)=>{let _=JSON.stringify([T,...F]);return this.process.stdout.write(_+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let F=T.toString();this.unprocessedEvents.push(...F.split("\x03"));let _=this.unprocessedEvents.shift();this.incompleteData+=_??"";try{let W=u_(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let $=u_(J);this.handleEvent(...$)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let F=new OY(`user:${T}`);this.relays.set(T,F),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let _ of this.relayServices){let W=_(F);if(W)F.disposalFunctions.push(W)}this.on(`user:${T}`,(..._)=>{F.in.next(_)}),F.out.subscribe("socket",(_)=>{this.emit(..._)})}),this.on("user-leaves",(T)=>{let F=this.relays.get(T);if(this.off(`relay:${T}`),F)F.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var{file:oA,serve:FO}=globalThis.Bun;import{readFileSync as QY}from"fs";import{createServer as c3}from"http";import{createServer as d3}from"https";import{resolve as D4}from"path";function UY(T,F){if(T instanceof Promise)throw new Error(F)}function m3(T,F){let _={},W=[];for(let J in T){let $=T[J]["~standard"].validate(F[J]);if(UY($,`Validation must be synchronous, but ${J} returned a Promise.`),$.issues){W.push(...$.issues.map((Y)=>({...Y,path:[J,...Y.path??[]]})));continue}_[J]=$.value}if(W.length)return{issues:W};return{value:_}}function V4(T){let F=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[y,h]of Object.entries(F))if(h==="")delete F[y]}if(!!T.skipValidation)return F;let J=typeof T.client==="object"?T.client:{},$=typeof T.server==="object"?T.server:{},Y=typeof T.shared==="object"?T.shared:{},Z=T.isServer??(typeof window==="undefined"||("Deno"in window)),A=Z?{...$,...Y,...J}:{...J,...Y},X=T.createFinalSchema?.(A,Z)["~standard"].validate(F)??m3(A,F);UY(X,"Validation must be synchronous");let O=T.onValidationError??((y)=>{throw console.error("\u274C Invalid environment variables:",y),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(X.issues)return O(X.issues);let E=(y)=>{if(!T.clientPrefix)return!0;return!y.startsWith(T.clientPrefix)&&!(y in Y)},K=(y)=>{return Z||!E(y)},j=(y)=>{return y==="__esModule"||y==="$$typeof"},S=(T.extends??[]).reduce((y,h)=>{return Object.assign(y,h)},{}),P=Object.assign(S,X.value);return new Proxy(P,{get(y,h){if(typeof h!=="string")return;if(j(h))return;if(!K(h))return M(h);return Reflect.get(y,h)}})}var o3="__vite_start_time"in globalThis,u3=typeof window!=="undefined",JN="vitest"in globalThis,s0=J0("string"),MY=J0('"true" | "false" | undefined'),q0=V4({isServer:!o3&&!u3,server:{CI:J0("string | undefined").pipe(Boolean),POSTGRES_USER:s0,POSTGRES_PASSWORD:s0,POSTGRES_DATABASE:s0,POSTGRES_HOST:s0,POSTGRES_PORT:s0.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:s0.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:MY.pipe((T)=>T==="true"),FRONTEND_PORT:s0.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:s0.pipe.try((T)=>JSON.parse(T),J0("string[]")),API_KEY_OPENAI:J0("string | undefined"),API_KEY_RESEND:J0("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:s0,VITE_DEV_FRONTEND_HOST:J0("string | undefined"),VITE_DEV_HTTPS:MY.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var zY=D4(import.meta.dirname,"../dev"),J1=q0.VITE_DEV_HTTPS?{cert:QY(D4(zY,"./cert.pem"),"utf-8"),key:QY(D4(zY,"./key.pem"),"utf-8")}:void 0;function HN(T){if(J1)return d3(J1,T);return c3({},T)}import nH from"path";var H=Symbol.for("drizzle:entityKind"),UN=Symbol.for("drizzle:hasOwnEntityKind");function R(T,F){if(!T||typeof T!=="object")return!1;if(T instanceof F)return!0;if(!Object.prototype.hasOwnProperty.call(F,H))throw new Error(`Class "${F.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let _=Object.getPrototypeOf(T).constructor;if(_)while(_){if(H in _&&_[H]===F[H])return!0;_=Object.getPrototypeOf(_)}return!1}class XT{constructor(T,F){this.table=T,this.config=F,this.name=F.name,this.keyAsName=F.keyAsName,this.notNull=F.notNull,this.default=F.default,this.defaultFn=F.defaultFn,this.onUpdateFn=F.onUpdateFn,this.hasDefault=F.hasDefault,this.primary=F.primaryKey,this.isUnique=F.isUnique,this.uniqueName=F.uniqueName,this.uniqueType=F.uniqueType,this.dataType=F.dataType,this.columnType=F.columnType,this.generated=F.generated,this.generatedIdentity=F.generatedIdentity}static[H]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class L4{static[H]="ColumnBuilder";config;constructor(T,F,_){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:F,columnType:_,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var j0=Symbol.for("drizzle:Name");class S4{static[H]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,F){if(this.reference=()=>{let{name:_,columns:W,foreignColumns:J}=T();return{name:_,columns:W,foreignTable:J[0].table,foreignColumns:J}},F)this._onUpdate=F.onUpdate,this._onDelete=F.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new EY(T,this)}}class EY{constructor(T,F){this.table=T,this.reference=F.reference,this.onUpdate=F._onUpdate,this.onDelete=F._onDelete}static[H]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:F,foreignColumns:_}=this.reference(),W=F.map((Y)=>Y.name),J=_.map((Y)=>Y.name),$=[this.table[j0],...W,_[0].table[j0],...J];return T??`${$.join("_")}_fk`}}function $1(T,...F){return T(...F)}function RY(T,F){return`${T[j0]}_${F.join("_")}_unique`}function wY(T,F,_){for(let W=F;W<T.length;W++){let J=T[W];if(J==="\\"){W++;continue}if(J==='"')return[T.slice(F,W).replace(/\\/g,""),W+1];if(_)continue;if(J===","||J==="}")return[T.slice(F,W).replace(/\\/g,""),W]}return[T.slice(F).replace(/\\/g,""),T.length]}function KY(T,F=0){let _=[],W=F,J=!1;while(W<T.length){let $=T[W];if($===","){if(J||W===F)_.push("");J=!0,W++;continue}if(J=!1,$==="\\"){W+=2;continue}if($==='"'){let[A,X]=wY(T,W+1,!0);_.push(A),W=X;continue}if($==="}")return[_,W+1];if($==="{"){let[A,X]=KY(T,W+1);_.push(A),W=X;continue}let[Y,Z]=wY(T,W,!1);_.push(Y),W=Z}return[_,W]}function VY(T){let[F]=KY(T,1);return F}function I4(T){return`{${T.map((F)=>{if(Array.isArray(F))return I4(F);if(typeof F==="string")return`"${F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${F}`}).join(",")}}`}class B extends L4{foreignKeyConfigs=[];static[H]="PgColumnBuilder";array(T){return new LY(this.config.name,this,T)}references(T,F={}){return this.foreignKeyConfigs.push({ref:T,actions:F}),this}unique(T,F){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=F?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,F){return this.foreignKeyConfigs.map(({ref:_,actions:W})=>{return $1((J,$)=>{let Y=new S4(()=>{let Z=J();return{columns:[T],foreignColumns:[Z]}});if($.onUpdate)Y.onUpdate($.onUpdate);if($.onDelete)Y.onDelete($.onDelete);return Y.build(F)},_,W)})}buildExtraConfigColumn(T){return new DY(T,this.config)}}class L extends XT{constructor(T,F){if(!F.uniqueName)F.uniqueName=RY(T,[F.name]);super(T,F);this.table=T}static[H]="PgColumn"}class DY extends L{static[H]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class r_{static[H]="IndexedColumn";constructor(T,F,_,W){this.name=T,this.keyAsName=F,this.type=_,this.indexConfig=W}name;keyAsName;type;indexConfig}class LY extends B{static[H]="PgArrayBuilder";constructor(T,F,_){super(T,"array","PgArray");this.config.baseBuilder=F,this.config.size=_}build(T){let F=this.config.baseBuilder.build(T);return new N4(T,this.config,F)}}class N4 extends L{constructor(T,F,_,W){super(T,F);this.baseColumn=_,this.range=W,this.size=F.size}size;static[H]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=VY(T);return T.map((F)=>this.baseColumn.mapFromDriverValue(F))}mapToDriverValue(T,F=!1){let _=T.map((W)=>W===null?null:R(this.baseColumn,N4)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if(F)return _;return I4(_)}}class SY extends B{static[H]="PgEnumObjectColumnBuilder";constructor(T,F){super(T,"string","PgEnumObjectColumn");this.config.enum=F}build(T){return new IY(T,this.config)}}class IY extends L{static[H]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,F){super(T,F);this.enum=F.enum}getSQLType(){return this.enum.enumName}}var Y1=Symbol.for("drizzle:isPgEnum");function NY(T){return!!T&&typeof T==="function"&&Y1 in T&&T[Y1]===!0}class CY extends B{static[H]="PgEnumColumnBuilder";constructor(T,F){super(T,"string","PgEnumColumn");this.config.enum=F}build(T){return new kY(T,this.config)}}class kY extends L{static[H]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,F){super(T,F);this.enum=F.enum}getSQLType(){return this.enum.enumName}}function s_(T,F){return Array.isArray(F)?l3(T,[...F],void 0):i3(T,F,void 0)}function l3(T,F,_){let W=Object.assign((J)=>new CY(J??"",W),{enumName:T,enumValues:F,schema:_,[Y1]:!0});return W}function i3(T,F,_){let W=Object.assign((J)=>new SY(J??"",W),{enumName:T,enumValues:Object.values(F),schema:_,[Y1]:!0});return W}class yT{static[H]="Subquery";constructor(T,F,_,W=!1){this._={brand:"Subquery",sql:T,selectedFields:F,alias:_,isWith:W}}}class a_ extends yT{static[H]="WithSubquery"}var BY="0.43.1";var C4,k4,AT={startActiveSpan(T,F){if(!C4)return F();if(!k4)k4=C4.trace.getTracer("drizzle-orm",BY);return $1((_,W)=>W.startActiveSpan(T,(J)=>{try{return F(J)}catch($){throw J.setStatus({code:_.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{J.end()}}),C4,k4)}};var MT=Symbol.for("drizzle:ViewBaseConfig");var Z1=Symbol.for("drizzle:Schema"),X1=Symbol.for("drizzle:Columns"),fY=Symbol.for("drizzle:ExtraConfigColumns"),B4=Symbol.for("drizzle:OriginalName"),f4=Symbol.for("drizzle:BaseName"),e_=Symbol.for("drizzle:IsAlias"),qY=Symbol.for("drizzle:ExtraConfigBuilder"),t3=Symbol.for("drizzle:IsDrizzleTable");class C{static[H]="Table";static Symbol={Name:j0,Schema:Z1,OriginalName:B4,Columns:X1,ExtraConfigColumns:fY,BaseName:f4,IsAlias:e_,ExtraConfigBuilder:qY};[j0];[B4];[Z1];[X1];[fY];[f4];[e_]=!1;[t3]=!0;[qY]=void 0;constructor(T,F,_){this[j0]=this[B4]=T,this[Z1]=F,this[f4]=_}}function vT(T){return T[j0]}function SF(T){return`${T[Z1]??"public"}.${T[j0]}`}function q4(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function n3(T){let F={sql:"",params:[]};for(let _ of T)if(F.sql+=_.sql,F.params.push(..._.params),_.typings?.length){if(!F.typings)F.typings=[];F.typings.push(..._.typings)}return F}class PT{static[H]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new k([this])}}class k{constructor(T){this.queryChunks=T}static[H]="SQL";decoder=yY;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return AT.startActiveSpan("drizzle.buildSQL",(F)=>{let _=this.buildQueryFromSourceParams(this.queryChunks,T);return F?.setAttributes({"drizzle.query.text":_.sql,"drizzle.query.params":JSON.stringify(_.params)}),_})}buildQueryFromSourceParams(T,F){let _=Object.assign({},F,{inlineParams:F.inlineParams||this.shouldInlineParams,paramStartIndex:F.paramStartIndex||{value:0}}),{casing:W,escapeName:J,escapeParam:$,prepareTyping:Y,inlineParams:Z,paramStartIndex:A}=_;return n3(T.map((X)=>{if(R(X,PT))return{sql:X.value.join(""),params:[]};if(R(X,A1))return{sql:J(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){let O=[new PT("(")];for(let[M,E]of X.entries())if(O.push(E),M<X.length-1)O.push(new PT(", "));return O.push(new PT(")")),this.buildQueryFromSourceParams(O,_)}if(R(X,k))return this.buildQueryFromSourceParams(X.queryChunks,{..._,inlineParams:Z||X.shouldInlineParams});if(R(X,C)){let O=X[C.Symbol.Schema],M=X[C.Symbol.Name];return{sql:O===void 0||X[e_]?J(M):J(O)+"."+J(M),params:[]}}if(R(X,XT)){let O=W.getColumnCasing(X);if(F.invokeSource==="indexes")return{sql:J(O),params:[]};let M=X.table[C.Symbol.Schema];return{sql:X.table[e_]||M===void 0?J(X.table[C.Symbol.Name])+"."+J(O):J(M)+"."+J(X.table[C.Symbol.Name])+"."+J(O),params:[]}}if(R(X,Y0)){let O=X[MT].schema,M=X[MT].name;return{sql:O===void 0||X[MT].isAlias?J(M):J(O)+"."+J(M),params:[]}}if(R(X,Q0)){if(R(X.value,UF))return{sql:$(A.value++,X),params:[X],typings:["none"]};let O=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(R(O,k))return this.buildQueryFromSourceParams([O],_);if(Z)return{sql:this.mapInlineParam(O,_),params:[]};let M=["none"];if(Y)M=[Y(X.encoder)];return{sql:$(A.value++,O),params:[O],typings:M}}if(R(X,UF))return{sql:$(A.value++,X),params:[X],typings:["none"]};if(R(X,k.Aliased)&&X.fieldAlias!==void 0)return{sql:J(X.fieldAlias),params:[]};if(R(X,yT)){if(X._.isWith)return{sql:J(X._.alias),params:[]};return this.buildQueryFromSourceParams([new PT("("),X._.sql,new PT(") "),new A1(X._.alias)],_)}if(NY(X)){if(X.schema)return{sql:J(X.schema)+"."+J(X.enumName),params:[]};return{sql:J(X.enumName),params:[]}}if(q4(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],_);return this.buildQueryFromSourceParams([new PT("("),X.getSQL(),new PT(")")],_)}if(Z)return{sql:this.mapInlineParam(X,_),params:[]};return{sql:$(A.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:F}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return F(T);if(typeof T==="object"){let _=T.toString();if(_==="[object Object]")return F(JSON.stringify(T));return F(_)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new k.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class A1{constructor(T){this.value=T}static[H]="Name";brand;getSQL(){return new k([this])}}function jY(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var yY={mapFromDriverValue:(T)=>T},PY={mapToDriverValue:(T)=>T},FC={...yY,...PY};class Q0{constructor(T,F=PY){this.value=T,this.encoder=F}static[H]="Param";brand;getSQL(){return new k([this])}}function U(T,...F){let _=[];if(F.length>0||T.length>0&&T[0]!=="")_.push(new PT(T[0]));for(let[W,J]of F.entries())_.push(J,new PT(T[W+1]));return new k(_)}((T)=>{function F(){return new k([])}T.empty=F;function _(A){return new k(A)}T.fromList=_;function W(A){return new k([new PT(A)])}T.raw=W;function J(A,X){let O=[];for(let[M,E]of A.entries()){if(M>0&&X!==void 0)O.push(X);O.push(E)}return new k(O)}T.join=J;function $(A){return new A1(A)}T.identifier=$;function Y(A){return new UF(A)}T.placeholder=Y;function Z(A,X){return new Q0(A,X)}T.param=Z})(U||(U={}));((T)=>{class F{constructor(_,W){this.sql=_,this.fieldAlias=W}static[H]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new F(this.sql,this.fieldAlias)}}T.Aliased=F})(k||(k={}));class UF{constructor(T){this.name=T}static[H]="Placeholder";getSQL(){return new k([this])}}function j4(T,F){return T.map((_)=>{if(R(_,UF)){if(!(_.name in F))throw new Error(`No value for placeholder "${_.name}" was provided`);return F[_.name]}if(R(_,Q0)&&R(_.value,UF)){if(!(_.value.name in F))throw new Error(`No value for placeholder "${_.value.name}" was provided`);return _.encoder.mapToDriverValue(F[_.value.name])}return _})}var r3=Symbol.for("drizzle:IsDrizzleView");class Y0{static[H]="View";[MT];[r3]=!0;constructor({name:T,schema:F,selectedFields:_,query:W}){this[MT]={name:T,originalName:T,schema:F,selectedFields:_,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new k([this])}}XT.prototype.getSQL=function(){return new k([this])};C.prototype.getSQL=function(){return new k([this])};yT.prototype.getSQL=function(){return new k([this])};class W_{constructor(T){this.table=T}static[H]="ColumnAliasProxyHandler";get(T,F){if(F==="table")return this.table;return T[F]}}class TW{constructor(T,F){this.alias=T,this.replaceOriginalName=F}static[H]="TableAliasProxyHandler";get(T,F){if(F===C.Symbol.IsAlias)return!0;if(F===C.Symbol.Name)return this.alias;if(this.replaceOriginalName&&F===C.Symbol.OriginalName)return this.alias;if(F===MT)return{...T[MT],name:this.alias,isAlias:!0};if(F===C.Symbol.Columns){let W=T[C.Symbol.Columns];if(!W)return W;let J={};return Object.keys(W).map(($)=>{J[$]=new Proxy(W[$],new W_(new Proxy(T,this)))}),J}let _=T[F];if(R(_,XT))return new Proxy(_,new W_(new Proxy(T,this)));return _}}function G1(T,F){return new Proxy(T,new TW(F,!1))}function m0(T,F){return new Proxy(T,new W_(new Proxy(T.table,new TW(F,!1))))}function y4(T,F){return new k.Aliased(FW(T.sql,F),T.fieldAlias)}function FW(T,F){return U.join(T.queryChunks.map((_)=>{if(R(_,XT))return m0(_,F);if(R(_,k))return FW(_,F);if(R(_,k.Aliased))return y4(_,F);return _}))}class H1 extends Error{static[H]="DrizzleError";constructor({message:T,cause:F}){super(T);this.name="DrizzleError",this.cause=F}}class P4 extends H1{static[H]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class vY{static[H]="ConsoleLogWriter";write(T){console.log(T)}}class v4{static[H]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new vY}logQuery(T,F){let _=F.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),W=_.length?` -- params: [${_.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class x4{static[H]="NoopLogger";logQuery(){}}class rT{static[H]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((F)=>{return T?.(),F},(F)=>{throw T?.(),F})}then(T,F){return this.execute().then(T,F)}}function xY(T,F,_){let W={},J=T.reduce(($,{path:Y,field:Z},A)=>{let X;if(R(Z,XT))X=Z;else if(R(Z,k))X=Z.decoder;else X=Z.sql.decoder;let O=$;for(let[M,E]of Y.entries())if(M<Y.length-1){if(!(E in O))O[E]={};O=O[E]}else{let K=F[A],j=O[E]=K===null?null:X.mapFromDriverValue(K);if(_&&R(Z,XT)&&Y.length===2){let S=Y[0];if(!(S in W))W[S]=j===null?vT(Z.table):!1;else if(typeof W[S]==="string"&&W[S]!==vT(Z.table))W[S]=!1}}return $},{});if(_&&Object.keys(W).length>0){for(let[$,Y]of Object.entries(W))if(typeof Y==="string"&&!_[Y])J[$]=null}return J}function V0(T,F){return Object.entries(T).reduce((_,[W,J])=>{if(typeof W!=="string")return _;let $=F?[...F,W]:[W];if(R(J,XT)||R(J,k)||R(J,k.Aliased))_.push({path:$,field:J});else if(R(J,C))_.push(...V0(J[C.Symbol.Columns],$));else _.push(...V0(J,$));return _},[])}function _W(T,F){let _=Object.keys(T),W=Object.keys(F);if(_.length!==W.length)return!1;for(let[J,$]of _.entries())if($!==W[J])return!1;return!0}function O1(T,F){let _=Object.entries(F).filter(([,W])=>W!==void 0).map(([W,J])=>{if(R(J,k)||R(J,XT))return[W,J];else return[W,new Q0(J,T[C.Symbol.Columns][W])]});if(_.length===0)throw new Error("No values to set");return Object.fromEntries(_)}function bY(T,F){for(let _ of F)for(let W of Object.getOwnPropertyNames(_.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(_.prototype,W)||Object.create(null))}}function hY(T){return T[C.Symbol.Columns]}function a0(T){return R(T,yT)?T._.alias:R(T,Y0)?T[MT].name:R(T,k)?void 0:T[C.Symbol.IsAlias]?T[C.Symbol.Name]:T[C.Symbol.BaseName]}function s(T,F){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:F}}function pY(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let F=typeof T.logger;if(F!=="boolean"&&(F!=="object"||typeof T.logger.logQuery!=="function")&&F!=="undefined")return!1;return!0}if("schema"in T){let F=typeof T.schema;if(F!=="object"&&F!=="undefined")return!1;return!0}if("casing"in T){let F=typeof T.casing;if(F!=="string"&&F!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let F=typeof T.connection;if(F!=="string"&&F!=="object"&&F!=="undefined")return!1;return!0}if("client"in T){let F=typeof T.client;if(F!=="object"&&F!=="function"&&F!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class MF extends B{static[H]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:F,..._}=T;this.config.generatedIdentity={type:"always",sequenceName:F,sequenceOptions:_}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:F,..._}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:F,sequenceOptions:_}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class gY extends MF{static[H]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new mY(T,this.config)}}class mY extends L{static[H]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class oY extends MF{static[H]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new uY(T,this.config)}}class uY extends L{static[H]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function cY(T,F){let{name:_,config:W}=s(T,F);if(W.mode==="number")return new gY(_);return new oY(_)}class dY extends B{static[H]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new lY(T,this.config)}}class lY extends L{static[H]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class iY extends B{static[H]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new tY(T,this.config)}}class tY extends L{static[H]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function nY(T,F){let{name:_,config:W}=s(T,F);if(W.mode==="number")return new dY(_);return new iY(_)}class rY extends B{static[H]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new sY(T,this.config)}}class sY extends L{static[H]="PgBoolean";getSQLType(){return"boolean"}}function WW(T){return new rY(T??"")}class aY extends B{static[H]="PgCharBuilder";constructor(T,F){super(T,"string","PgChar");this.config.length=F.length,this.config.enumValues=F.enum}build(T){return new eY(T,this.config)}}class eY extends L{static[H]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function TZ(T,F={}){let{name:_,config:W}=s(T,F);return new aY(_,W)}class FZ extends B{static[H]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new _Z(T,this.config)}}class _Z extends L{static[H]="PgCidr";getSQLType(){return"cidr"}}function WZ(T){return new FZ(T??"")}class JZ extends B{static[H]="PgCustomColumnBuilder";constructor(T,F,_){super(T,"custom","PgCustomColumn");this.config.fieldConfig=F,this.config.customTypeParams=_}build(T){return new $Z(T,this.config)}}class $Z extends L{static[H]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,F){super(T,F);this.sqlName=F.customTypeParams.dataType(F.fieldConfig),this.mapTo=F.customTypeParams.toDriver,this.mapFrom=F.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function YZ(T){return(F,_)=>{let{name:W,config:J}=s(F,_);return new JZ(W,J,T)}}class e0 extends B{static[H]="PgDateColumnBaseBuilder";defaultNow(){return this.default(U`now()`)}}class ZZ extends e0{static[H]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new U1(T,this.config)}}class U1 extends L{static[H]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class XZ extends e0{static[H]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new M1(T,this.config)}}class M1 extends L{static[H]="PgDateString";getSQLType(){return"date"}}function AZ(T,F){let{name:_,config:W}=s(T,F);if(W?.mode==="date")return new ZZ(_);return new XZ(_)}class GZ extends B{static[H]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new HZ(T,this.config)}}class HZ extends L{static[H]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function OZ(T){return new GZ(T??"")}class UZ extends B{static[H]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new MZ(T,this.config)}}class MZ extends L{static[H]="PgInet";getSQLType(){return"inet"}}function QZ(T){return new UZ(T??"")}class zZ extends MF{static[H]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new EZ(T,this.config)}}class EZ extends L{static[H]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function JW(T){return new zZ(T??"")}class RZ extends B{static[H]="PgIntervalBuilder";constructor(T,F){super(T,"string","PgInterval");this.config.intervalConfig=F}build(T){return new wZ(T,this.config)}}class wZ extends L{static[H]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",F=this.precision?`(${this.precision})`:"";return`interval${T}${F}`}}function KZ(T,F={}){let{name:_,config:W}=s(T,F);return new RZ(_,W)}class VZ extends B{static[H]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new Q1(T,this.config)}}class Q1 extends L{static[H]="PgJson";constructor(T,F){super(T,F)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function DZ(T){return new VZ(T??"")}class LZ extends B{static[H]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new z1(T,this.config)}}class z1 extends L{static[H]="PgJsonb";constructor(T,F){super(T,F)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function SZ(T){return new LZ(T??"")}class IZ extends B{static[H]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new NZ(T,this.config)}}class NZ extends L{static[H]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[F,_,W]=T.slice(1,-1).split(",");return[Number.parseFloat(F),Number.parseFloat(_),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class CZ extends B{static[H]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new kZ(T,this.config)}}class kZ extends L{static[H]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[F,_,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat(F),b:Number.parseFloat(_),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function BZ(T,F){let{name:_,config:W}=s(T,F);if(!W?.mode||W.mode==="tuple")return new IZ(_);return new CZ(_)}class fZ extends B{static[H]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new qZ(T,this.config)}}class qZ extends L{static[H]="PgMacaddr";getSQLType(){return"macaddr"}}function jZ(T){return new fZ(T??"")}class yZ extends B{static[H]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new PZ(T,this.config)}}class PZ extends L{static[H]="PgMacaddr8";getSQLType(){return"macaddr8"}}function vZ(T){return new yZ(T??"")}class xZ extends B{static[H]="PgNumericBuilder";constructor(T,F,_){super(T,"string","PgNumeric");this.config.precision=F,this.config.scale=_}build(T){return new E1(T,this.config)}}class E1 extends L{static[H]="PgNumeric";precision;scale;constructor(T,F){super(T,F);this.precision=F.precision,this.scale=F.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}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 bZ extends B{static[H]="PgNumericNumberBuilder";constructor(T,F,_){super(T,"number","PgNumericNumber");this.config.precision=F,this.config.scale=_}build(T){return new hZ(T,this.config)}}class hZ extends L{static[H]="PgNumericNumber";precision;scale;constructor(T,F){super(T,F);this.precision=F.precision,this.scale=F.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}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 pZ extends B{static[H]="PgNumericBigIntBuilder";constructor(T,F,_){super(T,"bigint","PgNumericBigInt");this.config.precision=F,this.config.scale=_}build(T){return new gZ(T,this.config)}}class gZ extends L{static[H]="PgNumericBigInt";precision;scale;constructor(T,F){super(T,F);this.precision=F.precision,this.scale=F.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 mZ(T,F){let{name:_,config:W}=s(T,F),J=W?.mode;return J==="number"?new bZ(_,W?.precision,W?.scale):J==="bigint"?new pZ(_,W?.precision,W?.scale):new xZ(_,W?.precision,W?.scale)}class oZ extends B{static[H]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new uZ(T,this.config)}}class uZ extends L{static[H]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[F,_]=T.slice(1,-1).split(",");return[Number.parseFloat(F),Number.parseFloat(_)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class cZ extends B{static[H]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new dZ(T,this.config)}}class dZ extends L{static[H]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[F,_]=T.slice(1,-1).split(",");return{x:Number.parseFloat(F),y:Number.parseFloat(_)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function lZ(T,F){let{name:_,config:W}=s(T,F);if(!W?.mode||W.mode==="tuple")return new oZ(_);return new cZ(_)}function s3(T){let F=[];for(let _=0;_<T.length;_+=2)F.push(Number.parseInt(T.slice(_,_+2),16));return new Uint8Array(F)}function iZ(T,F){let _=new ArrayBuffer(8),W=new DataView(_);for(let J=0;J<8;J++)W.setUint8(J,T[F+J]);return W.getFloat64(0,!0)}function b4(T){let F=s3(T),_=0,W=F[_];_+=1;let J=new DataView(F.buffer),$=J.getUint32(_,W===1);_+=4;let Y;if($&536870912)Y=J.getUint32(_,W===1),_+=4;if(($&65535)===1){let Z=iZ(F,_);_+=8;let A=iZ(F,_);return _+=8,[Z,A]}throw new Error("Unsupported geometry type")}class tZ extends B{static[H]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new nZ(T,this.config)}}class nZ extends L{static[H]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return b4(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class rZ extends B{static[H]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new sZ(T,this.config)}}class sZ extends L{static[H]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let F=b4(T);return{x:F[0],y:F[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function aZ(T,F){let{name:_,config:W}=s(T,F);if(!W?.mode||W.mode==="tuple")return new tZ(_);return new rZ(_)}class eZ extends B{static[H]="PgRealBuilder";constructor(T,F){super(T,"number","PgReal");this.config.length=F}build(T){return new TX(T,this.config)}}class TX extends L{static[H]="PgReal";constructor(T,F){super(T,F)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function FX(T){return new eZ(T??"")}class _X extends B{static[H]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new WX(T,this.config)}}class WX extends L{static[H]="PgSerial";getSQLType(){return"serial"}}function JX(T){return new _X(T??"")}class $X extends MF{static[H]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new YX(T,this.config)}}class YX extends L{static[H]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function ZX(T){return new $X(T??"")}class XX extends B{static[H]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new AX(T,this.config)}}class AX extends L{static[H]="PgSmallSerial";getSQLType(){return"smallserial"}}function GX(T){return new XX(T??"")}class HX extends B{static[H]="PgTextBuilder";constructor(T,F){super(T,"string","PgText");this.config.enumValues=F.enum}build(T){return new OX(T,this.config)}}class OX extends L{static[H]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function UX(T,F={}){let{name:_,config:W}=s(T,F);return new HX(_,W)}class MX extends e0{constructor(T,F,_){super(T,"string","PgTime");this.withTimezone=F,this.precision=_,this.config.withTimezone=F,this.config.precision=_}static[H]="PgTimeBuilder";build(T){return new R1(T,this.config)}}class R1 extends L{static[H]="PgTime";withTimezone;precision;constructor(T,F){super(T,F);this.withTimezone=F.withTimezone,this.precision=F.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function QX(T,F={}){let{name:_,config:W}=s(T,F);return new MX(_,W.withTimezone??!1,W.precision)}class zX extends e0{static[H]="PgTimestampBuilder";constructor(T,F,_){super(T,"date","PgTimestamp");this.config.withTimezone=F,this.config.precision=_}build(T){return new w1(T,this.config)}}class w1 extends L{static[H]="PgTimestamp";withTimezone;precision;constructor(T,F){super(T,F);this.withTimezone=F.withTimezone,this.precision=F.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class EX extends e0{static[H]="PgTimestampStringBuilder";constructor(T,F,_){super(T,"string","PgTimestampString");this.config.withTimezone=F,this.config.precision=_}build(T){return new K1(T,this.config)}}class K1 extends L{static[H]="PgTimestampString";withTimezone;precision;constructor(T,F){super(T,F);this.withTimezone=F.withTimezone,this.precision=F.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function y0(T,F={}){let{name:_,config:W}=s(T,F);if(W?.mode==="string")return new EX(_,W.withTimezone??!1,W.precision);return new zX(_,W?.withTimezone??!1,W?.precision)}class RX extends B{static[H]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(U`gen_random_uuid()`)}build(T){return new V1(T,this.config)}}class V1 extends L{static[H]="PgUUID";getSQLType(){return"uuid"}}function D0(T){return new RX(T??"")}class wX extends B{static[H]="PgVarcharBuilder";constructor(T,F){super(T,"string","PgVarchar");this.config.length=F.length,this.config.enumValues=F.enum}build(T){return new KX(T,this.config)}}class KX extends L{static[H]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function sT(T,F={}){let{name:_,config:W}=s(T,F);return new wX(_,W)}class VX extends B{static[H]="PgBinaryVectorBuilder";constructor(T,F){super(T,"string","PgBinaryVector");this.config.dimensions=F.dimensions}build(T){return new DX(T,this.config)}}class DX extends L{static[H]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function LX(T,F){let{name:_,config:W}=s(T,F);return new VX(_,W)}class SX extends B{static[H]="PgHalfVectorBuilder";constructor(T,F){super(T,"array","PgHalfVector");this.config.dimensions=F.dimensions}build(T){return new IX(T,this.config)}}class IX extends L{static[H]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((F)=>Number.parseFloat(F))}}function NX(T,F){let{name:_,config:W}=s(T,F);return new SX(_,W)}class CX extends B{static[H]="PgSparseVectorBuilder";constructor(T,F){super(T,"string","PgSparseVector");this.config.dimensions=F.dimensions}build(T){return new kX(T,this.config)}}class kX extends L{static[H]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function BX(T,F){let{name:_,config:W}=s(T,F);return new CX(_,W)}class fX extends B{static[H]="PgVectorBuilder";constructor(T,F){super(T,"array","PgVector");this.config.dimensions=F.dimensions}build(T){return new qX(T,this.config)}}class qX extends L{static[H]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((F)=>Number.parseFloat(F))}}function jX(T,F){let{name:_,config:W}=s(T,F);return new fX(_,W)}function yX(){return{bigint:cY,bigserial:nY,boolean:WW,char:TZ,cidr:WZ,customType:YZ,date:AZ,doublePrecision:OZ,inet:QZ,integer:JW,interval:KZ,json:DZ,jsonb:SZ,line:BZ,macaddr:jZ,macaddr8:vZ,numeric:mZ,point:lZ,geometry:aZ,real:FX,serial:JX,smallint:ZX,smallserial:GX,text:UX,time:QX,timestamp:y0,uuid:D0,varchar:sT,bit:LX,halfvec:NX,sparsevec:BX,vector:jX}}var h4=Symbol.for("drizzle:PgInlineForeignKeys"),PX=Symbol.for("drizzle:EnableRLS");class hT extends C{static[H]="PgTable";static Symbol=Object.assign({},C.Symbol,{InlineForeignKeys:h4,EnableRLS:PX});[h4]=[];[PX]=!1;[C.Symbol.ExtraConfigBuilder]=void 0;[C.Symbol.ExtraConfigColumns]={}}function a3(T,F,_,W,J=T){let $=new hT(T,W,J),Y=typeof F==="function"?F(yX()):F,Z=Object.fromEntries(Object.entries(Y).map(([O,M])=>{let E=M;E.setName(O);let K=E.build($);return $[h4].push(...E.buildForeignKeys(K,$)),[O,K]})),A=Object.fromEntries(Object.entries(Y).map(([O,M])=>{let E=M;E.setName(O);let K=E.buildExtraConfigColumn($);return[O,K]})),X=Object.assign($,Z);if(X[C.Symbol.Columns]=Z,X[C.Symbol.ExtraConfigColumns]=A,_)X[hT.Symbol.ExtraConfigBuilder]=_;return Object.assign(X,{enableRLS:()=>{return X[hT.Symbol.EnableRLS]=!0,X}})}var QF=(T,F,_)=>{return a3(T,F,_,void 0)};function vX(...T){if(T[0].columns)return new $W(T[0].columns,T[0].name);return new $W(T)}class $W{static[H]="PgPrimaryKeyBuilder";columns;name;constructor(T,F){this.columns=T,this.name=F}build(T){return new xX(T,this.columns,this.name)}}class xX{constructor(T,F,_){this.table=T,this.columns=F,this.name=_}static[H]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[hT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function Z0(T,F){if(jY(F)&&!q4(T)&&!R(T,Q0)&&!R(T,UF)&&!R(T,XT)&&!R(T,C)&&!R(T,Y0))return new Q0(T,F);return T}var D1=(T,F)=>{return U`${T} = ${Z0(F,T)}`},bX=(T,F)=>{return U`${T} <> ${Z0(F,T)}`};function YW(...T){let F=T.filter((_)=>_!==void 0);if(F.length===0)return;if(F.length===1)return new k(F);return new k([new PT("("),U.join(F,new PT(" and ")),new PT(")")])}function hX(...T){let F=T.filter((_)=>_!==void 0);if(F.length===0)return;if(F.length===1)return new k(F);return new k([new PT("("),U.join(F,new PT(" or ")),new PT(")")])}function pX(T){return U`not ${T}`}var gX=(T,F)=>{return U`${T} > ${Z0(F,T)}`},mX=(T,F)=>{return U`${T} >= ${Z0(F,T)}`},oX=(T,F)=>{return U`${T} < ${Z0(F,T)}`},uX=(T,F)=>{return U`${T} <= ${Z0(F,T)}`};function cX(T,F){if(Array.isArray(F)){if(F.length===0)return U`false`;return U`${T} in ${F.map((_)=>Z0(_,T))}`}return U`${T} in ${Z0(F,T)}`}function dX(T,F){if(Array.isArray(F)){if(F.length===0)return U`true`;return U`${T} not in ${F.map((_)=>Z0(_,T))}`}return U`${T} not in ${Z0(F,T)}`}function lX(T){return U`${T} is null`}function iX(T){return U`${T} is not null`}function tX(T){return U`exists ${T}`}function nX(T){return U`not exists ${T}`}function rX(T,F,_){return U`${T} between ${Z0(F,T)} and ${Z0(_,T)}`}function sX(T,F,_){return U`${T} not between ${Z0(F,T)} and ${Z0(_,T)}`}function aX(T,F){return U`${T} like ${F}`}function eX(T,F){return U`${T} not like ${F}`}function TA(T,F){return U`${T} ilike ${F}`}function FA(T,F){return U`${T} not ilike ${F}`}function _A(T){return U`${T} asc`}function WA(T){return U`${T} desc`}class p4{constructor(T,F,_){this.sourceTable=T,this.referencedTable=F,this.relationName=_,this.referencedTableName=F[C.Symbol.Name]}static[H]="Relation";referencedTableName;fieldName}class JA{constructor(T,F){this.table=T,this.config=F}static[H]="Relations"}class zF extends p4{constructor(T,F,_,W){super(T,F,_?.relationName);this.config=_,this.isNullable=W}static[H]="One";withFieldName(T){let F=new zF(this.sourceTable,this.referencedTable,this.config,this.isNullable);return F.fieldName=T,F}}class ZW extends p4{constructor(T,F,_){super(T,F,_?.relationName);this.config=_}static[H]="Many";withFieldName(T){let F=new ZW(this.sourceTable,this.referencedTable,this.config);return F.fieldName=T,F}}function $A(){return{and:YW,between:rX,eq:D1,exists:tX,gt:gX,gte:mX,ilike:TA,inArray:cX,isNull:lX,isNotNull:iX,like:aX,lt:oX,lte:uX,ne:bX,not:pX,notBetween:sX,notExists:nX,notLike:eX,notIlike:FA,notInArray:dX,or:hX,sql:U}}function YA(){return{sql:U,asc:_A,desc:WA}}function ZA(T,F){if(Object.keys(T).length===1&&"default"in T&&!R(T.default,C))T=T.default;let _={},W={},J={};for(let[$,Y]of Object.entries(T))if(R(Y,C)){let Z=SF(Y),A=W[Z];_[Z]=$,J[$]={tsName:$,dbName:Y[C.Symbol.Name],schema:Y[C.Symbol.Schema],columns:Y[C.Symbol.Columns],relations:A?.relations??{},primaryKey:A?.primaryKey??[]};for(let O of Object.values(Y[C.Symbol.Columns]))if(O.primary)J[$].primaryKey.push(O);let X=Y[C.Symbol.ExtraConfigBuilder]?.(Y[C.Symbol.ExtraConfigColumns]);if(X){for(let O of Object.values(X))if(R(O,$W))J[$].primaryKey.push(...O.columns)}}else if(R(Y,JA)){let Z=SF(Y.table),A=_[Z],X=Y.config(F(Y.table)),O;for(let[M,E]of Object.entries(X))if(A){let K=J[A];if(K.relations[M]=E,O)K.primaryKey.push(...O)}else{if(!(Z in W))W[Z]={relations:{},primaryKey:O};W[Z].relations[M]=E}}return{tables:J,tableNamesMap:_}}function e3(T){return function F(_,W){return new zF(T,_,W,W?.fields.reduce((J,$)=>J&&$.notNull,!0)??!1)}}function TH(T){return function F(_,W){return new ZW(T,_,W)}}function XA(T,F,_){if(R(_,zF)&&_.config)return{fields:_.config.fields,references:_.config.references};let W=F[SF(_.referencedTable)];if(!W)throw new Error(`Table "${_.referencedTable[C.Symbol.Name]}" not found in schema`);let J=T[W];if(!J)throw new Error(`Table "${W}" not found in schema`);let $=_.sourceTable,Y=F[SF($)];if(!Y)throw new Error(`Table "${$[C.Symbol.Name]}" not found in schema`);let Z=[];for(let A of Object.values(J.relations))if(_.relationName&&_!==A&&A.relationName===_.relationName||!_.relationName&&A.referencedTable===_.sourceTable)Z.push(A);if(Z.length>1)throw _.relationName?new Error(`There are multiple relations with name "${_.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${_.sourceTable[C.Symbol.Name]}". Please specify relation name`);if(Z[0]&&R(Z[0],zF)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw new Error(`There is not enough information to infer relation "${Y}.${_.fieldName}"`)}function AA(T){return{one:e3(T),many:TH(T)}}function L1(T,F,_,W,J=($)=>$){let $={};for(let[Y,Z]of W.entries())if(Z.isJson){let A=F.relations[Z.tsKey],X=_[Y],O=typeof X==="string"?JSON.parse(X):X;$[Z.tsKey]=R(A,zF)?O&&L1(T,T[Z.relationTableTsKey],O,Z.selection,J):O.map((M)=>L1(T,T[Z.relationTableTsKey],M,Z.selection,J))}else{let A=J(_[Y]),X=Z.field,O;if(R(X,XT))O=X;else if(R(X,k))O=X.decoder;else O=X.sql.decoder;$[Z.tsKey]=A===null?null:O.mapFromDriverValue(A)}return $}import SH from"os";import IH from"fs";var S1=new Map,g4=new Map,m4=Symbol("OriginError"),J_={};class L0 extends Promise{constructor(T,F,_,W,J={}){let $,Y;super((Z,A)=>{$=Z,Y=A});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=F,this.handler=_,this.canceller=W,this.options=J,this.state=null,this.statement=null,this.resolve=(Z)=>(this.active=!1,$(Z)),this.reject=(Z)=>(this.active=!1,Y(Z)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[m4]=this.handler.debug?new Error:this.tagged&&FH(this.strings)}get origin(){return(this.handler.debug?this[m4].stack:this.tagged&&g4.has(this.strings)?g4.get(this.strings):g4.set(this.strings,this[m4].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,F){if(this.options.simple=!1,typeof T==="function")F=T,T=1;if(this.cursorRows=T,typeof F==="function")return this.cursorFn=F,this;let _;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};_&&_();let W=new Promise((J,$)=>{this.cursorFn=(Y)=>{return J({value:Y,done:!1}),new Promise((Z)=>_=Z)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=(Y)=>(this.active=!1,$(Y))});return this.execute(),W},return(){return _&&_(J_),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function FH(T){if(S1.has(T))return S1.get(T);let F=Error.stackTraceLimit;return Error.stackTraceLimit=4,S1.set(T,new Error),Error.stackTraceLimit=F,S1.get(T)}class $_ extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var CT={connection:GA,postgres:HA,generic:OA,notSupported:UA};function GA(T,F,_){let{host:W,port:J}=_||F,$=Object.assign(new Error("write "+T+" "+(F.path||W+":"+J)),{code:T,errno:T,address:F.path||W},F.path?{}:{port:J});return Error.captureStackTrace($,GA),$}function HA(T){let F=new $_(T);return Error.captureStackTrace(F,HA),F}function OA(T,F){let _=Object.assign(new Error(T+": "+F),{code:T});return Error.captureStackTrace(_,OA),_}function UA(T){let F=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(F,UA),F}var _H={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class C1{then(){o4()}catch(){o4()}finally(){o4()}}class HW extends C1{constructor(T){super();this.value=f1(T)}}class o0 extends C1{constructor(T,F,_){super();this.value=T,this.type=F,this.array=_}}class k1 extends C1{constructor(T,F){super();this.first=T,this.rest=F}build(T,F,_,W){let J=WH.map(([$,Y])=>({fn:Y,i:T.search($)})).sort(($,Y)=>$.i-Y.i).pop();return J.i===-1?i4(this.first,W):J.fn(this.first,this.rest,F,_,W)}}function B1(T,F,_,W){let J=T instanceof o0?T.value:T;if(J===void 0){if(T instanceof o0?T.value=W.transform.undefined:J=T=W.transform.undefined,J===void 0)throw CT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+_.push(T instanceof o0?(F.push(T.value),T.array?T.array[T.type||N1(T.value)]||T.type||EA(T.value):T.type):(F.push(T),N1(T)))}var QA=wA(_H);function d4(T,F,_,W,J,$){for(let Y=1;Y<T.strings.length;Y++)F+=l4(F,_,W,J,$)+T.strings[Y],_=T.args[Y];return F}function l4(T,F,_,W,J){return F instanceof k1?F.build(T,_,W,J):F instanceof L0?c4(F,_,W,J):F instanceof HW?F.value:F&&F[0]instanceof L0?F.reduce(($,Y)=>$+" "+c4(Y,_,W,J),""):B1(F,_,W,J)}function c4(T,F,_,W){return T.fragment=!0,d4(T,T.strings[0],T.args[0],F,_,W)}function zA(T,F,_,W,J){return T.map(($)=>"("+W.map((Y)=>l4("values",$[Y],F,_,J)).join(",")+")").join(",")}function MA(T,F,_,W,J){let $=Array.isArray(T[0]),Y=F.length?F.flat():Object.keys($?T[0]:T);return zA($?T:[T],_,W,Y,J)}function I1(T,F,_,W,J){if(typeof T==="string"&&(T=[T].concat(F)),Array.isArray(T))return i4(T,J);let $;return(F.length?F.flat():Object.keys(T)).map((Z)=>{return $=T[Z],($ instanceof L0?c4($,_,W,J):$ instanceof HW?$.value:B1($,_,W,J))+" as "+f1(J.transform.column.to?J.transform.column.to(Z):Z)}).join(",")}var WH=Object.entries({values:MA,in:(...T)=>{let F=MA(...T);return F==="()"?"(null)":F},select:I1,as:I1,returning:I1,"\\(":I1,update(T,F,_,W,J){return(F.length?F.flat():Object.keys(T)).map(($)=>f1(J.transform.column.to?J.transform.column.to($):$)+"="+l4("values",T[$],_,W,J))},insert(T,F,_,W,J){let $=F.length?F.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+i4($,J)+")values"+zA(Array.isArray(T)?T:[T],_,W,$,J)}}).map(([T,F])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),F]);function o4(){throw CT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:JH,parsers:$H}=QA;function EA(T){if(Array.isArray(T))return EA(T[0]);return typeof T==="string"?1009:0}var RA=function(T){let F=wA(T||{});return{serializers:Object.assign({},JH,F.serializers),parsers:Object.assign({},$H,F.parsers)}};function wA(T){return Object.keys(T).reduce((F,_)=>{if(T[_].from&&[].concat(T[_].from).forEach((W)=>F.parsers[W]=T[_].parse),T[_].serialize)F.serializers[T[_].to]=T[_].serialize,T[_].from&&[].concat(T[_].from).forEach((W)=>F.serializers[W]=T[_].serialize);return F},{parsers:{},serializers:{}})}function i4(T,{transform:{column:F}}){return T.map((_)=>f1(F.to?F.to(_):_)).join(",")}var f1=function T(F){return'"'+F.replace(/"/g,'""').replace(/\./g,'"."')+'"'},N1=function T(F){return F instanceof o0?F.type:F instanceof Date?1184:F instanceof Uint8Array?17:F===!0||F===!1?16:typeof F==="bigint"?20:Array.isArray(F)?T(F[0]):0},YH=/\\/g,ZH=/"/g;function XH(T){return T.replace(YH,"\\\\").replace(ZH,"\\\"")}var KA=function T(F,_,W,J){if(Array.isArray(F)===!1)return F;if(!F.length)return"{}";let $=F[0],Y=J===1020?";":",";if(Array.isArray($)&&!$.type)return"{"+F.map((Z)=>T(Z,_,W,J)).join(Y)+"}";return"{"+F.map((Z)=>{if(Z===void 0){if(Z=W.transform.undefined,Z===void 0)throw CT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Z===null?"null":'"'+XH(_?_(Z.type?Z.value:Z):""+Z)+'"'}).join(Y)+"}"},u4={i:0,char:null,str:"",quoted:!1,last:0},VA=function T(F,_,W){return u4.i=u4.last=0,DA(u4,F,_,W)};function DA(T,F,_,W){let J=[],$=W===1020?";":",";for(;T.i<F.length;T.i++){if(T.char=F[T.i],T.quoted)if(T.char==="\\")T.str+=F[++T.i];else if(T.char==='"')J.push(_?_(T.str):T.str),T.str="",T.quoted=F[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,J.push(DA(T,F,_,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&J.push(_?_(F.slice(T.last,T.i)):F.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===$&&T.p!=="}"&&T.p!=='"')J.push(_?_(F.slice(T.last,T.i)):F.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&J.push(_?_(F.slice(T.last,T.i+1)):F.slice(T.last,T.i+1)),J}var IF=(T)=>{let F=T[0];for(let _=1;_<T.length;_++)F+=T[_]==="_"?T[++_].toUpperCase():T[_];return F},NF=(T)=>{let F=T[0].toUpperCase();for(let _=1;_<T.length;_++)F+=T[_]==="_"?T[++_].toUpperCase():T[_];return F},CF=(T)=>T.replace(/_/g,"-"),XW=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),AW=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),GW=(T)=>T.replace(/-/g,"_");function t4(T){return function F(_,W){return typeof _==="object"&&_!==null&&(W.type===114||W.type===3802)?Array.isArray(_)?_.map((J)=>F(J,W)):Object.entries(_).reduce((J,[$,Y])=>Object.assign(J,{[T($)]:F(Y,W)}),{}):_}}IF.column={from:IF};IF.value={from:t4(IF)};XW.column={to:XW};var n4={...IF};n4.column.to=XW;NF.column={from:NF};NF.value={from:t4(NF)};AW.column={to:AW};var r4={...NF};r4.column.to=AW;CF.column={from:CF};CF.value={from:t4(CF)};GW.column={to:GW};var s4={...CF};s4.column.to=GW;import LA from"net";import OH from"tls";import OW from"crypto";import a4 from"stream";import{performance as SA}from"perf_hooks";class kF 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 z0=AH;function AH(T=[]){let F=T.slice(),_=0;return{get length(){return F.length-_},remove:(W)=>{let J=F.indexOf(W);return J===-1?null:(F.splice(J,1),W)},push:(W)=>(F.push(W),W),shift:()=>{let W=F[_++];if(_===F.length)_=0,F=[];else F[_-1]=void 0;return W}}}var dT=Buffer.allocUnsafe(256),GH="BCcDdEFfHPpQSX".split("").reduce((T,F)=>{let _=F.charCodeAt(0);return T[F]=()=>{return dT[0]=_,JT.i=5,JT},T},{}),JT=Object.assign(HH,GH,{N:String.fromCharCode(0),i:0,inc(T){return JT.i+=T,JT},str(T){let F=Buffer.byteLength(T);return q1(F),JT.i+=dT.write(T,JT.i,F,"utf8"),JT},i16(T){return q1(2),dT.writeUInt16BE(T,JT.i),JT.i+=2,JT},i32(T,F){if(F||F===0)return dT.writeUInt32BE(T,F),JT;return q1(4),dT.writeUInt32BE(T,JT.i),JT.i+=4,JT},z(T){return q1(T),dT.fill(0,JT.i,JT.i+T),JT.i+=T,JT},raw(T){return dT=Buffer.concat([dT.subarray(0,JT.i),T]),JT.i=dT.length,JT},end(T=1){dT.writeUInt32BE(JT.i-T,T);let F=dT.subarray(0,JT.i);return JT.i=0,dT=Buffer.allocUnsafe(256),F}}),x=JT;function q1(T){if(dT.length-JT.i<T){let F=dT,_=F.length;dT=Buffer.allocUnsafe(_+(_>>1)+T),F.copy(dT)}}function HH(){return JT.i=0,JT}var FJ=CA,UH=1,EF=x().S().end(),IA=x().H().end(),MH=x().i32(8).i32(80877103).end(8),QH=Buffer.concat([x().E().str(x.N).i32(0).end(),EF]),zH=x().D().str("S").str(x.N).end(),Y_=()=>{},EH=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),RH={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 CA(T,F={},{onopen:_=Y_,onend:W=Y_,onclose:J=Y_}={}){let{ssl:$,max:Y,user:Z,host:A,port:X,database:O,parsers:M,transform:E,onnotice:K,onnotify:j,onparameter:S,max_pipeline:P,keep_alive:f,backoff:y,target_session_attrs:h}=T,TT=z0(),u=UH++,g={pid:null,secret:null},d=TJ(c1,T.idle_timeout),ST=TJ(c1,T.max_lifetime),A0=TJ(nA,T.connect_timeout),D=null,$T,l=new kF,e=Buffer.alloc(0),xT=T.fetch_types,G0={},S0={},qF=Math.random().toString(36).slice(2),V=1,p=0,WT=0,wT=0,kT=0,n=0,GT=0,IT=0,KT=null,QT=null,pT=!1,HT=null,I0=null,gT=null,TF=null,BT=null,zT=null,N0=null,P0=null,N=null,G_=null,mT={queue:F.closed,idleTimer:d,connect(G){gT=G||!0,CJ()},terminate:O_,execute:H_,cancel:dA,end:c1,count:0,id:u};return F.closed&&F.closed.push(mT),mT;async function cA(){let G;try{G=T.socket?await Promise.resolve(T.socket(T)):new LA.Socket}catch(Q){yF(Q);return}return G.on("error",yF),G.on("close",kJ),G.on("drain",IJ),G}async function dA({pid:G,secret:Q},b,FT){try{$T=x().i32(16).i32(80877102).i32(G).i32(Q).end(16),await NJ(),D.once("error",FT),D.once("close",b)}catch(DT){FT(DT)}}function H_(G){if(pT)return wW(G,CT.connection("CONNECTION_DESTROYED",T));if(G.cancelled)return;try{return G.state=g,N?TT.push(G):(N=G,N.active=!0),tA(G),bT(lA(G))&&!G.describeFirst&&!G.cursorFn&&TT.length<P&&(!G.options.onexecute||G.options.onexecute(mT))}catch(Q){return TT.length===0&&bT(EF),v0(Q),!0}}function lA(G){if(G.parameters.length>=65534)throw CT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return G.options.simple?x().Q().str(G.statement.string+x.N).end():G.describeFirst?Buffer.concat([DJ(G),IA]):G.prepare?G.prepared?RW(G):Buffer.concat([DJ(G),RW(G)]):iA(G)}function DJ(G){return Buffer.concat([fJ(G.statement.string,G.parameters,G.statement.types,G.statement.name),y5("S",G.statement.name)])}function RW(G){return Buffer.concat([j5(G.parameters,G.statement.types,G.statement.name,G.cursorName),G.cursorFn?qJ("",G.cursorRows):QH])}function iA(G){return Buffer.concat([fJ(G.statement.string,G.parameters,G.statement.types),zH,RW(G)])}function tA(G){let Q=[],b=[],FT=d4(G,G.strings[0],G.args[0],Q,b,T);!G.tagged&&G.args.forEach((DT)=>B1(DT,Q,b,T)),G.prepare=T.prepare&&("prepare"in G.options?G.options.prepare:!0),G.string=FT,G.signature=G.prepare&&b+FT,G.onlyDescribe&&delete S0[G.signature],G.parameters=G.parameters||Q,G.prepared=G.prepare&&G.signature in S0,G.describeFirst=G.onlyDescribe||Q.length&&!G.prepared,G.statement=G.prepared?S0[G.signature]:{string:FT,types:b,name:G.prepare?qF+V++:""},typeof T.debug==="function"&&T.debug(u,FT,Q,b)}function bT(G,Q){if(zT=zT?Buffer.concat([zT,G]):Buffer.from(G),Q||zT.length>=1024)return LJ(Q);return QT===null&&(QT=setImmediate(LJ)),!0}function LJ(G){let Q=D.write(zT,G);return QT!==null&&clearImmediate(QT),zT=QT=null,Q}function nA(){v0(CT.connection("CONNECT_TIMEOUT",T,D)),D.destroy()}async function SJ(){if(bT(MH),!await new Promise((Q)=>D.once("data",(b)=>Q(b[0]===83)))&&$==="prefer")return jF();D.removeAllListeners(),D=OH.connect({socket:D,servername:LA.isIP(D.host)?void 0:D.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),D.on("secureConnect",jF),D.on("error",yF),D.on("close",kJ),D.on("drain",IJ)}function IJ(){!N&&_(mT)}function u1(G){if(HT){if(HT.push(G),WT-=G.length,WT>=0)return}e=HT?Buffer.concat(HT,n-WT):e.length===0?G:Buffer.concat([e,G],e.length+G.length);while(e.length>4){if(n=e.readUInt32BE(1),n>=e.length){WT=n-e.length,HT=[e];break}try{rA(e.subarray(0,n+1))}catch(Q){N&&(N.cursorFn||N.describeFirst)&&bT(EF),v0(Q)}e=e.subarray(n+1),WT=0,HT=null}}async function NJ(){if(pT=!1,G0={},D||(D=await cA()),!D)return;if(A0.start(),T.socket)return $?SJ():jF();if(D.on("connect",$?SJ:jF),T.path)return D.connect(T.path);D.ssl=$,D.connect(X[wT],A[wT]),D.host=A[wT],D.port=X[wT],wT=(wT+1)%X.length}function CJ(){setTimeout(NJ,p?p+GT-SA.now():0)}function jF(){try{S0={},xT=T.fetch_types,qF=Math.random().toString(36).slice(2),V=1,ST.start(),D.on("data",u1),f&&D.setKeepAlive&&D.setKeepAlive(!0,1000*f);let G=v5();bT(G)}catch(G){yF(G)}}function yF(G){if(mT.queue===F.connecting&&T.host[kT+1])return;v0(G);while(TT.length)wW(TT.shift(),G)}function v0(G){BT&&(BT.destroy(G),BT=null),N&&wW(N,G),gT&&(wW(gT,G),gT=null)}function wW(G,Q){"query"in Q||"parameters"in Q||Object.defineProperties(Q,{stack:{value:Q.stack+G.origin.replace(/.*\n/,`
50
+ `),enumerable:T.debug},query:{value:G.string,enumerable:T.debug},parameters:{value:G.parameters,enumerable:T.debug},args:{value:G.args,enumerable:T.debug},types:{value:G.statement&&G.statement.types,enumerable:T.debug}}),G.reject(Q)}function c1(){return TF||(!mT.reserved&&W(mT),!mT.reserved&&!gT&&!N&&TT.length===0?(O_(),new Promise((G)=>D&&D.readyState!=="closed"?D.once("close",G):G())):TF=new Promise((G)=>N0=G))}function O_(){if(pT=!0,BT||N||gT||TT.length)yF(CT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(QT),D)D.removeListener("data",u1),D.removeListener("connect",jF),D.readyState==="open"&&D.end(x().X().end());N0&&(N0(),TF=N0=null)}async function kJ(G){if(e=Buffer.alloc(0),WT=0,HT=null,clearImmediate(QT),D.removeListener("data",u1),D.removeListener("connect",jF),d.cancel(),ST.cancel(),A0.cancel(),D.removeAllListeners(),D=null,gT)return CJ();!G&&(N||TT.length)&&yF(CT.connection("CONNECTION_CLOSED",T,D)),p=SA.now(),G&&T.shared.retries++,GT=(typeof y==="function"?y(T.shared.retries):y)*1000,J(mT,CT.connection("CONNECTION_CLOSED",T,D))}function rA(G,Q=G[0]){(Q===68?sA:Q===100?S5:Q===65?R5:Q===83?aA:Q===90?eA:Q===67?T5:Q===50?BJ:Q===49?F5:Q===116?_5:Q===84?W5:Q===82?J5:Q===110?G5:Q===75?H5:Q===69?z5:Q===115?w5:Q===51?K5:Q===71?V5:Q===78?N5:Q===72?D5:Q===99?I5:Q===73?C5:Q===86?k5:Q===118?B5:Q===87?L5:f5)(G)}function sA(G){let Q=7,b,FT,DT,oT=N.isRaw?new Array(N.statement.columns.length):{};for(let lT=0;lT<N.statement.columns.length;lT++)FT=N.statement.columns[lT],b=G.readInt32BE(Q),Q+=4,DT=b===-1?null:N.isRaw===!0?G.subarray(Q,Q+=b):FT.parser===void 0?G.toString("utf8",Q,Q+=b):FT.parser.array===!0?FT.parser(G.toString("utf8",Q+1,Q+=b)):FT.parser(G.toString("utf8",Q,Q+=b)),N.isRaw?oT[lT]=N.isRaw===!0?DT:E.value.from?E.value.from(DT,FT):DT:oT[FT.name]=E.value.from?E.value.from(DT,FT):DT;N.forEachFn?N.forEachFn(E.row.from?E.row.from(oT):oT,l):l[IT++]=E.row.from?E.row.from(oT):oT}function aA(G){let[Q,b]=G.toString("utf8",5,G.length-1).split(x.N);if(G0[Q]=b,T.parameters[Q]!==b)T.parameters[Q]=b,S&&S(Q,b)}function eA(G){if(N&&N.options.simple&&N.resolve(I0||l),N=I0=null,l=new kF,A0.cancel(),gT){if(h){if(!G0.in_hot_standby||!G0.default_transaction_read_only)return Q5();else if(M5(h,G0))return O_()}if(xT)return gT===!0&&(gT=null),O5();gT!==!0&&H_(gT),T.shared.retries=kT=0,gT=null;return}while(TT.length&&(N=TT.shift())&&(N.active=!0,N.cancelled))CA(T).cancel(N.state,N.cancelled.resolve,N.cancelled.reject);if(N)return;mT.reserved?!mT.reserved.release&&G[5]===73?TF?O_():(mT.reserved=null,_(mT)):mT.reserved():TF?O_():_(mT)}function T5(G){IT=0;for(let Q=G.length-1;Q>0;Q--){if(G[Q]===32&&G[Q+1]<58&&l.count===null)l.count=+G.toString("utf8",Q+1,G.length-1);if(G[Q-1]>=65){l.command=G.toString("utf8",5,Q),l.state=g;break}}if(G_&&(G_(),G_=null),l.command==="BEGIN"&&Y!==1&&!mT.reserved)return v0(CT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(N.options.simple)return BJ();if(N.cursorFn)l.count&&N.cursorFn(l),bT(EF);N.resolve(l)}function F5(){N.parsing=!1}function BJ(){!l.statement&&(l.statement=N.statement),l.columns=N.statement.columns}function _5(G){let Q=G.readUInt16BE(5);for(let b=0;b<Q;++b)!N.statement.types[b]&&(N.statement.types[b]=G.readUInt32BE(7+b*4));N.prepare&&(S0[N.signature]=N.statement),N.describeFirst&&!N.onlyDescribe&&(bT(RW(N)),N.describeFirst=!1)}function W5(G){if(l.command)I0=I0||[l],I0.push(l=new kF),l.count=null,N.statement.columns=null;let Q=G.readUInt16BE(5),b=7,FT;N.statement.columns=Array(Q);for(let DT=0;DT<Q;++DT){FT=b;while(G[b++]!==0);let oT=G.readUInt32BE(b),lT=G.readUInt16BE(b+4),FF=G.readUInt32BE(b+6);N.statement.columns[DT]={name:E.column.from?E.column.from(G.toString("utf8",FT,b-1)):G.toString("utf8",FT,b-1),parser:M[FF],table:oT,number:lT,type:FF},b+=18}if(l.statement=N.statement,N.onlyDescribe)return N.resolve(N.statement),bT(EF)}async function J5(G,Q=G.readUInt32BE(5)){(Q===3?$5:Q===5?Y5:Q===10?Z5:Q===11?X5:Q===12?A5:Q!==0?q5:Y_)(G,Q)}async function $5(){let G=await d1();bT(x().p().str(G).z(1).end())}async function Y5(G){let Q="md5"+await NA(Buffer.concat([Buffer.from(await NA(await d1()+Z)),G.subarray(9)]));bT(x().p().str(Q).z(1).end())}async function Z5(){P0=(await OW.randomBytes(18)).toString("base64"),x().p().str("SCRAM-SHA-256"+x.N);let G=x.i;bT(x.inc(4).str("n,,n=*,r="+P0).i32(x.i-G-4,G).end())}async function X5(G){let Q=G.toString("utf8",9).split(",").reduce((lT,FF)=>(lT[FF[0]]=FF.slice(2),lT),{}),b=await OW.pbkdf2Sync(await d1(),Buffer.from(Q.s,"base64"),parseInt(Q.i),32,"sha256"),FT=await j1(b,"Client Key"),DT="n=*,r="+P0+",r="+Q.r+",s="+Q.s+",i="+Q.i+",c=biws,r="+Q.r;KT=(await j1(await j1(b,"Server Key"),DT)).toString("base64");let oT="c=biws,r="+Q.r+",p="+KH(FT,Buffer.from(await j1(await wH(FT),DT))).toString("base64");bT(x().p().str(oT).end())}function A5(G){if(G.toString("utf8",9).split(x.N,1)[0].slice(2)===KT)return;v0(CT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),D.destroy()}function d1(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function G5(){if(l.statement=N.statement,l.statement.columns=[],N.onlyDescribe)return N.resolve(N.statement),bT(EF)}function H5(G){g.pid=G.readUInt32BE(5),g.secret=G.readUInt32BE(9)}async function O5(){xT=!1,(await new L0([`
62
51
  select b.oid, b.typarray
63
52
  from pg_catalog.pg_type a
64
53
  left join pg_catalog.pg_type b on b.oid = a.typelem
65
54
  where a.typcategory = 'A'
66
55
  group by b.oid, b.typarray
67
56
  order by b.oid
68
- `],[],PA)).forEach(({oid:Z,typarray:c})=>g4(Z,c))}function g4(W,Z){if(!!T.parsers[Z]&&!!T.serializers[Z])return;let c=T.parsers[W];T.shared.typeArrayMap[W]=Z,T.parsers[Z]=(RT)=>s2(RT,c,Z),T.parsers[Z].array=!0,T.serializers[Z]=(RT)=>l2(RT,T.serializers[W],T,Z)}function n4(W,Z){return W==="read-write"&&Z.default_transaction_read_only==="on"||W==="read-only"&&Z.default_transaction_read_only==="off"||W==="primary"&&Z.in_hot_standby==="on"||W==="standby"&&Z.in_hot_standby==="off"||W==="prefer-standby"&&Z.in_hot_standby==="off"&&T.host[PT]}function u4(){let W=new vo([`
57
+ `],[],H_)).forEach(({oid:Q,typarray:b})=>U5(Q,b))}function U5(G,Q){if(!!T.parsers[Q]&&!!T.serializers[Q])return;let b=T.parsers[G];T.shared.typeArrayMap[G]=Q,T.parsers[Q]=(FT)=>VA(FT,b,Q),T.parsers[Q].array=!0,T.serializers[Q]=(FT)=>KA(FT,T.serializers[G],T,Q)}function M5(G,Q){return G==="read-write"&&Q.default_transaction_read_only==="on"||G==="read-only"&&Q.default_transaction_read_only==="off"||G==="primary"&&Q.in_hot_standby==="on"||G==="standby"&&Q.in_hot_standby==="off"||G==="prefer-standby"&&Q.in_hot_standby==="off"&&T.host[kT]}function Q5(){let G=new L0([`
69
58
  show transaction_read_only;
70
59
  select pg_catalog.pg_is_in_recovery()
71
- `],[],PA,null,{simple:!0});W.resolve=([[Z],[c]])=>{vT.default_transaction_read_only=Z.transaction_read_only,vT.in_hot_standby=c.pg_is_in_recovery?"on":"off"},W.execute()}function c4(W){N&&(N.cursorFn||N.describeFirst)&&sT(bF);let Z=qT.postgres(o_(W));N&&N.retried?lo(N.retried):N&&N.prepared&&sZ.has(Z.routine)?i4(N,Z):lo(Z)}function i4(W,Z){delete Xo[W.signature],W.retried=Z,PA(W)}function d4(W){if(!Q)return;let Z=9;while(W[Z++]!==0);Q(W.toString("utf8",9,Z-1),W.toString("utf8",Z,W.length-1))}async function r4(){try{let W=await Promise.resolve(N.cursorFn(t));xT=0,W===NA?sT(RX(N.portal)):(t=new eF,sT(p_("",N.cursorRows)))}catch(W){sT(bF),N.reject(W)}}function l4(){t.count&&N.cursorFn(t),N.resolve(t)}function s4(){mT=new T_.Writable({autoDestroy:!0,write(W,Z,c){z.write(u().d().raw(W).end(),c)},destroy(W,Z){Z(W),z.write(u().f().str(W+u.N).end()),mT=null},final(W){z.write(u().c().end()),vA=W}}),N.resolve(mT)}function a4(){mT=new T_.Readable({read(){z.resume()}}),N.resolve(mT)}function e4(){mT=new T_.Duplex({autoDestroy:!0,read(){z.resume()},write(W,Z,c){z.write(u().d().raw(W).end(),c)},destroy(W,Z){Z(W),z.write(u().f().str(W+u.N).end()),mT=null},final(W){z.write(u().c().end()),vA=W}}),N.resolve(mT)}function TX(W){mT&&(mT.push(W.subarray(5))||z.pause())}function oX(){mT&&mT.push(null),mT=null}function FX(W){H?H(o_(W)):console.log(o_(W))}function AX(){}function yX(){lo(qT.notSupported("FunctionCallResponse"))}function SX(){lo(qT.notSupported("NegotiateProtocolVersion"))}function fX(W){console.error("Postgres.js : Unknown Message:",W[0])}function $X(W,Z){console.error("Postgres.js : Unknown Auth:",Z)}function JX(W,Z,c="",RT=""){let NT,Ao;return u().B().str(RT+u.N).str(c+u.N).i16(0).i16(W.length),W.forEach((Jo,EF)=>{if(Jo===null)return u.i32(4294967295);Ao=Z[EF],W[EF]=Jo=Ao in T.serializers?T.serializers[Ao](Jo):""+Jo,NT=u.i,u.inc(4).str(Jo).i32(u.i-NT-4,NT)}),u.i16(0),u.end()}function N_(W,Z,c,RT=""){return u().P().str(RT+u.N).str(W+u.N).i16(Z.length),Z.forEach((NT,Ao)=>u.i32(c[Ao]||0)),u.end()}function _X(W,Z=""){return u().D().str(W).str(Z+u.N).end()}function p_(W="",Z=0){return Buffer.concat([u().E().str(W+u.N).i32(Z).end(),o4])}function RX(W=""){return Buffer.concat([u().C().str("P").str(W+u.N).end(),u().S().end()])}function WX(){return a||u().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:$,database:R,client_encoding:"UTF8"},T.connection)).filter(([,W])=>W).map(([W,Z])=>W+u.N+Z).join(u.N)).z(2).end(0)}}function o_(T){let o={},F=5;for(let A=5;A<T.length-1;A++)if(T[A]===0)o[aZ[T[F]]]=T.toString("utf8",F+1,A),F=A+1;return o}function F4(T){return gy.createHash("md5").update(T).digest("hex")}function Zf(T,o){return gy.createHmac("sha256",T).update(o).digest()}function eZ(T){return gy.createHash("sha256").update(T).digest()}function TH(T,o){let F=Math.max(T.length,o.length),A=Buffer.allocUnsafe(F);for(let y=0;y<F;y++)A[y]=T[y]^o[y];return A}function F_(T,o){if(o=typeof o==="function"?o():o,!o)return{cancel:jA,start:jA};let F;return{cancel(){F&&(clearTimeout(F),F=null)},start(){F&&clearTimeout(F),F=setTimeout(A,o*1000,arguments)}};function A(y){T.apply(null,y),F=null}}var y4=()=>{};function y_(T,o){let F=new Map,A="postgresjs_"+Math.random().toString(36).slice(2),y={},S,f,$=!1,_=O.sql=T({...o,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...o.connection,replication:"database"},onclose:async function(){if($)return;f=null,y.pid=y.secret=void 0,Y(await H(_,A,o.publications)),F.forEach((E)=>E.forEach(({onsubscribe:B})=>B()))},no_subscribe:!0}),J=_.end,R=_.close;return _.end=async()=>{return $=!0,f&&await new Promise((E)=>(f.once("close",E),f.end())),J()},_.close=async()=>{return f&&await new Promise((E)=>(f.once("close",E),f.end())),R()},O;async function O(E,B,p=y4,v=y4){if(E=AH(E),!S)S=H(_,A,o.publications);let h={fn:B,onsubscribe:p},U=F.has(E)?F.get(E).add(h):F.set(E,new Set([h])).get(E),V=()=>{U.delete(h),U.size===0&&F.delete(E)};return S.then((I)=>{return Y(I),p(),f&&f.on("error",v),{unsubscribe:V,state:y,sql:_}})}function Y(E){f=E.stream,y.pid=E.state.pid,y.secret=E.state.secret}async function H(E,B,p){if(!p)throw new Error("Missing publication names");let v=await E.unsafe(`CREATE_REPLICATION_SLOT ${B} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=v,U=await E.unsafe(`START_REPLICATION SLOT ${B} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${p}')`).writable(),V={lsn:Buffer.concat(h.consistent_point.split("/").map((z)=>Buffer.from(("00000000"+z).slice(-8),"hex")))};return U.on("data",L),U.on("error",I),U.on("close",E.close),{stream:U,state:v.state};function I(z){console.error("Unexpected error during logical streaming - reconnecting",z)}function L(z){if(z[0]===119)FH(z.subarray(25),V,E.options.parsers,m,o.transform);else if(z[0]===107&&z[17])V.lsn=z.subarray(1,9),s()}function m(z,a){let t=a.relation.schema+"."+a.relation.table;Q("*",z,a),Q("*:"+t,z,a),a.relation.keys.length&&Q("*:"+t+"="+a.relation.keys.map((e)=>z[e.name]),z,a),Q(a.command,z,a),Q(a.command+":"+t,z,a),a.relation.keys.length&&Q(a.command+":"+t+"="+a.relation.keys.map((e)=>z[e.name]),z,a)}function s(){let z=Buffer.alloc(34);z[0]=114,z.fill(V.lsn,1),z.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),U.write(z)}}function Q(E,B,p){F.has(E)&&F.get(E).forEach(({fn:v})=>v(B,p,E))}}function oH(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function FH(T,o,F,A,y){let S=(f,[$,_])=>(f[$.charCodeAt(0)]=_,f);Object.entries({R:(f)=>{let $=1,_=o[f.readUInt32BE($)]={schema:f.toString("utf8",$+=4,$=f.indexOf(0,$))||"pg_catalog",table:f.toString("utf8",$+1,$=f.indexOf(0,$+1)),columns:Array(f.readUInt16BE($+=2)),keys:[]};$+=2;let J=0,R;while($<f.length)R=_.columns[J++]={key:f[$++],name:y.column.from?y.column.from(f.toString("utf8",$,$=f.indexOf(0,$))):f.toString("utf8",$,$=f.indexOf(0,$)),type:f.readUInt32BE($+=1),parser:F[f.readUInt32BE($)],atttypmod:f.readUInt32BE($+=4)},R.key&&_.keys.push(R),$+=4},Y:()=>{},O:()=>{},B:(f)=>{o.date=oH(f.readBigInt64BE(9)),o.lsn=f.subarray(1,9)},I:(f)=>{let $=1,_=o[f.readUInt32BE($)],{row:J}=Hf(f,_.columns,$+=7,y);A(J,{command:"insert",relation:_})},D:(f)=>{let $=1,_=o[f.readUInt32BE($)];$+=4;let J=f[$]===75;A(J||f[$]===79?Hf(f,_.columns,$+=3,y).row:null,{command:"delete",relation:_,key:J})},U:(f)=>{let $=1,_=o[f.readUInt32BE($)];$+=4;let J=f[$]===75,R=J||f[$]===79?Hf(f,_.columns,$+=3,y):null;R&&($=R.i);let{row:O}=Hf(f,_.columns,$+3,y);A(O,{command:"update",relation:_,key:J,old:R&&R.row})},T:()=>{},C:()=>{}}).reduce(S,{})[T[0]](T)}function Hf(T,o,F,A){let y,S,f,$=A.raw?new Array(o.length):{};for(let _=0;_<o.length;_++)y=T[F++],S=o[_],f=y===110?null:y===117?void 0:S.parser===void 0?T.toString("utf8",F+4,F+=4+T.readUInt32BE(F)):S.parser.array===!0?S.parser(T.toString("utf8",F+5,F+=4+T.readUInt32BE(F))):S.parser(T.toString("utf8",F+4,F+=4+T.readUInt32BE(F))),A.raw?$[_]=A.raw===!0?f:A.value.from?A.value.from(f,S):f:$[S.name]=A.value.from?A.value.from(f,S):f;return{i:F,row:A.row.from?A.row.from($):$}}function AH(T){let o=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!o)throw new Error("Malformed subscribe pattern: "+T);let[,F,A,y]=o;return(F||"*")+(A?":"+(A.indexOf(".")===-1?"public."+A:A):"")+(y?"="+y:"")}import S4 from"stream";function S_(T,o,F=393216){return new Promise(async(A,y)=>{await T.begin(async(S)=>{let f;!o&&([{oid:o}]=await S`select lo_creat(-1) as oid`);let[{fd:$}]=await S`select lo_open(${o}, ${F}) as fd`,_={writable:R,readable:J,close:()=>S`select lo_close(${$})`.then(f),tell:()=>S`select lo_tell64(${$})`,read:(O)=>S`select loread(${$}, ${O}) as data`,write:(O)=>S`select lowrite(${$}, ${O})`,truncate:(O)=>S`select lo_truncate64(${$}, ${O})`,seek:(O,Y=0)=>S`select lo_lseek64(${$}, ${O}, ${Y})`,size:()=>S`
60
+ `],[],H_,null,{simple:!0});G.resolve=([[Q],[b]])=>{G0.default_transaction_read_only=Q.transaction_read_only,G0.in_hot_standby=b.pg_is_in_recovery?"on":"off"},G.execute()}function z5(G){N&&(N.cursorFn||N.describeFirst)&&bT(EF);let Q=CT.postgres(e4(G));N&&N.retried?v0(N.retried):N&&N.prepared&&EH.has(Q.routine)?E5(N,Q):v0(Q)}function E5(G,Q){delete S0[G.signature],G.retried=Q,H_(G)}function R5(G){if(!j)return;let Q=9;while(G[Q++]!==0);j(G.toString("utf8",9,Q-1),G.toString("utf8",Q,G.length-1))}async function w5(){try{let G=await Promise.resolve(N.cursorFn(l));IT=0,G===J_?bT(P5(N.portal)):(l=new kF,bT(qJ("",N.cursorRows)))}catch(G){bT(EF),N.reject(G)}}function K5(){l.count&&N.cursorFn(l),N.resolve(l)}function V5(){BT=new a4.Writable({autoDestroy:!0,write(G,Q,b){D.write(x().d().raw(G).end(),b)},destroy(G,Q){Q(G),D.write(x().f().str(G+x.N).end()),BT=null},final(G){D.write(x().c().end()),G_=G}}),N.resolve(BT)}function D5(){BT=new a4.Readable({read(){D.resume()}}),N.resolve(BT)}function L5(){BT=new a4.Duplex({autoDestroy:!0,read(){D.resume()},write(G,Q,b){D.write(x().d().raw(G).end(),b)},destroy(G,Q){Q(G),D.write(x().f().str(G+x.N).end()),BT=null},final(G){D.write(x().c().end()),G_=G}}),N.resolve(BT)}function S5(G){BT&&(BT.push(G.subarray(5))||D.pause())}function I5(){BT&&BT.push(null),BT=null}function N5(G){K?K(e4(G)):console.log(e4(G))}function C5(){}function k5(){v0(CT.notSupported("FunctionCallResponse"))}function B5(){v0(CT.notSupported("NegotiateProtocolVersion"))}function f5(G){console.error("Postgres.js : Unknown Message:",G[0])}function q5(G,Q){console.error("Postgres.js : Unknown Auth:",Q)}function j5(G,Q,b="",FT=""){let DT,oT;return x().B().str(FT+x.N).str(b+x.N).i16(0).i16(G.length),G.forEach((lT,FF)=>{if(lT===null)return x.i32(4294967295);oT=Q[FF],G[FF]=lT=oT in T.serializers?T.serializers[oT](lT):""+lT,DT=x.i,x.inc(4).str(lT).i32(x.i-DT-4,DT)}),x.i16(0),x.end()}function fJ(G,Q,b,FT=""){return x().P().str(FT+x.N).str(G+x.N).i16(Q.length),Q.forEach((DT,oT)=>x.i32(b[oT]||0)),x.end()}function y5(G,Q=""){return x().D().str(G).str(Q+x.N).end()}function qJ(G="",Q=0){return Buffer.concat([x().E().str(G+x.N).i32(Q).end(),IA])}function P5(G=""){return Buffer.concat([x().C().str("P").str(G+x.N).end(),x().S().end()])}function v5(){return $T||x().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:Z,database:O,client_encoding:"UTF8"},T.connection)).filter(([,G])=>G).map(([G,Q])=>G+x.N+Q).join(x.N)).z(2).end(0)}}function e4(T){let F={},_=5;for(let W=5;W<T.length-1;W++)if(T[W]===0)F[RH[T[_]]]=T.toString("utf8",_+1,W),_=W+1;return F}function NA(T){return OW.createHash("md5").update(T).digest("hex")}function j1(T,F){return OW.createHmac("sha256",T).update(F).digest()}function wH(T){return OW.createHash("sha256").update(T).digest()}function KH(T,F){let _=Math.max(T.length,F.length),W=Buffer.allocUnsafe(_);for(let J=0;J<_;J++)W[J]=T[J]^F[J];return W}function TJ(T,F){if(F=typeof F==="function"?F():F,!F)return{cancel:Y_,start:Y_};let _;return{cancel(){_&&(clearTimeout(_),_=null)},start(){_&&clearTimeout(_),_=setTimeout(W,F*1000,arguments)}};function W(J){T.apply(null,J),_=null}}var kA=()=>{};function _J(T,F){let _=new Map,W="postgresjs_"+Math.random().toString(36).slice(2),J={},$,Y,Z=!1,A=M.sql=T({...F,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...F.connection,replication:"database"},onclose:async function(){if(Z)return;Y=null,J.pid=J.secret=void 0,E(await K(A,W,F.publications)),_.forEach((S)=>S.forEach(({onsubscribe:P})=>P()))},no_subscribe:!0}),X=A.end,O=A.close;return A.end=async()=>{return Z=!0,Y&&await new Promise((S)=>(Y.once("close",S),Y.end())),X()},A.close=async()=>{return Y&&await new Promise((S)=>(Y.once("close",S),Y.end())),O()},M;async function M(S,P,f=kA,y=kA){if(S=LH(S),!$)$=K(A,W,F.publications);let h={fn:P,onsubscribe:f},TT=_.has(S)?_.get(S).add(h):_.set(S,new Set([h])).get(S),u=()=>{TT.delete(h),TT.size===0&&_.delete(S)};return $.then((g)=>{return E(g),f(),Y&&Y.on("error",y),{unsubscribe:u,state:J,sql:A}})}function E(S){Y=S.stream,J.pid=S.state.pid,J.secret=S.state.secret}async function K(S,P,f){if(!f)throw new Error("Missing publication names");let y=await S.unsafe(`CREATE_REPLICATION_SLOT ${P} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=y,TT=await S.unsafe(`START_REPLICATION SLOT ${P} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${f}')`).writable(),u={lsn:Buffer.concat(h.consistent_point.split("/").map((D)=>Buffer.from(("00000000"+D).slice(-8),"hex")))};return TT.on("data",d),TT.on("error",g),TT.on("close",S.close),{stream:TT,state:y.state};function g(D){console.error("Unexpected error during logical streaming - reconnecting",D)}function d(D){if(D[0]===119)DH(D.subarray(25),u,S.options.parsers,ST,F.transform);else if(D[0]===107&&D[17])u.lsn=D.subarray(1,9),A0()}function ST(D,$T){let l=$T.relation.schema+"."+$T.relation.table;j("*",D,$T),j("*:"+l,D,$T),$T.relation.keys.length&&j("*:"+l+"="+$T.relation.keys.map((e)=>D[e.name]),D,$T),j($T.command,D,$T),j($T.command+":"+l,D,$T),$T.relation.keys.length&&j($T.command+":"+l+"="+$T.relation.keys.map((e)=>D[e.name]),D,$T)}function A0(){let D=Buffer.alloc(34);D[0]=114,D.fill(u.lsn,1),D.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),TT.write(D)}}function j(S,P,f){_.has(S)&&_.get(S).forEach(({fn:y})=>y(P,f,S))}}function VH(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function DH(T,F,_,W,J){let $=(Y,[Z,A])=>(Y[Z.charCodeAt(0)]=A,Y);Object.entries({R:(Y)=>{let Z=1,A=F[Y.readUInt32BE(Z)]={schema:Y.toString("utf8",Z+=4,Z=Y.indexOf(0,Z))||"pg_catalog",table:Y.toString("utf8",Z+1,Z=Y.indexOf(0,Z+1)),columns:Array(Y.readUInt16BE(Z+=2)),keys:[]};Z+=2;let X=0,O;while(Z<Y.length)O=A.columns[X++]={key:Y[Z++],name:J.column.from?J.column.from(Y.toString("utf8",Z,Z=Y.indexOf(0,Z))):Y.toString("utf8",Z,Z=Y.indexOf(0,Z)),type:Y.readUInt32BE(Z+=1),parser:_[Y.readUInt32BE(Z)],atttypmod:Y.readUInt32BE(Z+=4)},O.key&&A.keys.push(O),Z+=4},Y:()=>{},O:()=>{},B:(Y)=>{F.date=VH(Y.readBigInt64BE(9)),F.lsn=Y.subarray(1,9)},I:(Y)=>{let Z=1,A=F[Y.readUInt32BE(Z)],{row:X}=y1(Y,A.columns,Z+=7,J);W(X,{command:"insert",relation:A})},D:(Y)=>{let Z=1,A=F[Y.readUInt32BE(Z)];Z+=4;let X=Y[Z]===75;W(X||Y[Z]===79?y1(Y,A.columns,Z+=3,J).row:null,{command:"delete",relation:A,key:X})},U:(Y)=>{let Z=1,A=F[Y.readUInt32BE(Z)];Z+=4;let X=Y[Z]===75,O=X||Y[Z]===79?y1(Y,A.columns,Z+=3,J):null;O&&(Z=O.i);let{row:M}=y1(Y,A.columns,Z+3,J);W(M,{command:"update",relation:A,key:X,old:O&&O.row})},T:()=>{},C:()=>{}}).reduce($,{})[T[0]](T)}function y1(T,F,_,W){let J,$,Y,Z=W.raw?new Array(F.length):{};for(let A=0;A<F.length;A++)J=T[_++],$=F[A],Y=J===110?null:J===117?void 0:$.parser===void 0?T.toString("utf8",_+4,_+=4+T.readUInt32BE(_)):$.parser.array===!0?$.parser(T.toString("utf8",_+5,_+=4+T.readUInt32BE(_))):$.parser(T.toString("utf8",_+4,_+=4+T.readUInt32BE(_))),W.raw?Z[A]=W.raw===!0?Y:W.value.from?W.value.from(Y,$):Y:Z[$.name]=W.value.from?W.value.from(Y,$):Y;return{i:_,row:W.row.from?W.row.from(Z):Z}}function LH(T){let F=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!F)throw new Error("Malformed subscribe pattern: "+T);let[,_,W,J]=F;return(_||"*")+(W?":"+(W.indexOf(".")===-1?"public."+W:W):"")+(J?"="+J:"")}import BA from"stream";function WJ(T,F,_=393216){return new Promise(async(W,J)=>{await T.begin(async($)=>{let Y;!F&&([{oid:F}]=await $`select lo_creat(-1) as oid`);let[{fd:Z}]=await $`select lo_open(${F}, ${_}) as fd`,A={writable:O,readable:X,close:()=>$`select lo_close(${Z})`.then(Y),tell:()=>$`select lo_tell64(${Z})`,read:(M)=>$`select loread(${Z}, ${M}) as data`,write:(M)=>$`select lowrite(${Z}, ${M})`,truncate:(M)=>$`select lo_truncate64(${Z}, ${M})`,seek:(M,E=0)=>$`select lo_lseek64(${Z}, ${M}, ${E})`,size:()=>$`
72
61
  select
73
- lo_lseek64(${$}, location, 0) as position,
62
+ lo_lseek64(${Z}, location, 0) as position,
74
63
  seek.size
75
64
  from (
76
65
  select
@@ -78,10 +67,10 @@ ${f.trace}`:"No previous disposal trace was found."),A.type){case"atom_family":c
78
67
  tell.location
79
68
  from (select lo_tell64($1) as location) tell
80
69
  ) seek
81
- `};return A(_),new Promise(async(O)=>f=O);async function J({highWaterMark:O=16384,start:Y=0,end:H=1/0}={}){let Q=H-Y;return Y&&await _.seek(Y),new S4.Readable({highWaterMark:O,async read(E){let B=E>Q?E-Q:E;Q-=E;let[{data:p}]=await _.read(B);if(this.push(p),p.length<E)this.push(null)}})}async function R({highWaterMark:O=16384,start:Y=0}={}){return Y&&await _.seek(Y),new S4.Writable({highWaterMark:O,write(H,Q,E){_.write(H).then(()=>E(),E)}})}}).catch(y)})}Object.assign(Gf,{PostgresError:pA,toPascal:sF,pascal:aJ,toCamel:lF,camel:sJ,toKebab:aF,kebab:eJ,fromPascal:my,fromCamel:Py,fromKebab:ty,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var xA=Gf;function Gf(T,o){let F=fH(T,o),A=F.no_subscribe||y_(Gf,{...F}),y=!1,S=Io(),f=Io(),$=Io(),_=Io(),J=Io(),R=Io(),O=Io(),Y=Io(),H={connecting:f,reserved:$,closed:_,ended:J,open:R,busy:O,full:Y},Q=[...Array(F.max)].map(()=>A_(F,H,{onopen:Xo,onend:vT,onclose:AF})),E=B(m);return Object.assign(E,{get parameters(){return F.parameters},largeObject:S_.bind(null,E),subscribe:A,CLOSE:NA,END:NA,PostgresError:pA,options:F,reserve:h,listen:p,begin:U,close:t,end:a}),E;function B(D){return D.debug=F.debug,Object.entries(F.types).reduce((FT,[ET,xT])=>{return FT[ET]=(kT)=>new FF(kT,xT.to),FT},g),Object.assign(_T,{types:g,typed:g,unsafe:IT,notify:v,array:L,json:I,file:PT}),_T;function g(FT,ET){return new FF(FT,ET)}function _T(FT,...ET){return FT&&Array.isArray(FT.raw)?new vo(FT,ET,D,z):typeof FT==="string"&&!ET.length?new hy(F.transform.column.to?F.transform.column.to(FT):FT):new Mf(FT,ET)}function IT(FT,ET=[],xT={}){return arguments.length===2&&!Array.isArray(ET)&&(xT=ET,ET=[]),new vo([FT],ET,D,z,{prepare:!1,...xT,simple:"simple"in xT?xT.simple:ET.length===0})}function PT(FT,ET=[],xT={}){return arguments.length===2&&!Array.isArray(ET)&&(xT=ET,ET=[]),new vo([],ET,(VT)=>{SH.readFile(FT,"utf8",(To,KT)=>{if(To)return VT.reject(To);VT.strings=[KT],D(VT)})},z,{...xT,simple:"simple"in xT?xT.simple:ET.length===0})}}async function p(D,g,_T){let IT={fn:g,onlisten:_T},PT=p.sql||(p.sql=Gf({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(p.channels).forEach(([VT,{listeners:To}])=>{delete p.channels[VT],Promise.all(To.map((KT)=>p(VT,KT.fn,KT.onlisten).catch(()=>{})))})},onnotify(VT,To){VT in p.channels&&p.channels[VT].listeners.forEach((KT)=>KT.fn(To))}})),FT=p.channels||(p.channels={});if(D in FT){FT[D].listeners.push(IT);let VT=await FT[D].result;return IT.onlisten&&IT.onlisten(),{state:VT.state,unlisten:kT}}FT[D]={result:PT`listen ${PT.unsafe('"'+D.replace(/"/g,'""')+'"')}`,listeners:[IT]};let xT=await FT[D].result;return IT.onlisten&&IT.onlisten(),{state:xT.state,unlisten:kT};async function kT(){if(D in FT===!1)return;if(FT[D].listeners=FT[D].listeners.filter((VT)=>VT!==IT),FT[D].listeners.length)return;return delete FT[D],PT`unlisten ${PT.unsafe('"'+D.replace(/"/g,'""')+'"')}`}}async function v(D,g){return await E`select pg_notify(${D}, ${""+g})`}async function h(){let D=Io(),g=R.length?R.shift():await new Promise((PT)=>{S.push({reserve:PT}),_.length&&ZT(_.shift())});V(g,$),g.reserved=()=>D.length?g.execute(D.shift()):V(g,$),g.reserved.release=!0;let _T=B(IT);return _T.release=()=>{g.reserved=null,Xo(g)},_T;function IT(PT){g.queue===Y?D.push(PT):g.execute(PT)||V(g,Y)}}async function U(D,g){!g&&(g=D,D="");let _T=Io(),IT=0,PT,FT=null;try{return await E.unsafe("begin "+D.replace(/[^a-z ]/ig,""),[],{onexecute:xT}).execute(),await Promise.race([ET(PT,g),new Promise((kT,VT)=>PT.onclose=VT)])}catch(kT){throw kT}async function ET(kT,VT,To){let KT=B(mT);KT.savepoint=wF,KT.prepare=(DT)=>FT=DT.replace(/[^a-z0-9$-_. ]/gi);let Po,oo;To&&await KT`savepoint ${KT(To)}`;try{if(oo=await new Promise((DT,mo)=>{let ro=VT(KT);Promise.resolve(Array.isArray(ro)?Promise.all(ro):ro).then(DT,mo)}),Po)throw Po}catch(DT){throw await(To?KT`rollback to ${KT(To)}`:KT`rollback`),DT instanceof pA&&DT.code==="25P02"&&Po||DT}if(!To)FT?await KT`prepare transaction '${KT.unsafe(FT)}'`:await KT`commit`;return oo;function wF(DT,mo){if(DT&&Array.isArray(DT.raw))return wF((ro)=>ro.apply(ro,arguments));return arguments.length===1&&(mo=DT,DT=null),ET(kT,mo,"s"+IT+++(DT?"_"+DT:""))}function mT(DT){DT.catch((mo)=>Po||(Po=mo)),kT.queue===Y?_T.push(DT):kT.execute(DT)||V(kT,Y)}}function xT(kT){PT=kT,V(kT,$),kT.reserved=()=>_T.length?kT.execute(_T.shift()):V(kT,$)}}function V(D,g){return D.queue.remove(D),g.push(D),D.queue=g,g===R?D.idleTimer.start():D.idleTimer.cancel(),D}function I(D){return new FF(D,3802)}function L(D,g){if(!Array.isArray(D))return L(Array.from(arguments));return new FF(D,g||(D.length?Rf(D)||25:0),F.shared.typeArrayMap)}function m(D){if(y)return D.reject(qT.connection("CONNECTION_ENDED",F,F));if(R.length)return s(R.shift(),D);if(_.length)return ZT(_.shift(),D);O.length?s(O.shift(),D):S.push(D)}function s(D,g){return D.execute(g)?V(D,O):V(D,Y)}function z(D){return new Promise((g,_T)=>{D.state?D.active?A_(F).cancel(D.state,g,_T):D.cancelled={resolve:g,reject:_T}:(S.remove(D),D.cancelled=!0,D.reject(qT.generic("57014","canceling statement due to user request")),g())})}async function a({timeout:D=null}={}){if(y)return y;await 1;let g;return y=Promise.race([new Promise((_T)=>D!==null&&(g=setTimeout(e,D*1000,_T))),Promise.all(Q.map((_T)=>_T.end()).concat(p.sql?p.sql.end({timeout:0}):[],A.sql?A.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(g))}async function t(){await Promise.all(Q.map((D)=>D.end()))}async function e(D){await Promise.all(Q.map((g)=>g.terminate()));while(S.length)S.shift().reject(qT.connection("CONNECTION_DESTROYED",F));D()}function ZT(D,g){return V(D,f),D.connect(g),D}function vT(D){V(D,J)}function Xo(D){if(S.length===0)return V(D,R);let g=Math.ceil(S.length/(f.length+1)),_T=!0;while(_T&&S.length&&g-- >0){let IT=S.shift();if(IT.reserve)return IT.reserve(D);_T=D.execute(IT)}_T?V(D,O):V(D,Y)}function AF(D,g){V(D,_),D.reserved=null,D.onclose&&(D.onclose(g),D.onclose=null),F.onclose&&F.onclose(D.id),S.length&&ZT(D,S.shift())}}function fH(T,o){if(T&&T.shared)return T;let F=process.env,A=(!T||typeof T==="string"?o:T)||{},{url:y,multihost:S}=WH(T),f=[...y.searchParams].reduce((Y,[H,Q])=>(Y[H]=Q,Y),{}),$=A.hostname||A.host||S||y.hostname||F.PGHOST||"localhost",_=A.port||y.port||F.PGPORT||5432,J=A.user||A.username||y.username||F.PGUSERNAME||F.PGUSER||MH();A.no_prepare&&(A.prepare=!1),f.sslmode&&(f.ssl=f.sslmode,delete f.sslmode),"timeout"in A&&(console.log("The timeout option is deprecated, use idle_timeout instead"),A.idle_timeout=A.timeout),f.sslrootcert==="system"&&(f.ssl="verify-full");let R=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:_H,max_pipeline:100,backoff:JH,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray($)?$:$.split(",").map((Y)=>Y.split(":")[0]),port:Array.isArray(_)?_:$.split(",").map((Y)=>parseInt(Y.split(":")[1]||_)),path:A.path||$.indexOf("/")>-1&&$+"/.s.PGSQL."+_,database:A.database||A.db||(y.pathname||"").slice(1)||F.PGDATABASE||J,user:J,pass:A.pass||A.password||y.password||F.PGPASSWORD||"",...Object.entries(O).reduce((Y,[H,Q])=>{let E=H in A?A[H]:(H in f)?f[H]==="disable"||f[H]==="false"?!1:f[H]:F["PG"+H.toUpperCase()]||Q;return Y[H]=typeof E==="string"&&R.includes(H)?+E:E,Y},{}),connection:{application_name:"postgres.js",...A.connection,...Object.entries(f).reduce((Y,[H,Q])=>((H in O)||(Y[H]=Q),Y),{})},types:A.types||{},target_session_attrs:$H(A,y,F),onnotice:A.onnotice,onnotify:A.onnotify,onclose:A.onclose,onparameter:A.onparameter,socket:A.socket,transform:RH(A.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...d2(A.types)}}function $H(T,o,F){let A=T.target_session_attrs||o.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!A||["read-write","read-only","primary","standby","prefer-standby"].includes(A))return A;throw new Error("target_session_attrs "+A+" is not supported")}function JH(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function _H(){return 60*(30+Math.random()*30)}function RH(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function WH(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let o=T;o=o.slice(o.indexOf("://")+3).split(/[?/]/)[0],o=decodeURIComponent(o.slice(o.indexOf("@")+1));let F=new URL(T.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:o.indexOf(",")>-1&&o}}function MH(){try{return yH.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class pT{static[M]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,o){if(o==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(o===QT)return{...T[QT],selectedFields:new Proxy(T[QT].selectedFields,this)};if(typeof o==="symbol")return T[o];let A=(w(T,iT)?T._.selectedFields:w(T,Uo)?T[QT].selectedFields:T)[o];if(w(A,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!A.isSelectionField)return A.sql;let y=A.clone();return y.isSelectionField=!0,y}if(w(A,b)){if(this.config.sqlBehavior==="sql")return A;throw new Error(`You tried to reference "${o}" 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(w(A,GT)){if(this.config.alias)return new Proxy(A,new BA(new Proxy(A.table,new By(this.config.alias,this.config.replaceOriginalName??!1))));return A}if(typeof A!=="object"||A===null)return A;return new Proxy(A,new pT(this.config))}}class wf extends Wo{constructor(T,o,F,A){super();this.session=o,this.dialect=F,this.config={table:T,withList:A}}static[M]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[x.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=bo(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function OH(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function XH(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,A,y)=>{let S=y===0?A.toLowerCase():`${A[0].toUpperCase()}${A.slice(1)}`;return F+S},"")}function YH(T){return T}class f_{static[M]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?OH:T==="camelCase"?XH:YH}getColumnCasing(T){if(!T.keyAsName)return T.name;let o=T.table[x.Symbol.Schema]??"public",F=T.table[x.Symbol.OriginalName],A=`${o}.${F}.${T.name}`;if(!this.cache[A])this.cacheTable(T.table);return this.cache[A]}cacheTable(T){let o=T[x.Symbol.Schema]??"public",F=T[x.Symbol.OriginalName],A=`${o}.${F}`;if(!this.cachedTables[A]){for(let y of Object.values(T[x.Symbol.Columns])){let S=`${A}.${y.name}`;this.cache[S]=this.convert(y.name)}this.cachedTables[A]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ny extends Uo{static[M]="PgViewBase"}class TA{static[M]="PgDialect";casing;constructor(T){this.casing=new f_(T?.casing)}async migrate(T,o,F){let A=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",y=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",S=X`
82
- CREATE TABLE IF NOT EXISTS ${X.identifier(y)}.${X.identifier(A)} (
70
+ `};return W(A),new Promise(async(M)=>Y=M);async function X({highWaterMark:M=16384,start:E=0,end:K=1/0}={}){let j=K-E;return E&&await A.seek(E),new BA.Readable({highWaterMark:M,async read(S){let P=S>j?S-j:S;j-=S;let[{data:f}]=await A.read(P);if(this.push(f),f.length<S)this.push(null)}})}async function O({highWaterMark:M=16384,start:E=0}={}){return E&&await A.seek(E),new BA.Writable({highWaterMark:M,write(K,j,S){A.write(K).then(()=>S(),S)}})}}).catch(J)})}Object.assign(P1,{PostgresError:$_,toPascal:NF,pascal:r4,toCamel:IF,camel:n4,toKebab:CF,kebab:s4,fromPascal:AW,fromCamel:XW,fromKebab:GW,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var Z_=P1;function P1(T,F){let _=NH(T,F),W=_.no_subscribe||_J(P1,{..._}),J=!1,$=z0(),Y=z0(),Z=z0(),A=z0(),X=z0(),O=z0(),M=z0(),E=z0(),K={connecting:Y,reserved:Z,closed:A,ended:X,open:O,busy:M,full:E},j=[...Array(_.max)].map(()=>FJ(_,K,{onopen:S0,onend:G0,onclose:qF})),S=P(ST);return Object.assign(S,{get parameters(){return _.parameters},largeObject:WJ.bind(null,S),subscribe:W,CLOSE:J_,END:J_,PostgresError:$_,options:_,reserve:h,listen:f,begin:TT,close:l,end:$T}),S;function P(V){return V.debug=_.debug,Object.entries(_.types).reduce((n,[GT,IT])=>{return n[GT]=(KT)=>new o0(KT,IT.to),n},p),Object.assign(WT,{types:p,typed:p,unsafe:wT,notify:y,array:d,json:g,file:kT}),WT;function p(n,GT){return new o0(n,GT)}function WT(n,...GT){return n&&Array.isArray(n.raw)?new L0(n,GT,V,D):typeof n==="string"&&!GT.length?new HW(_.transform.column.to?_.transform.column.to(n):n):new k1(n,GT)}function wT(n,GT=[],IT={}){return arguments.length===2&&!Array.isArray(GT)&&(IT=GT,GT=[]),new L0([n],GT,V,D,{prepare:!1,...IT,simple:"simple"in IT?IT.simple:GT.length===0})}function kT(n,GT=[],IT={}){return arguments.length===2&&!Array.isArray(GT)&&(IT=GT,GT=[]),new L0([],GT,(QT)=>{IH.readFile(n,"utf8",(pT,HT)=>{if(pT)return QT.reject(pT);QT.strings=[HT],V(QT)})},D,{...IT,simple:"simple"in IT?IT.simple:GT.length===0})}}async function f(V,p,WT){let wT={fn:p,onlisten:WT},kT=f.sql||(f.sql=P1({..._,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(f.channels).forEach(([QT,{listeners:pT}])=>{delete f.channels[QT],Promise.all(pT.map((HT)=>f(QT,HT.fn,HT.onlisten).catch(()=>{})))})},onnotify(QT,pT){QT in f.channels&&f.channels[QT].listeners.forEach((HT)=>HT.fn(pT))}})),n=f.channels||(f.channels={});if(V in n){n[V].listeners.push(wT);let QT=await n[V].result;return wT.onlisten&&wT.onlisten(),{state:QT.state,unlisten:KT}}n[V]={result:kT`listen ${kT.unsafe('"'+V.replace(/"/g,'""')+'"')}`,listeners:[wT]};let IT=await n[V].result;return wT.onlisten&&wT.onlisten(),{state:IT.state,unlisten:KT};async function KT(){if(V in n===!1)return;if(n[V].listeners=n[V].listeners.filter((QT)=>QT!==wT),n[V].listeners.length)return;return delete n[V],kT`unlisten ${kT.unsafe('"'+V.replace(/"/g,'""')+'"')}`}}async function y(V,p){return await S`select pg_notify(${V}, ${""+p})`}async function h(){let V=z0(),p=O.length?O.shift():await new Promise((kT)=>{$.push({reserve:kT}),A.length&&xT(A.shift())});u(p,Z),p.reserved=()=>V.length?p.execute(V.shift()):u(p,Z),p.reserved.release=!0;let WT=P(wT);return WT.release=()=>{p.reserved=null,S0(p)},WT;function wT(kT){p.queue===E?V.push(kT):p.execute(kT)||u(p,E)}}async function TT(V,p){!p&&(p=V,V="");let WT=z0(),wT=0,kT,n=null;try{return await S.unsafe("begin "+V.replace(/[^a-z ]/ig,""),[],{onexecute:IT}).execute(),await Promise.race([GT(kT,p),new Promise((KT,QT)=>kT.onclose=QT)])}catch(KT){throw KT}async function GT(KT,QT,pT){let HT=P(BT);HT.savepoint=TF,HT.prepare=(zT)=>n=zT.replace(/[^a-z0-9$-_. ]/gi);let I0,gT;pT&&await HT`savepoint ${HT(pT)}`;try{if(gT=await new Promise((zT,N0)=>{let P0=QT(HT);Promise.resolve(Array.isArray(P0)?Promise.all(P0):P0).then(zT,N0)}),I0)throw I0}catch(zT){throw await(pT?HT`rollback to ${HT(pT)}`:HT`rollback`),zT instanceof $_&&zT.code==="25P02"&&I0||zT}if(!pT)n?await HT`prepare transaction '${HT.unsafe(n)}'`:await HT`commit`;return gT;function TF(zT,N0){if(zT&&Array.isArray(zT.raw))return TF((P0)=>P0.apply(P0,arguments));return arguments.length===1&&(N0=zT,zT=null),GT(KT,N0,"s"+wT+++(zT?"_"+zT:""))}function BT(zT){zT.catch((N0)=>I0||(I0=N0)),KT.queue===E?WT.push(zT):KT.execute(zT)||u(KT,E)}}function IT(KT){kT=KT,u(KT,Z),KT.reserved=()=>WT.length?KT.execute(WT.shift()):u(KT,Z)}}function u(V,p){return V.queue.remove(V),p.push(V),V.queue=p,p===O?V.idleTimer.start():V.idleTimer.cancel(),V}function g(V){return new o0(V,3802)}function d(V,p){if(!Array.isArray(V))return d(Array.from(arguments));return new o0(V,p||(V.length?N1(V)||25:0),_.shared.typeArrayMap)}function ST(V){if(J)return V.reject(CT.connection("CONNECTION_ENDED",_,_));if(O.length)return A0(O.shift(),V);if(A.length)return xT(A.shift(),V);M.length?A0(M.shift(),V):$.push(V)}function A0(V,p){return V.execute(p)?u(V,M):u(V,E)}function D(V){return new Promise((p,WT)=>{V.state?V.active?FJ(_).cancel(V.state,p,WT):V.cancelled={resolve:p,reject:WT}:($.remove(V),V.cancelled=!0,V.reject(CT.generic("57014","canceling statement due to user request")),p())})}async function $T({timeout:V=null}={}){if(J)return J;await 1;let p;return J=Promise.race([new Promise((WT)=>V!==null&&(p=setTimeout(e,V*1000,WT))),Promise.all(j.map((WT)=>WT.end()).concat(f.sql?f.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function l(){await Promise.all(j.map((V)=>V.end()))}async function e(V){await Promise.all(j.map((p)=>p.terminate()));while($.length)$.shift().reject(CT.connection("CONNECTION_DESTROYED",_));V()}function xT(V,p){return u(V,Y),V.connect(p),V}function G0(V){u(V,X)}function S0(V){if($.length===0)return u(V,O);let p=Math.ceil($.length/(Y.length+1)),WT=!0;while(WT&&$.length&&p-- >0){let wT=$.shift();if(wT.reserve)return wT.reserve(V);WT=V.execute(wT)}WT?u(V,M):u(V,E)}function qF(V,p){u(V,A),V.reserved=null,V.onclose&&(V.onclose(p),V.onclose=null),_.onclose&&_.onclose(V.id),$.length&&xT(V,$.shift())}}function NH(T,F){if(T&&T.shared)return T;let _=process.env,W=(!T||typeof T==="string"?F:T)||{},{url:J,multihost:$}=qH(T),Y=[...J.searchParams].reduce((E,[K,j])=>(E[K]=j,E),{}),Z=W.hostname||W.host||$||J.hostname||_.PGHOST||"localhost",A=W.port||J.port||_.PGPORT||5432,X=W.user||W.username||J.username||_.PGUSERNAME||_.PGUSER||jH();W.no_prepare&&(W.prepare=!1),Y.sslmode&&(Y.ssl=Y.sslmode,delete Y.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),Y.sslrootcert==="system"&&(Y.ssl="verify-full");let O=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:BH,max_pipeline:100,backoff:kH,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Z)?Z:Z.split(",").map((E)=>E.split(":")[0]),port:Array.isArray(A)?A:Z.split(",").map((E)=>parseInt(E.split(":")[1]||A)),path:W.path||Z.indexOf("/")>-1&&Z+"/.s.PGSQL."+A,database:W.database||W.db||(J.pathname||"").slice(1)||_.PGDATABASE||X,user:X,pass:W.pass||W.password||J.password||_.PGPASSWORD||"",...Object.entries(M).reduce((E,[K,j])=>{let S=K in W?W[K]:(K in Y)?Y[K]==="disable"||Y[K]==="false"?!1:Y[K]:_["PG"+K.toUpperCase()]||j;return E[K]=typeof S==="string"&&O.includes(K)?+S:S,E},{}),connection:{application_name:"postgres.js",...W.connection,...Object.entries(Y).reduce((E,[K,j])=>((K in M)||(E[K]=j),E),{})},types:W.types||{},target_session_attrs:CH(W,J,_),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:fH(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...RA(W.types)}}function CH(T,F,_){let W=T.target_session_attrs||F.searchParams.get("target_session_attrs")||_.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function kH(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function BH(){return 60*(30+Math.random()*30)}function fH(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function qH(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let F=T;F=F.slice(F.indexOf("://")+3).split(/[?/]/)[0],F=decodeURIComponent(F.slice(F.indexOf("@")+1));let _=new URL(T.replace(F,F.split(",")[0]));return{url:{username:decodeURIComponent(_.username),password:decodeURIComponent(_.password),host:_.host,hostname:_.hostname,port:_.port,pathname:_.pathname,searchParams:_.searchParams},multihost:F.indexOf(",")>-1&&F}}function jH(){try{return SH.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class LT{static[H]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,F){if(F==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(F===MT)return{...T[MT],selectedFields:new Proxy(T[MT].selectedFields,this)};if(typeof F==="symbol")return T[F];let W=(R(T,yT)?T._.selectedFields:R(T,Y0)?T[MT].selectedFields:T)[F];if(R(W,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let J=W.clone();return J.isSelectionField=!0,J}if(R(W,k)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${F}" 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(R(W,XT)){if(this.config.alias)return new Proxy(W,new W_(new Proxy(W.table,new TW(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new LT(this.config))}}class v1 extends rT{constructor(T,F,_,W){super();this.session=F,this.dialect=_,this.config={table:T,withList:W}}static[H]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[C.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=V0(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...F}=this.dialect.sqlToQuery(this.getSQL());return F}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new LT({alias:vT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function yH(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((_)=>_.toLowerCase()).join("_")}function PH(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((_,W,J)=>{let $=J===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return _+$},"")}function vH(T){return T}class JJ{static[H]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?yH:T==="camelCase"?PH:vH}getColumnCasing(T){if(!T.keyAsName)return T.name;let F=T.table[C.Symbol.Schema]??"public",_=T.table[C.Symbol.OriginalName],W=`${F}.${_}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let F=T[C.Symbol.Schema]??"public",_=T[C.Symbol.OriginalName],W=`${F}.${_}`;if(!this.cachedTables[W]){for(let J of Object.values(T[C.Symbol.Columns])){let $=`${W}.${J.name}`;this.cache[$]=this.convert(J.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class UW extends Y0{static[H]="PgViewBase"}class BF{static[H]="PgDialect";casing;constructor(T){this.casing=new JJ(T?.casing)}async migrate(T,F,_){let W=typeof _==="string"?"__drizzle_migrations":_.migrationsTable??"__drizzle_migrations",J=typeof _==="string"?"drizzle":_.migrationsSchema??"drizzle",$=U`
71
+ CREATE TABLE IF NOT EXISTS ${U.identifier(J)}.${U.identifier(W)} (
83
72
  id SERIAL PRIMARY KEY,
84
73
  hash text NOT NULL,
85
74
  created_at bigint
86
75
  )
87
- `;await o.execute(X`CREATE SCHEMA IF NOT EXISTS ${X.identifier(y)}`),await o.execute(S);let $=(await o.all(X`select id, hash, created_at from ${X.identifier(y)}.${X.identifier(A)} order by created_at desc limit 1`))[0];await o.transaction(async(_)=>{for await(let J of T)if(!$||Number($.created_at)<J.folderMillis){for(let R of J.sql)await _.execute(X.raw(R));await _.execute(X`insert into ${X.identifier(y)}.${X.identifier(A)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let o=[X`with `];for(let[F,A]of T.entries())if(o.push(X`${X.identifier(A._.alias)} as (${A._.sql})`),F<T.length-1)o.push(X`, `);return o.push(X` `),X.join(o)}buildDeleteQuery({table:T,where:o,returning:F,withList:A}){let y=this.buildWithCTE(A),S=F?X` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,f=o?X` where ${o}`:void 0;return X`${y}delete from ${T}${f}${S}`}buildUpdateSet(T,o){let F=T[x.Symbol.Columns],A=Object.keys(F).filter((S)=>o[S]!==void 0||F[S]?.onUpdateFn!==void 0),y=A.length;return X.join(A.flatMap((S,f)=>{let $=F[S],_=o[S]??X.param($.onUpdateFn(),$),J=X`${X.identifier(this.casing.getColumnCasing($))} = ${_}`;if(f<y-1)return[J,X.raw(", ")];return[J]}))}buildUpdateQuery({table:T,set:o,where:F,returning:A,withList:y,from:S,joins:f}){let $=this.buildWithCTE(y),_=T[eT.Symbol.Name],J=T[eT.Symbol.Schema],R=T[eT.Symbol.OriginalName],O=_===R?void 0:_,Y=X`${J?X`${X.identifier(J)}.`:void 0}${X.identifier(R)}${O&&X` ${X.identifier(O)}`}`,H=this.buildUpdateSet(T,o),Q=S&&X.join([X.raw(" from "),this.buildFromTable(S)]),E=this.buildJoins(f),B=A?X` returning ${this.buildSelection(A,{isSingleTable:!S})}`:void 0,p=F?X` where ${F}`:void 0;return X`${$}update ${Y} set ${H}${Q}${E}${p}${B}`}buildSelection(T,{isSingleTable:o=!1}={}){let F=T.length,A=T.flatMap(({field:y},S)=>{let f=[];if(w(y,b.Aliased)&&y.isSelectionField)f.push(X.identifier(y.fieldAlias));else if(w(y,b.Aliased)||w(y,b)){let $=w(y,b.Aliased)?y.sql:y;if(o)f.push(new b($.queryChunks.map((_)=>{if(w(_,C))return X.identifier(this.casing.getColumnCasing(_));return _})));else f.push($);if(w(y,b.Aliased))f.push(X` as ${X.identifier(y.fieldAlias)}`)}else if(w(y,GT))if(o)f.push(X.identifier(this.casing.getColumnCasing(y)));else f.push(y);if(S<F-1)f.push(X`, `);return f});return X.join(A)}buildJoins(T){if(!T||T.length===0)return;let o=[];for(let[F,A]of T.entries()){if(F===0)o.push(X` `);let y=A.table,S=A.lateral?X` lateral`:void 0,f=A.on?X` on ${A.on}`:void 0;if(w(y,eT)){let $=y[eT.Symbol.Name],_=y[eT.Symbol.Schema],J=y[eT.Symbol.OriginalName],R=$===J?void 0:A.alias;o.push(X`${X.raw(A.joinType)} join${S} ${_?X`${X.identifier(_)}.`:void 0}${X.identifier(J)}${R&&X` ${X.identifier(R)}`}${f}`)}else if(w(y,Uo)){let $=y[QT].name,_=y[QT].schema,J=y[QT].originalName,R=$===J?void 0:A.alias;o.push(X`${X.raw(A.joinType)} join${S} ${_?X`${X.identifier(_)}.`:void 0}${X.identifier(J)}${R&&X` ${X.identifier(R)}`}${f}`)}else o.push(X`${X.raw(A.joinType)} join${S} ${y}${f}`);if(F<T.length-1)o.push(X` `)}return X.join(o)}buildFromTable(T){if(w(T,x)&&T[x.Symbol.IsAlias]){let o=X`${X.identifier(T[x.Symbol.OriginalName])}`;if(T[x.Symbol.Schema])o=X`${X.identifier(T[x.Symbol.Schema])}.${o}`;return X`${o} ${X.identifier(T[x.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:o,fieldsFlat:F,where:A,having:y,table:S,joins:f,orderBy:$,groupBy:_,limit:J,offset:R,lockingClause:O,distinct:Y,setOperators:H}){let Q=F??bo(o);for(let e of Q)if(w(e.field,GT)&&lT(e.field.table)!==(w(S,iT)?S._.alias:w(S,ny)?S[QT].name:w(S,b)?void 0:lT(S))&&!((ZT)=>f?.some(({alias:vT})=>vT===(ZT[x.Symbol.IsAlias]?lT(ZT):ZT[x.Symbol.BaseName])))(e.field.table)){let ZT=lT(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${ZT}"."${e.field.name}", but the table "${ZT}" is not part of the query! Did you forget to join it?`)}let E=!f||f.length===0,B=this.buildWithCTE(T),p;if(Y)p=Y===!0?X` distinct`:X` distinct on (${X.join(Y.on,X`, `)})`;let v=this.buildSelection(Q,{isSingleTable:E}),h=this.buildFromTable(S),U=this.buildJoins(f),V=A?X` where ${A}`:void 0,I=y?X` having ${y}`:void 0,L;if($&&$.length>0)L=X` order by ${X.join($,X`, `)}`;let m;if(_&&_.length>0)m=X` group by ${X.join(_,X`, `)}`;let s=typeof J==="object"||typeof J==="number"&&J>=0?X` limit ${J}`:void 0,z=R?X` offset ${R}`:void 0,a=X.empty();if(O){let e=X` for ${X.raw(O.strength)}`;if(O.config.of)e.append(X` of ${X.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],X`, `)}`);if(O.config.noWait)e.append(X` nowait`);else if(O.config.skipLocked)e.append(X` skip locked`);a.append(e)}let t=X`${B}select${p} ${v} from ${h}${U}${V}${m}${I}${L}${s}${z}${a}`;if(H.length>0)return this.buildSetOperations(t,H);return t}buildSetOperations(T,o){let[F,...A]=o;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(A.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),A)}buildSetOperationQuery({leftSelect:T,setOperator:{type:o,isAll:F,rightSelect:A,limit:y,orderBy:S,offset:f}}){let $=X`(${T.getSQL()}) `,_=X`(${A.getSQL()})`,J;if(S&&S.length>0){let H=[];for(let Q of S)if(w(Q,C))H.push(X.identifier(Q.name));else if(w(Q,b)){for(let E=0;E<Q.queryChunks.length;E++){let B=Q.queryChunks[E];if(w(B,C))Q.queryChunks[E]=X.identifier(B.name)}H.push(X`${Q}`)}else H.push(X`${Q}`);J=X` order by ${X.join(H,X`, `)} `}let R=typeof y==="object"||typeof y==="number"&&y>=0?X` limit ${y}`:void 0,O=X.raw(`${o} ${F?"all ":""}`),Y=f?X` offset ${f}`:void 0;return X`${$}${O}${_}${J}${R}${Y}`}buildInsertQuery({table:T,values:o,onConflict:F,returning:A,withList:y,select:S,overridingSystemValue_:f}){let $=[],_=T[x.Symbol.Columns],J=Object.entries(_).filter(([B,p])=>!p.shouldDisableInsert()),R=J.map(([,B])=>X.identifier(this.casing.getColumnCasing(B)));if(S){let B=o;if(w(B,b))$.push(B);else $.push(B.getSQL())}else{let B=o;$.push(X.raw("values "));for(let[p,v]of B.entries()){let h=[];for(let[U,V]of J){let I=v[U];if(I===void 0||w(I,Co)&&I.value===void 0)if(V.defaultFn!==void 0){let L=V.defaultFn(),m=w(L,b)?L:X.param(L,V);h.push(m)}else if(!V.default&&V.onUpdateFn!==void 0){let L=V.onUpdateFn(),m=w(L,b)?L:X.param(L,V);h.push(m)}else h.push(X`default`);else h.push(I)}if($.push(h),p<B.length-1)$.push(X`, `)}}let O=this.buildWithCTE(y),Y=X.join($),H=A?X` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,Q=F?X` on conflict ${F}`:void 0,E=f===!0?X`overriding system value `:void 0;return X`${O}insert into ${T} ${R} ${E}${Y}${Q}${H}`}buildRefreshMaterializedViewQuery({view:T,concurrently:o,withNoData:F}){let A=o?X` concurrently`:void 0,y=F?X` with no data`:void 0;return X`refresh materialized view${A} ${T}${y}`}prepareTyping(T){if(w(T,Tf)||w(T,eS))return"json";else if(w(T,of))return"decimal";else if(w(T,Ff))return"time";else if(w(T,Af)||w(T,yf))return"timestamp";else if(w(T,sS)||w(T,aS))return"date";else if(w(T,Sf))return"uuid";else return"none"}sqlToQuery(T,o){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:o})}buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:F,table:A,tableConfig:y,queryConfig:S,tableAlias:f,nestedQueryRelation:$,joinOn:_}){let J=[],R,O,Y=[],H,Q=[];if(S===!0)J=Object.entries(y.columns).map(([p,v])=>({dbKey:v.name,tsKey:p,field:oF(v,f),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let B=Object.fromEntries(Object.entries(y.columns).map(([I,L])=>[I,oF(L,f)]));if(S.where){let I=typeof S.where==="function"?S.where(B,x2()):S.where;H=I&&Ny(I,f)}let p=[],v=[];if(S.columns){let I=!1;for(let[L,m]of Object.entries(S.columns)){if(m===void 0)continue;if(L in y.columns){if(!I&&m===!0)I=!0;v.push(L)}}if(v.length>0)v=I?v.filter((L)=>S.columns?.[L]===!0):Object.keys(y.columns).filter((L)=>!v.includes(L))}else v=Object.keys(y.columns);for(let I of v){let L=y.columns[I];p.push({tsKey:I,value:L})}let h=[];if(S.with)h=Object.entries(S.with).filter((I)=>!!I[1]).map(([I,L])=>({tsKey:I,queryConfig:L,relation:y.relations[I]}));let U;if(S.extras){U=typeof S.extras==="function"?S.extras(B,{sql:X}):S.extras;for(let[I,L]of Object.entries(U))p.push({tsKey:I,value:xJ(L,f)})}for(let{tsKey:I,value:L}of p)J.push({dbKey:w(L,b.Aliased)?L.fieldAlias:y.columns[I].name,tsKey:I,field:w(L,GT)?oF(L,f):L,relationTableTsKey:void 0,isJson:!1,selection:[]});let V=typeof S.orderBy==="function"?S.orderBy(B,b2()):S.orderBy??[];if(!Array.isArray(V))V=[V];Y=V.map((I)=>{if(w(I,GT))return oF(I,f);return Ny(I,f)}),R=S.limit,O=S.offset;for(let{tsKey:I,queryConfig:L,relation:m}of h){let s=v2(o,F,m),z=rF(m.referencedTable),a=F[z],t=`${f}_${I}`,e=qy(...s.fields.map((Xo,AF)=>ff(oF(s.references[AF],t),oF(Xo,f)))),ZT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:F,table:T[a],tableConfig:o[a],queryConfig:w(m,xF)?L===!0?{limit:1}:{...L,limit:1}:L,tableAlias:t,joinOn:e,nestedQueryRelation:m}),vT=X`${X.identifier(t)}.${X.identifier("data")}`.as(I);Q.push({on:X`true`,table:new iT(ZT.sql,{},t),alias:t,joinType:"left",lateral:!0}),J.push({dbKey:I,tsKey:I,field:vT,relationTableTsKey:a,isJson:!0,selection:ZT.selection})}}if(J.length===0)throw new rS({message:`No fields selected for table "${y.tsName}" ("${f}")`});let E;if(H=qy(_,H),$){let B=X`json_build_array(${X.join(J.map(({field:h,tsKey:U,isJson:V})=>V?X`${X.identifier(`${f}_${U}`)}.${X.identifier("data")}`:w(h,b.Aliased)?h.sql:h),X`, `)})`;if(w($,vy))B=X`coalesce(json_agg(${B}${Y.length>0?X` order by ${X.join(Y,X`, `)}`:void 0}), '[]'::json)`;let p=[{dbKey:"data",tsKey:"data",field:B.as("data"),isJson:!0,relationTableTsKey:y.tsName,selection:J}];if(R!==void 0||O!==void 0||Y.length>0)E=this.buildSelectQuery({table:dS(A,f),fields:{},fieldsFlat:[{path:[],field:X.raw("*")}],where:H,limit:R,offset:O,orderBy:Y,setOperators:[]}),H=void 0,R=void 0,O=void 0,Y=[];else E=dS(A,f);E=this.buildSelectQuery({table:w(E,eT)?E:new iT(E,{},f),fields:{},fieldsFlat:p.map(({field:h})=>({path:[],field:w(h,GT)?oF(h,f):h})),joins:Q,where:H,limit:R,offset:O,orderBy:Y,setOperators:[]})}else E=this.buildSelectQuery({table:dS(A,f),fields:{},fieldsFlat:J.map(({field:B})=>({path:[],field:w(B,GT)?oF(B,f):B})),joins:Q,where:H,limit:R,offset:O,orderBy:Y,setOperators:[]});return{tableTsKey:y.tsName,sql:E,selection:J}}}class $_{static[M]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Oo{static[M]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let o=!!this.fields,F=T,A;if(this.fields)A=this.fields;else if(w(F,iT))A=Object.fromEntries(Object.keys(F._.selectedFields).map((y)=>[y,F[y]]));else if(w(F,ny))A=F[QT].selectedFields;else if(w(F,b))A={};else A=XM(F);return new J_({table:F,fields:A,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class f4 extends $_{static[M]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:o,isPartialSelect:F,session:A,dialect:y,withList:S,distinct:f}){super();this.config={withList:S,table:T,fields:{...o},distinct:f,setOperators:[]},this.isPartialSelect=F,this.session=A,this.dialect=y,this._={selectedFields:o},this.tableName=HF(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T,o){return(F,A)=>{let y=this.tableName,S=HF(F);if(typeof S==="string"&&this.config.joins?.some((f)=>f.alias===S))throw new Error(`Alias "${S}" 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 S==="string"&&!w(F,b)){let f=w(F,iT)?F._.selectedFields:w(F,Uo)?F[QT].selectedFields:F[x.Symbol.Columns];this.config.fields[S]=f}}if(typeof A==="function")A=A(new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:A,table:F,joinType:T,alias:S,lateral:o}),typeof S==="string")switch(T){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!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,o){return(F)=>{let A=typeof F==="function"?F(ZH()):F;if(!py(this.getSelectedFields(),A.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:o,rightSelect:A}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(o)?o:[o]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}else{let o=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,o={}){return this.config.lockingClause={strength:T,config:o},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}as(T){return new Proxy(new iT(this.getSQL(),this.config.fields,T),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new pT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class J_ extends f4{static[M]="PgSelect";_prepare(T){let{session:o,config:F,dialect:A,joinsNotNullableMap:y,authToken:S}=this;if(!o)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return wT.startActiveSpan("drizzle.prepareQuery",()=>{let f=bo(F.fields),$=o.prepareQuery(A.sqlToQuery(this.getSQL()),f,T,!0);return $.joinsNotNullableMap=y,$.setToken(S)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}OM(J_,[Wo]);function bA(T,o){return(F,A,...y)=>{let S=[A,...y].map((f)=>({type:T,isAll:o,rightSelect:f}));for(let f of S)if(!py(F.getSelectedFields(),f.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(S)}}var ZH=()=>({union:HH,unionAll:GH,intersect:wH,intersectAll:EH,except:KH,exceptAll:UH}),HH=bA("union",!1),GH=bA("union",!0),wH=bA("intersect",!1),EH=bA("intersect",!0),KH=bA("except",!1),UH=bA("except",!0);class uy{static[M]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=w(T,TA)?T:void 0,this.dialectConfig=w(T,TA)?void 0:T}$with=(T,o)=>{let F=this;return{as:(y)=>{if(typeof y==="function")y=y(F);return new Proxy(new Iy(y.getSQL(),o??("getSelectedFields"in y?y.getSelectedFields()??{}:{}),T,!0),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let o=this;function F(S){return new Oo({fields:S??void 0,session:void 0,dialect:o.getDialect(),withList:T})}function A(S){return new Oo({fields:S??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function y(S,f){return new Oo({fields:f??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:S}})}return{select:F,selectDistinct:A,selectDistinctOn:y}}select(T){return new Oo({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new Oo({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,o){return new Oo({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new TA(this.dialectConfig);return this.dialect}}class Ef{constructor(T,o,F,A,y){this.table=T,this.session=o,this.dialect=F,this.withList=A,this.overridingSystemValue_=y}static[M]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let o=T.map((F)=>{let A={},y=this.table[x.Symbol.Columns];for(let S of Object.keys(F)){let f=F[S];A[S]=w(f,b)?f:new Co(f,y[S])}return A});return new __(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let o=typeof T==="function"?T(new uy):T;if(!w(o,b)&&!py(this.table[cS],o._.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 __(this.table,o,this.session,this.dialect,this.withList,!0)}}class __ extends Wo{constructor(T,o,F,A,y,S,f){super();this.session=F,this.dialect=A,this.config={table:T,values:o,withList:y,select:S,overridingSystemValue_:f}}static[M]="PgInsert";config;returning(T=this.config.table[x.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=bo(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=X`do nothing`;else{let o="";o=Array.isArray(T.target)?T.target.map((A)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(A))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?X` where ${T.where}`:void 0;this.config.onConflict=X`(${X.raw(o)})${F} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let o=T.where?X` where ${T.where}`:void 0,F=T.targetWhere?X` where ${T.targetWhere}`:void 0,A=T.setWhere?X` where ${T.setWhere}`:void 0,y=this.dialect.buildUpdateSet(this.config.table,lS(this.config.table,T.set)),S="";return S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=X`(${X.raw(S)})${F} do update set ${y}${o}${A}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class R_ extends Wo{constructor(T,o,F){super();this.session=o,this.dialect=F,this.config={view:T}}static[M]="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,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class Kf{constructor(T,o,F,A){this.table=T,this.session=o,this.dialect=F,this.withList=A}static[M]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new $4(this.table,lS(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class $4 extends Wo{constructor(T,o,F,A,y){super();this.session=F,this.dialect=A,this.config={set:o,table:T,withList:y,joins:[]},this.tableName=HF(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[M]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let o=T,F=HF(o);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=o,this}getTableLikeFields(T){if(w(T,eT))return T[x.Symbol.Columns];else if(w(T,iT))return T._.selectedFields;return T[QT].selectedFields}createJoin(T){return(o,F)=>{let A=HF(o);if(typeof A==="string"&&this.config.joins.some((y)=>y.alias===A))throw new Error(`Alias "${A}" is already used in this query`);if(typeof F==="function"){let y=this.config.from&&!w(this.config.from,b)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[x.Symbol.Columns],new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),y&&new Proxy(y,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:o,joinType:T,alias:A}),typeof A==="string")switch(T){case"left":{this.joinsNotNullableMap[A]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([y])=>[y,!1])),this.joinsNotNullableMap[A]=!0;break}case"inner":{this.joinsNotNullableMap[A]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([y])=>[y,!1])),this.joinsNotNullableMap[A]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[x.Symbol.Columns]),this.config.from){let o=HF(this.config.from);if(typeof o==="string"&&this.config.from&&!w(this.config.from,b)){let F=this.getTableLikeFields(this.config.from);T[o]=F}for(let F of this.config.joins){let A=HF(F.table);if(typeof A==="string"&&!w(F.table,b)){let y=this.getTableLikeFields(F.table);T[A]=y}}}}return this.config.returningFields=T,this.config.returning=bo(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){let o=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return o.joinsNotNullableMap=this.joinsNotNullableMap,o}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class cy extends b{constructor(T){super(cy.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=cy.buildCount(T.source,T.filters)}sql;token;static[M]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,o){return X`(select count(*) from ${T}${X.raw(" where ").if(o)}${o})`}static buildCount(T,o){return X`select count(*) as count from ${T}${X.raw(" where ").if(o)}${o};`}setToken(T){return this.token=T,this}then(T,o){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,o)}catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}}class M_{constructor(T,o,F,A,y,S,f){this.fullSchema=T,this.schema=o,this.tableNamesMap=F,this.table=A,this.tableConfig=y,this.dialect=S,this.session=f}static[M]="PgRelationalQueryBuilder";findMany(T){return new W_(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new W_(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class W_ extends Wo{constructor(T,o,F,A,y,S,f,$,_){super();this.fullSchema=T,this.schema=o,this.tableNamesMap=F,this.table=A,this.tableConfig=y,this.dialect=S,this.session=f,this.config=$,this.mode=_}static[M]="PgRelationalQuery";_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(A,y)=>{let S=A.map((f)=>$f(this.schema,this.tableConfig,f,o.selection,y));if(this.mode==="first")return S[0];return S})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),o=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:o}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class O_ extends Wo{constructor(T,o,F,A){super();this.execute=T,this.sql=o,this.query=F,this.mapBatchResult=A}static[M]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,o){return o?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class iy{constructor(T,o,F){if(this.dialect=T,this.session=o,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[A,y]of Object.entries(this._.schema))this.query[A]=new M_(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[A],y,T,o)}static[M]="PgDatabase";query;$with=(T,o)=>{let F=this;return{as:(y)=>{if(typeof y==="function")y=y(new uy(F.dialect));return new Proxy(new Iy(y.getSQL(),o??("getSelectedFields"in y?y.getSelectedFields()??{}:{}),T,!0),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,o){return new cy({source:T,filters:o,session:this.session})}with(...T){let o=this;function F(_){return new Oo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T})}function A(_){return new Oo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:!0})}function y(_,J){return new Oo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:{on:_}})}function S(_){return new Kf(_,o.session,o.dialect,T)}function f(_){return new Ef(_,o.session,o.dialect,T)}function $(_){return new wf(_,o.session,o.dialect,T)}return{select:F,selectDistinct:A,selectDistinctOn:y,update:S,insert:f,delete:$}}select(T){return new Oo({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new Oo({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,o){return new Oo({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new Kf(T,this.session,this.dialect)}insert(T){return new Ef(T,this.session,this.dialect)}delete(T){return new wf(T,this.session,this.dialect)}refreshMaterializedView(T){return new R_(T,this.session,this.dialect)}authToken;execute(T){let o=typeof T==="string"?X.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(o),A=this.session.prepareQuery(F,void 0,void 0,!1);return new O_(()=>A.execute(void 0,this.authToken),o,F,(y)=>A.mapResult(y,!0))}transaction(T,o){return this.session.transaction(T,o)}}class J4{constructor(T,o){this.unique=T,this.name=o}static[M]="PgIndexBuilderOn";on(...T){return new Uf(T.map((o)=>{if(w(o,b))return o;o=o;let F=new Ly(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new Uf(T.map((o)=>{if(w(o,b))return o;o=o;let F=new Ly(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,F}),this.unique,!0,this.name)}using(T,...o){return new Uf(o.map((F)=>{if(w(F,b))return F;F=F;let A=new Ly(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),A}),this.unique,!0,this.name,T)}}class Uf{static[M]="PgIndexBuilder";config;constructor(T,o,F,A,y="btree"){this.config={name:A,columns:T,unique:o,only:F,method:y}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new _4(this.config,T)}}class _4{static[M]="PgIndex";config;constructor(T,o){this.config={...T,table:o}}}function X_(T){return new J4(!0,T)}class Y_{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,o){return T}setToken(T){return this.authToken=T,this}static[M]="PgPreparedQuery";joinsNotNullableMap}class Z_{constructor(T){this.dialect=T}static[M]="PgSession";execute(T,o){return wT.startActiveSpan("drizzle.operation",()=>{return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(o).execute(void 0,o)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,o){let F=await this.execute(T,o);return Number(F[0].count)}}class H_ extends iy{constructor(T,o,F,A=0){super(T,o,F);this.schema=F,this.nestedIndex=A}static[M]="PgTransaction";rollback(){throw new bJ}getTransactionConfigSQL(T){let o=[];if(T.isolationLevel)o.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)o.push(T.accessMode);if(typeof T.deferrable==="boolean")o.push(T.deferrable?"deferrable":"not deferrable");return X.raw(o.join(" "))}setTransaction(T){return this.session.execute(X`set transaction ${this.getTransactionConfigSQL(T)}`)}}class R4 extends Y_{constructor(T,o,F,A,y,S,f){super({sql:o,params:F});this.client=T,this.queryString=o,this.params=F,this.logger=A,this.fields=y,this._isResponseInArrayMode=S,this.customResultMapper=f}static[M]="PostgresJsPreparedQuery";async execute(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let F=jJ(this.params,T);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:A,queryString:y,client:S,joinsNotNullableMap:f,customResultMapper:$}=this;if(!A&&!$)return wT.startActiveSpan("drizzle.driver.execute",()=>{return S.unsafe(y,F)});let _=await wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":y,"drizzle.query.params":JSON.stringify(F)}),S.unsafe(y,F).values()});return wT.startActiveSpan("drizzle.mapResponse",()=>{return $?$(_):_.map((J)=>MM(A,J,f))})})}all(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let F=jJ(this.params,T);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.client.unsafe(this.queryString,F)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class dy extends Z_{constructor(T,o,F,A={}){super(o);this.client=T,this.schema=F,this.options=A,this.logger=A.logger??new vJ}static[M]="PostgresJsSession";logger;prepareQuery(T,o,F,A,y){return new R4(this.client,T.sql,T.params,this.logger,o,A,y)}query(T,o){return this.logger.logQuery(T,o),this.client.unsafe(T,o).values()}queryObjects(T,o){return this.client.unsafe(T,o)}transaction(T,o){return this.client.begin(async(F)=>{let A=new dy(F,this.dialect,this.schema,this.options),y=new G_(this.dialect,A,this.schema);if(o)await y.setTransaction(o);return T(y)})}}class G_ extends H_{constructor(T,o,F,A=0){super(T,o,F,A);this.session=o}static[M]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((o)=>{let F=new dy(o,this.dialect,this.schema,this.session.options),A=new G_(this.dialect,F,this.schema);return T(A)})}}class W4 extends iy{static[M]="PostgresJsDatabase"}function qA(T,o={}){let F=(_)=>_;for(let _ of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[_]=F,T.options.serializers[_]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let A=new TA({casing:o.casing}),y;if(o.logger===!0)y=new qJ;else if(o.logger!==!1)y=o.logger;let S;if(o.schema){let _=q2(o.schema,P2);S={fullSchema:o.schema,schema:_.tables,tableNamesMap:_.tableNamesMap}}let f=new dy(T,A,S,{logger:y}),$=new W4(A,f,S);return $.$client=T,$}function zf(...T){if(typeof T[0]==="string"){let o=xA(T[0]);return qA(o,T[1])}if(YM(T[0])){let{connection:o,client:F,...A}=T[0];if(F)return qA(F,A);if(typeof o==="object"&&o.url!==void 0){let{url:S,...f}=o,$=xA(S,f);return qA($,A)}let y=xA(o);return qA(y,A)}return qA(T[0],T[1])}((T)=>{function o(F){return qA({options:{parsers:{},serializers:{}}},F)}T.mock=o})(zf||(zf={}));var E_={};ZX(E_,{users:()=>oA,untrackedUserColumnNames:()=>zH,twoFactorMethod:()=>Z4,trackedUserColumnName:()=>QH,trackableUserColumnNames:()=>X4,signInHistory:()=>DH,role:()=>O4,players:()=>w_,passwordResetAttempts:()=>LH,games:()=>Qf,banishedIps:()=>CH,accountActions:()=>VH,accountAction:()=>Y4});function M4(T){return X`lower(${T})`}var O4=Cy("role",["admin","user"]),oA=jF("users",{id:qo().primaryKey().defaultRandom(),username:Mo({length:16}).notNull(),emailOffered:Mo({length:254}).notNull(),emailVerified:Mo({length:254}),password:Mo({length:254}),createdAt:io({withTimezone:!0}).notNull().defaultNow(),createdIp:Mo({length:45}).notNull(),isActive:jy().notNull().default(!1),verifiedAt:io({withTimezone:!0}),userRole:O4().default("user")},(T)=>[X_("usernameUniqueIndex").on(M4(T.username)),X_("emailVerifiedUniqueIndex").on(M4(T.emailVerified))]),zH=["id","createdAt","createdIp","isActive","verifiedAt"],X4=["username","emailOffered","emailVerified","password","userRole"],QH=Cy("trackedUserColumnName",X4),Y4=Cy("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),VH=jF("accountActions",{userId:qo().references(()=>oA.id).primaryKey(),action:Y4().notNull(),code:Mo({length:254}).notNull(),wrongCodeCount:xy().notNull().default(0),expiresAt:io({withTimezone:!0}).notNull()}),Qf=jF("games",{id:qo().primaryKey().defaultRandom()}),w_=jF("players",{userId:qo().notNull().references(()=>oA.id,{onDelete:"cascade"}),gameId:qo().notNull().references(()=>Qf.id,{onDelete:"cascade"}),score:xy().notNull()},(T)=>[W2({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),DH=jF("signInHistory",{id:qo().primaryKey().defaultRandom(),userId:qo().references(()=>oA.id,{onDelete:"cascade"}),signInTime:io({withTimezone:!0}).notNull().defaultNow(),ipAddress:Mo({length:45}).notNull(),userAgent:Mo({length:1024}),successful:jy().notNull().default(!1)}),Z4=Cy("twoFactorMethod",["email","phone"]),LH=jF("passwordResetAttempts",{id:qo().primaryKey().defaultRandom(),userId:qo().notNull().references(()=>oA.id,{onDelete:"cascade"}),requestedIp:Mo({length:45}).notNull(),requestedAt:io({withTimezone:!0}).notNull().defaultNow(),succeededIp:Mo({length:45}),succeededAt:io({withTimezone:!0}),verificationMethod:Z4().notNull()}),CH=jF("banishedIps",{ip:Mo({length:45}).primaryKey(),reason:Mo({length:2048}).notNull(),banishedAt:io({withTimezone:!0}).notNull().defaultNow(),banishedUntil:io({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class K_{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(IH.resolve(__dirname,"notify_update.sql"));let T=[lT(oA),lT(Qf),lT(w_)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(o)=>{let F=o.split(","),A=F[0],y=F[1],S=`${A}("${y}")`;if(this.observers.has(S))this.observers.get(S).next(S)})}constructor(T=!1,o={host:uo.POSTGRES_HOST,port:uo.POSTGRES_PORT,user:uo.POSTGRES_USER,password:uo.POSTGRES_PASSWORD,database:uo.POSTGRES_DATABASE}){this.options=o,this.sql=xA(o),this.drizzle=zf(this.sql,{schema:E_,logger:T})}observe(T,o){if(!this.observers.has(T))this.observers.set(T,new oT);this.observers.get(T).subscribe("SINGLETON",o)}}var Vf={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function kH(T){return Number.parseInt(T,10)}var BH=Eo(Vf),NH=BH.keyof().pipe((T)=>kH(T)),H4=Eo([NH,"string"]);var z_=new EJ,{logger:Qo}=z_;Object.assign(console,Qo,{log:Qo.info});Qo.info("ready");var U_=w4(import.meta.dir,"..","app"),Hg=new K_({logQuery(T,o){Qo.info("\uD83D\uDCDD query",T,o)}});xH({hostname:"0.0.0.0",port:uo.FRONTEND_PORT??3333,...hS??void 0,async fetch(T){try{let o=new Date,F=new URL(T.url);if(Qo.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(w4(U_,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let A=pH(U_,F.pathname),y=jH(A);if(!y.startsWith(U_))throw[403,"Access Denied"];if(!await G4(y).exists())return Response.redirect("/");return new Response(G4(y))}catch(o){let F=H4(o);if(F instanceof Eo.errors===!1){let[A,y]=F,f=`${Vf[A]}. ${y}`;return Qo.info(`\u274C ${A}: ${f}`),new Response(f,{status:A})}if(o instanceof Error)Qo.error(o.message);else{let A=CA(o);Qo.error("frontend server threw",A)}return new Response(Vf[500],{status:500})}}});function Df(){Qo.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{Qo.info("\u2757 received SIGINT; exiting gracefully"),Df()});process.on("SIGTERM",()=>{Qo.info("\u2757 received SIGTERM; exiting gracefully"),Df()});process.on("exit",()=>{Qo.info("\u2757 received exit; exiting gracefully"),Df()});z_.on("timeToStop",()=>{Qo.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),Df()});Qo.info(`\uD83D\uDEEB frontend server running at http://localhost:${uo.FRONTEND_PORT}/`);z_.emit("alive");
76
+ `;await F.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(J)}`),await F.execute($);let Z=(await F.all(U`select id, hash, created_at from ${U.identifier(J)}.${U.identifier(W)} order by created_at desc limit 1`))[0];await F.transaction(async(A)=>{for await(let X of T)if(!Z||Number(Z.created_at)<X.folderMillis){for(let O of X.sql)await A.execute(U.raw(O));await A.execute(U`insert into ${U.identifier(J)}.${U.identifier(W)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let F=[U`with `];for(let[_,W]of T.entries())if(F.push(U`${U.identifier(W._.alias)} as (${W._.sql})`),_<T.length-1)F.push(U`, `);return F.push(U` `),U.join(F)}buildDeleteQuery({table:T,where:F,returning:_,withList:W}){let J=this.buildWithCTE(W),$=_?U` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,Y=F?U` where ${F}`:void 0;return U`${J}delete from ${T}${Y}${$}`}buildUpdateSet(T,F){let _=T[C.Symbol.Columns],W=Object.keys(_).filter(($)=>F[$]!==void 0||_[$]?.onUpdateFn!==void 0),J=W.length;return U.join(W.flatMap(($,Y)=>{let Z=_[$],A=F[$]??U.param(Z.onUpdateFn(),Z),X=U`${U.identifier(this.casing.getColumnCasing(Z))} = ${A}`;if(Y<J-1)return[X,U.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:F,where:_,returning:W,withList:J,from:$,joins:Y}){let Z=this.buildWithCTE(J),A=T[hT.Symbol.Name],X=T[hT.Symbol.Schema],O=T[hT.Symbol.OriginalName],M=A===O?void 0:A,E=U`${X?U`${U.identifier(X)}.`:void 0}${U.identifier(O)}${M&&U` ${U.identifier(M)}`}`,K=this.buildUpdateSet(T,F),j=$&&U.join([U.raw(" from "),this.buildFromTable($)]),S=this.buildJoins(Y),P=W?U` returning ${this.buildSelection(W,{isSingleTable:!$})}`:void 0,f=_?U` where ${_}`:void 0;return U`${Z}update ${E} set ${K}${j}${S}${f}${P}`}buildSelection(T,{isSingleTable:F=!1}={}){let _=T.length,W=T.flatMap(({field:J},$)=>{let Y=[];if(R(J,k.Aliased)&&J.isSelectionField)Y.push(U.identifier(J.fieldAlias));else if(R(J,k.Aliased)||R(J,k)){let Z=R(J,k.Aliased)?J.sql:J;if(F)Y.push(new k(Z.queryChunks.map((A)=>{if(R(A,L))return U.identifier(this.casing.getColumnCasing(A));return A})));else Y.push(Z);if(R(J,k.Aliased))Y.push(U` as ${U.identifier(J.fieldAlias)}`)}else if(R(J,XT))if(F)Y.push(U.identifier(this.casing.getColumnCasing(J)));else Y.push(J);if($<_-1)Y.push(U`, `);return Y});return U.join(W)}buildJoins(T){if(!T||T.length===0)return;let F=[];for(let[_,W]of T.entries()){if(_===0)F.push(U` `);let J=W.table,$=W.lateral?U` lateral`:void 0,Y=W.on?U` on ${W.on}`:void 0;if(R(J,hT)){let Z=J[hT.Symbol.Name],A=J[hT.Symbol.Schema],X=J[hT.Symbol.OriginalName],O=Z===X?void 0:W.alias;F.push(U`${U.raw(W.joinType)} join${$} ${A?U`${U.identifier(A)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${Y}`)}else if(R(J,Y0)){let Z=J[MT].name,A=J[MT].schema,X=J[MT].originalName,O=Z===X?void 0:W.alias;F.push(U`${U.raw(W.joinType)} join${$} ${A?U`${U.identifier(A)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${Y}`)}else F.push(U`${U.raw(W.joinType)} join${$} ${J}${Y}`);if(_<T.length-1)F.push(U` `)}return U.join(F)}buildFromTable(T){if(R(T,C)&&T[C.Symbol.IsAlias]){let F=U`${U.identifier(T[C.Symbol.OriginalName])}`;if(T[C.Symbol.Schema])F=U`${U.identifier(T[C.Symbol.Schema])}.${F}`;return U`${F} ${U.identifier(T[C.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:F,fieldsFlat:_,where:W,having:J,table:$,joins:Y,orderBy:Z,groupBy:A,limit:X,offset:O,lockingClause:M,distinct:E,setOperators:K}){let j=_??V0(F);for(let e of j)if(R(e.field,XT)&&vT(e.field.table)!==(R($,yT)?$._.alias:R($,UW)?$[MT].name:R($,k)?void 0:vT($))&&!((xT)=>Y?.some(({alias:G0})=>G0===(xT[C.Symbol.IsAlias]?vT(xT):xT[C.Symbol.BaseName])))(e.field.table)){let xT=vT(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${xT}"."${e.field.name}", but the table "${xT}" is not part of the query! Did you forget to join it?`)}let S=!Y||Y.length===0,P=this.buildWithCTE(T),f;if(E)f=E===!0?U` distinct`:U` distinct on (${U.join(E.on,U`, `)})`;let y=this.buildSelection(j,{isSingleTable:S}),h=this.buildFromTable($),TT=this.buildJoins(Y),u=W?U` where ${W}`:void 0,g=J?U` having ${J}`:void 0,d;if(Z&&Z.length>0)d=U` order by ${U.join(Z,U`, `)}`;let ST;if(A&&A.length>0)ST=U` group by ${U.join(A,U`, `)}`;let A0=typeof X==="object"||typeof X==="number"&&X>=0?U` limit ${X}`:void 0,D=O?U` offset ${O}`:void 0,$T=U.empty();if(M){let e=U` for ${U.raw(M.strength)}`;if(M.config.of)e.append(U` of ${U.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],U`, `)}`);if(M.config.noWait)e.append(U` nowait`);else if(M.config.skipLocked)e.append(U` skip locked`);$T.append(e)}let l=U`${P}select${f} ${y} from ${h}${TT}${u}${ST}${g}${d}${A0}${D}${$T}`;if(K.length>0)return this.buildSetOperations(l,K);return l}buildSetOperations(T,F){let[_,...W]=F;if(!_)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:_});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:_}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:F,isAll:_,rightSelect:W,limit:J,orderBy:$,offset:Y}}){let Z=U`(${T.getSQL()}) `,A=U`(${W.getSQL()})`,X;if($&&$.length>0){let K=[];for(let j of $)if(R(j,L))K.push(U.identifier(j.name));else if(R(j,k)){for(let S=0;S<j.queryChunks.length;S++){let P=j.queryChunks[S];if(R(P,L))j.queryChunks[S]=U.identifier(P.name)}K.push(U`${j}`)}else K.push(U`${j}`);X=U` order by ${U.join(K,U`, `)} `}let O=typeof J==="object"||typeof J==="number"&&J>=0?U` limit ${J}`:void 0,M=U.raw(`${F} ${_?"all ":""}`),E=Y?U` offset ${Y}`:void 0;return U`${Z}${M}${A}${X}${O}${E}`}buildInsertQuery({table:T,values:F,onConflict:_,returning:W,withList:J,select:$,overridingSystemValue_:Y}){let Z=[],A=T[C.Symbol.Columns],X=Object.entries(A).filter(([P,f])=>!f.shouldDisableInsert()),O=X.map(([,P])=>U.identifier(this.casing.getColumnCasing(P)));if($){let P=F;if(R(P,k))Z.push(P);else Z.push(P.getSQL())}else{let P=F;Z.push(U.raw("values "));for(let[f,y]of P.entries()){let h=[];for(let[TT,u]of X){let g=y[TT];if(g===void 0||R(g,Q0)&&g.value===void 0)if(u.defaultFn!==void 0){let d=u.defaultFn(),ST=R(d,k)?d:U.param(d,u);h.push(ST)}else if(!u.default&&u.onUpdateFn!==void 0){let d=u.onUpdateFn(),ST=R(d,k)?d:U.param(d,u);h.push(ST)}else h.push(U`default`);else h.push(g)}if(Z.push(h),f<P.length-1)Z.push(U`, `)}}let M=this.buildWithCTE(J),E=U.join(Z),K=W?U` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,j=_?U` on conflict ${_}`:void 0,S=Y===!0?U`overriding system value `:void 0;return U`${M}insert into ${T} ${O} ${S}${E}${j}${K}`}buildRefreshMaterializedViewQuery({view:T,concurrently:F,withNoData:_}){let W=F?U` concurrently`:void 0,J=_?U` with no data`:void 0;return U`refresh materialized view${W} ${T}${J}`}prepareTyping(T){if(R(T,z1)||R(T,Q1))return"json";else if(R(T,E1))return"decimal";else if(R(T,R1))return"time";else if(R(T,w1)||R(T,K1))return"timestamp";else if(R(T,U1)||R(T,M1))return"date";else if(R(T,V1))return"uuid";else return"none"}sqlToQuery(T,F){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:F})}buildRelationalQueryWithoutPK({fullSchema:T,schema:F,tableNamesMap:_,table:W,tableConfig:J,queryConfig:$,tableAlias:Y,nestedQueryRelation:Z,joinOn:A}){let X=[],O,M,E=[],K,j=[];if($===!0)X=Object.entries(J.columns).map(([f,y])=>({dbKey:y.name,tsKey:f,field:m0(y,Y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let P=Object.fromEntries(Object.entries(J.columns).map(([g,d])=>[g,m0(d,Y)]));if($.where){let g=typeof $.where==="function"?$.where(P,$A()):$.where;K=g&&FW(g,Y)}let f=[],y=[];if($.columns){let g=!1;for(let[d,ST]of Object.entries($.columns)){if(ST===void 0)continue;if(d in J.columns){if(!g&&ST===!0)g=!0;y.push(d)}}if(y.length>0)y=g?y.filter((d)=>$.columns?.[d]===!0):Object.keys(J.columns).filter((d)=>!y.includes(d))}else y=Object.keys(J.columns);for(let g of y){let d=J.columns[g];f.push({tsKey:g,value:d})}let h=[];if($.with)h=Object.entries($.with).filter((g)=>!!g[1]).map(([g,d])=>({tsKey:g,queryConfig:d,relation:J.relations[g]}));let TT;if($.extras){TT=typeof $.extras==="function"?$.extras(P,{sql:U}):$.extras;for(let[g,d]of Object.entries(TT))f.push({tsKey:g,value:y4(d,Y)})}for(let{tsKey:g,value:d}of f)X.push({dbKey:R(d,k.Aliased)?d.fieldAlias:J.columns[g].name,tsKey:g,field:R(d,XT)?m0(d,Y):d,relationTableTsKey:void 0,isJson:!1,selection:[]});let u=typeof $.orderBy==="function"?$.orderBy(P,YA()):$.orderBy??[];if(!Array.isArray(u))u=[u];E=u.map((g)=>{if(R(g,XT))return m0(g,Y);return FW(g,Y)}),O=$.limit,M=$.offset;for(let{tsKey:g,queryConfig:d,relation:ST}of h){let A0=XA(F,_,ST),D=SF(ST.referencedTable),$T=_[D],l=`${Y}_${g}`,e=YW(...A0.fields.map((S0,qF)=>D1(m0(A0.references[qF],l),m0(S0,Y)))),xT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:F,tableNamesMap:_,table:T[$T],tableConfig:F[$T],queryConfig:R(ST,zF)?d===!0?{limit:1}:{...d,limit:1}:d,tableAlias:l,joinOn:e,nestedQueryRelation:ST}),G0=U`${U.identifier(l)}.${U.identifier("data")}`.as(g);j.push({on:U`true`,table:new yT(xT.sql,{},l),alias:l,joinType:"left",lateral:!0}),X.push({dbKey:g,tsKey:g,field:G0,relationTableTsKey:$T,isJson:!0,selection:xT.selection})}}if(X.length===0)throw new H1({message:`No fields selected for table "${J.tsName}" ("${Y}")`});let S;if(K=YW(A,K),Z){let P=U`json_build_array(${U.join(X.map(({field:h,tsKey:TT,isJson:u})=>u?U`${U.identifier(`${Y}_${TT}`)}.${U.identifier("data")}`:R(h,k.Aliased)?h.sql:h),U`, `)})`;if(R(Z,ZW))P=U`coalesce(json_agg(${P}${E.length>0?U` order by ${U.join(E,U`, `)}`:void 0}), '[]'::json)`;let f=[{dbKey:"data",tsKey:"data",field:P.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:X}];if(O!==void 0||M!==void 0||E.length>0)S=this.buildSelectQuery({table:G1(W,Y),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:K,limit:O,offset:M,orderBy:E,setOperators:[]}),K=void 0,O=void 0,M=void 0,E=[];else S=G1(W,Y);S=this.buildSelectQuery({table:R(S,hT)?S:new yT(S,{},Y),fields:{},fieldsFlat:f.map(({field:h})=>({path:[],field:R(h,XT)?m0(h,Y):h})),joins:j,where:K,limit:O,offset:M,orderBy:E,setOperators:[]})}else S=this.buildSelectQuery({table:G1(W,Y),fields:{},fieldsFlat:X.map(({field:P})=>({path:[],field:R(P,XT)?m0(P,Y):P})),joins:j,where:K,limit:O,offset:M,orderBy:E,setOperators:[]});return{tableTsKey:J.tsName,sql:S,selection:X}}}class $J{static[H]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class aT{static[H]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let F=!!this.fields,_=T,W;if(this.fields)W=this.fields;else if(R(_,yT))W=Object.fromEntries(Object.keys(_._.selectedFields).map((J)=>[J,_[J]]));else if(R(_,UW))W=_[MT].selectedFields;else if(R(_,k))W={};else W=hY(_);return new YJ({table:_,fields:W,isPartialSelect:F,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class fA extends $J{static[H]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:F,isPartialSelect:_,session:W,dialect:J,withList:$,distinct:Y}){super();this.config={withList:$,table:T,fields:{...F},distinct:Y,setOperators:[]},this.isPartialSelect=_,this.session=W,this.dialect=J,this._={selectedFields:F},this.tableName=a0(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T,F){return(_,W)=>{let J=this.tableName,$=a0(_);if(typeof $==="string"&&this.config.joins?.some((Y)=>Y.alias===$))throw new Error(`Alias "${$}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof $==="string"&&!R(_,k)){let Y=R(_,yT)?_._.selectedFields:R(_,Y0)?_[MT].selectedFields:_[C.Symbol.Columns];this.config.fields[$]=Y}}if(typeof W==="function")W=W(new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:W,table:_,joinType:T,alias:$,lateral:F}),typeof $==="string")switch(T){case"left":{this.joinsNotNullableMap[$]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([Y])=>[Y,!1])),this.joinsNotNullableMap[$]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[$]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([Y])=>[Y,!1])),this.joinsNotNullableMap[$]=!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,F){return(_)=>{let W=typeof _==="function"?_(xH()):_;if(!_W(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:F,rightSelect:W}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let F=T[0](new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(F)?F:[F]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let F=T[0](new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),_=Array.isArray(F)?F:[F];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=_;else this.config.orderBy=_}else{let F=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,F={}){return this.config.lockingClause={strength:T,config:F},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...F}=this.dialect.sqlToQuery(this.getSQL());return F}as(T){return new Proxy(new yT(this.getSQL(),this.config.fields,T),new LT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new LT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class YJ extends fA{static[H]="PgSelect";_prepare(T){let{session:F,config:_,dialect:W,joinsNotNullableMap:J,authToken:$}=this;if(!F)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return AT.startActiveSpan("drizzle.prepareQuery",()=>{let Y=V0(_.fields),Z=F.prepareQuery(W.sqlToQuery(this.getSQL()),Y,T,!0);return Z.joinsNotNullableMap=J,Z.setToken($)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}bY(YJ,[rT]);function X_(T,F){return(_,W,...J)=>{let $=[W,...J].map((Y)=>({type:T,isAll:F,rightSelect:Y}));for(let Y of $)if(!_W(_.getSelectedFields(),Y.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return _.addSetOperators($)}}var xH=()=>({union:bH,unionAll:hH,intersect:pH,intersectAll:gH,except:mH,exceptAll:oH}),bH=X_("union",!1),hH=X_("union",!0),pH=X_("intersect",!1),gH=X_("intersect",!0),mH=X_("except",!1),oH=X_("except",!0);class MW{static[H]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=R(T,BF)?T:void 0,this.dialectConfig=R(T,BF)?void 0:T}$with=(T,F)=>{let _=this;return{as:(J)=>{if(typeof J==="function")J=J(_);return new Proxy(new a_(J.getSQL(),F??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new LT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let F=this;function _($){return new aT({fields:$??void 0,session:void 0,dialect:F.getDialect(),withList:T})}function W($){return new aT({fields:$??void 0,session:void 0,dialect:F.getDialect(),distinct:!0})}function J($,Y){return new aT({fields:Y??void 0,session:void 0,dialect:F.getDialect(),distinct:{on:$}})}return{select:_,selectDistinct:W,selectDistinctOn:J}}select(T){return new aT({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new aT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,F){return new aT({fields:F??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new BF(this.dialectConfig);return this.dialect}}class x1{constructor(T,F,_,W,J){this.table=T,this.session=F,this.dialect=_,this.withList=W,this.overridingSystemValue_=J}static[H]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let F=T.map((_)=>{let W={},J=this.table[C.Symbol.Columns];for(let $ of Object.keys(_)){let Y=_[$];W[$]=R(Y,k)?Y:new Q0(Y,J[$])}return W});return new ZJ(this.table,F,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let F=typeof T==="function"?T(new MW):T;if(!R(F,k)&&!_W(this.table[X1],F._.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 ZJ(this.table,F,this.session,this.dialect,this.withList,!0)}}class ZJ extends rT{constructor(T,F,_,W,J,$,Y){super();this.session=_,this.dialect=W,this.config={table:T,values:F,withList:J,select:$,overridingSystemValue_:Y}}static[H]="PgInsert";config;returning(T=this.config.table[C.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=V0(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=U`do nothing`;else{let F="";F=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let _=T.where?U` where ${T.where}`:void 0;this.config.onConflict=U`(${U.raw(F)})${_} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let F=T.where?U` where ${T.where}`:void 0,_=T.targetWhere?U` where ${T.targetWhere}`:void 0,W=T.setWhere?U` where ${T.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,O1(this.config.table,T.set)),$="";return $=Array.isArray(T.target)?T.target.map((Y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=U`(${U.raw($)})${_} do update set ${J}${F}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...F}=this.dialect.sqlToQuery(this.getSQL());return F}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new LT({alias:vT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class XJ extends rT{constructor(T,F,_){super();this.session=F,this.dialect=_,this.config={view:T}}static[H]="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,...F}=this.dialect.sqlToQuery(this.getSQL());return F}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class b1{constructor(T,F,_,W){this.table=T,this.session=F,this.dialect=_,this.withList=W}static[H]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new qA(this.table,O1(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class qA extends rT{constructor(T,F,_,W,J){super();this.session=_,this.dialect=W,this.config={set:F,table:T,withList:J,joins:[]},this.tableName=a0(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[H]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let F=T,_=a0(F);if(typeof _==="string")this.joinsNotNullableMap[_]=!0;return this.config.from=F,this}getTableLikeFields(T){if(R(T,hT))return T[C.Symbol.Columns];else if(R(T,yT))return T._.selectedFields;return T[MT].selectedFields}createJoin(T){return(F,_)=>{let W=a0(F);if(typeof W==="string"&&this.config.joins.some((J)=>J.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof _==="function"){let J=this.config.from&&!R(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;_=_(new Proxy(this.config.table[C.Symbol.Columns],new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:_,table:F,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[C.Symbol.Columns]),this.config.from){let F=a0(this.config.from);if(typeof F==="string"&&this.config.from&&!R(this.config.from,k)){let _=this.getTableLikeFields(this.config.from);T[F]=_}for(let _ of this.config.joins){let W=a0(_.table);if(typeof W==="string"&&!R(_.table,k)){let J=this.getTableLikeFields(_.table);T[W]=J}}}}return this.config.returningFields=T,this.config.returning=V0(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...F}=this.dialect.sqlToQuery(this.getSQL());return F}_prepare(T){let F=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return F.joinsNotNullableMap=this.joinsNotNullableMap,F}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new LT({alias:vT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class QW extends k{constructor(T){super(QW.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=QW.buildCount(T.source,T.filters)}sql;token;static[H]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,F){return U`(select count(*) from ${T}${U.raw(" where ").if(F)}${F})`}static buildCount(T,F){return U`select count(*) as count from ${T}${U.raw(" where ").if(F)}${F};`}setToken(T){return this.token=T,this}then(T,F){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,F)}catch(T){return this.then(void 0,T)}finally(T){return this.then((F)=>{return T?.(),F},(F)=>{throw T?.(),F})}}class GJ{constructor(T,F,_,W,J,$,Y){this.fullSchema=T,this.schema=F,this.tableNamesMap=_,this.table=W,this.tableConfig=J,this.dialect=$,this.session=Y}static[H]="PgRelationalQueryBuilder";findMany(T){return new AJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new AJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class AJ extends rT{constructor(T,F,_,W,J,$,Y,Z,A){super();this.fullSchema=T,this.schema=F,this.tableNamesMap=_,this.table=W,this.tableConfig=J,this.dialect=$,this.session=Y,this.config=Z,this.mode=A}static[H]="PgRelationalQuery";_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:F,builtQuery:_}=this._toSQL();return this.session.prepareQuery(_,void 0,T,!0,(W,J)=>{let $=W.map((Y)=>L1(this.schema,this.tableConfig,Y,F.selection,J));if(this.mode==="first")return $[0];return $})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),F=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:F}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class HJ extends rT{constructor(T,F,_,W){super();this.execute=T,this.sql=F,this.query=_,this.mapBatchResult=W}static[H]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,F){return F?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class zW{constructor(T,F,_){if(this.dialect=T,this.session=F,this._=_?{schema:_.schema,fullSchema:_.fullSchema,tableNamesMap:_.tableNamesMap,session:F}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:F},this.query={},this._.schema)for(let[W,J]of Object.entries(this._.schema))this.query[W]=new GJ(_.fullSchema,this._.schema,this._.tableNamesMap,_.fullSchema[W],J,T,F)}static[H]="PgDatabase";query;$with=(T,F)=>{let _=this;return{as:(J)=>{if(typeof J==="function")J=J(new MW(_.dialect));return new Proxy(new a_(J.getSQL(),F??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new LT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,F){return new QW({source:T,filters:F,session:this.session})}with(...T){let F=this;function _(A){return new aT({fields:A??void 0,session:F.session,dialect:F.dialect,withList:T})}function W(A){return new aT({fields:A??void 0,session:F.session,dialect:F.dialect,withList:T,distinct:!0})}function J(A,X){return new aT({fields:X??void 0,session:F.session,dialect:F.dialect,withList:T,distinct:{on:A}})}function $(A){return new b1(A,F.session,F.dialect,T)}function Y(A){return new x1(A,F.session,F.dialect,T)}function Z(A){return new v1(A,F.session,F.dialect,T)}return{select:_,selectDistinct:W,selectDistinctOn:J,update:$,insert:Y,delete:Z}}select(T){return new aT({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new aT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,F){return new aT({fields:F??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new b1(T,this.session,this.dialect)}insert(T){return new x1(T,this.session,this.dialect)}delete(T){return new v1(T,this.session,this.dialect)}refreshMaterializedView(T){return new XJ(T,this.session,this.dialect)}authToken;execute(T){let F=typeof T==="string"?U.raw(T):T.getSQL(),_=this.dialect.sqlToQuery(F),W=this.session.prepareQuery(_,void 0,void 0,!1);return new HJ(()=>W.execute(void 0,this.authToken),F,_,(J)=>W.mapResult(J,!0))}transaction(T,F){return this.session.transaction(T,F)}}class jA{constructor(T,F){this.unique=T,this.name=F}static[H]="PgIndexBuilderOn";on(...T){return new h1(T.map((F)=>{if(R(F,k))return F;F=F;let _=new r_(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),_}),this.unique,!1,this.name)}onOnly(...T){return new h1(T.map((F)=>{if(R(F,k))return F;F=F;let _=new r_(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=F.defaultConfig,_}),this.unique,!0,this.name)}using(T,...F){return new h1(F.map((_)=>{if(R(_,k))return _;_=_;let W=new r_(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=JSON.parse(JSON.stringify(_.defaultConfig)),W}),this.unique,!0,this.name,T)}}class h1{static[H]="PgIndexBuilder";config;constructor(T,F,_,W,J="btree"){this.config={name:W,columns:T,unique:F,only:_,method:J}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new yA(this.config,T)}}class yA{static[H]="PgIndex";config;constructor(T,F){this.config={...T,table:F}}}function OJ(T){return new jA(!0,T)}class UJ{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,F){return T}setToken(T){return this.authToken=T,this}static[H]="PgPreparedQuery";joinsNotNullableMap}class MJ{constructor(T){this.dialect=T}static[H]="PgSession";execute(T,F){return AT.startActiveSpan("drizzle.operation",()=>{return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(F).execute(void 0,F)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,F){let _=await this.execute(T,F);return Number(_[0].count)}}class QJ extends zW{constructor(T,F,_,W=0){super(T,F,_);this.schema=_,this.nestedIndex=W}static[H]="PgTransaction";rollback(){throw new P4}getTransactionConfigSQL(T){let F=[];if(T.isolationLevel)F.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)F.push(T.accessMode);if(typeof T.deferrable==="boolean")F.push(T.deferrable?"deferrable":"not deferrable");return U.raw(F.join(" "))}setTransaction(T){return this.session.execute(U`set transaction ${this.getTransactionConfigSQL(T)}`)}}class PA extends UJ{constructor(T,F,_,W,J,$,Y){super({sql:F,params:_});this.client=T,this.queryString=F,this.params=_,this.logger=W,this.fields=J,this._isResponseInArrayMode=$,this.customResultMapper=Y}static[H]="PostgresJsPreparedQuery";async execute(T={}){return AT.startActiveSpan("drizzle.execute",async(F)=>{let _=j4(this.params,T);F?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(_)}),this.logger.logQuery(this.queryString,_);let{fields:W,queryString:J,client:$,joinsNotNullableMap:Y,customResultMapper:Z}=this;if(!W&&!Z)return AT.startActiveSpan("drizzle.driver.execute",()=>{return $.unsafe(J,_)});let A=await AT.startActiveSpan("drizzle.driver.execute",()=>{return F?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(_)}),$.unsafe(J,_).values()});return AT.startActiveSpan("drizzle.mapResponse",()=>{return Z?Z(A):A.map((X)=>xY(W,X,Y))})})}all(T={}){return AT.startActiveSpan("drizzle.execute",async(F)=>{let _=j4(this.params,T);return F?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(_)}),this.logger.logQuery(this.queryString,_),AT.startActiveSpan("drizzle.driver.execute",()=>{return F?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(_)}),this.client.unsafe(this.queryString,_)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class EW extends MJ{constructor(T,F,_,W={}){super(F);this.client=T,this.schema=_,this.options=W,this.logger=W.logger??new x4}static[H]="PostgresJsSession";logger;prepareQuery(T,F,_,W,J){return new PA(this.client,T.sql,T.params,this.logger,F,W,J)}query(T,F){return this.logger.logQuery(T,F),this.client.unsafe(T,F).values()}queryObjects(T,F){return this.client.unsafe(T,F)}transaction(T,F){return this.client.begin(async(_)=>{let W=new EW(_,this.dialect,this.schema,this.options),J=new zJ(this.dialect,W,this.schema);if(F)await J.setTransaction(F);return T(J)})}}class zJ extends QJ{constructor(T,F,_,W=0){super(T,F,_,W);this.session=F}static[H]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((F)=>{let _=new EW(F,this.dialect,this.schema,this.session.options),W=new zJ(this.dialect,_,this.schema);return T(W)})}}class vA extends zW{static[H]="PostgresJsDatabase"}function A_(T,F={}){let _=(A)=>A;for(let A of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[A]=_,T.options.serializers[A]=_;T.options.serializers["114"]=_,T.options.serializers["3802"]=_;let W=new BF({casing:F.casing}),J;if(F.logger===!0)J=new v4;else if(F.logger!==!1)J=F.logger;let $;if(F.schema){let A=ZA(F.schema,AA);$={fullSchema:F.schema,schema:A.tables,tableNamesMap:A.tableNamesMap}}let Y=new EW(T,W,$,{logger:J}),Z=new vA(W,Y,$);return Z.$client=T,Z}function p1(...T){if(typeof T[0]==="string"){let F=Z_(T[0]);return A_(F,T[1])}if(pY(T[0])){let{connection:F,client:_,...W}=T[0];if(_)return A_(_,W);if(typeof F==="object"&&F.url!==void 0){let{url:$,...Y}=F,Z=Z_($,Y);return A_(Z,W)}let J=Z_(F);return A_(J,W)}return A_(T[0],T[1])}((T)=>{function F(_){return A_({options:{parsers:{},serializers:{}}},_)}T.mock=F})(p1||(p1={}));var RJ={};g5(RJ,{users:()=>fF,untrackedUserColumnNames:()=>uH,twoFactorMethod:()=>gA,trackedUserColumnName:()=>cH,trackableUserColumnNames:()=>hA,signInHistory:()=>lH,role:()=>bA,players:()=>EJ,passwordResetAttempts:()=>iH,games:()=>g1,banishedIps:()=>tH,accountActions:()=>dH,accountAction:()=>pA});function xA(T){return U`lower(${T})`}var bA=s_("role",["admin","user"]),fF=QF("users",{id:D0().primaryKey().defaultRandom(),username:sT({length:16}).notNull(),emailOffered:sT({length:254}).notNull(),emailVerified:sT({length:254}),password:sT({length:254}),createdAt:y0({withTimezone:!0}).notNull().defaultNow(),createdIp:sT({length:45}).notNull(),isActive:WW().notNull().default(!1),verifiedAt:y0({withTimezone:!0}),userRole:bA().default("user")},(T)=>[OJ("usernameUniqueIndex").on(xA(T.username)),OJ("emailVerifiedUniqueIndex").on(xA(T.emailVerified))]),uH=["id","createdAt","createdIp","isActive","verifiedAt"],hA=["username","emailOffered","emailVerified","password","userRole"],cH=s_("trackedUserColumnName",hA),pA=s_("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),dH=QF("accountActions",{userId:D0().references(()=>fF.id).primaryKey(),action:pA().notNull(),code:sT({length:254}).notNull(),wrongCodeCount:JW().notNull().default(0),expiresAt:y0({withTimezone:!0}).notNull()}),g1=QF("games",{id:D0().primaryKey().defaultRandom()}),EJ=QF("players",{userId:D0().notNull().references(()=>fF.id,{onDelete:"cascade"}),gameId:D0().notNull().references(()=>g1.id,{onDelete:"cascade"}),score:JW().notNull()},(T)=>[vX({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),lH=QF("signInHistory",{id:D0().primaryKey().defaultRandom(),userId:D0().references(()=>fF.id,{onDelete:"cascade"}),signInTime:y0({withTimezone:!0}).notNull().defaultNow(),ipAddress:sT({length:45}).notNull(),userAgent:sT({length:1024}),successful:WW().notNull().default(!1)}),gA=s_("twoFactorMethod",["email","phone"]),iH=QF("passwordResetAttempts",{id:D0().primaryKey().defaultRandom(),userId:D0().notNull().references(()=>fF.id,{onDelete:"cascade"}),requestedIp:sT({length:45}).notNull(),requestedAt:y0({withTimezone:!0}).notNull().defaultNow(),succeededIp:sT({length:45}),succeededAt:y0({withTimezone:!0}),verificationMethod:gA().notNull()}),tH=QF("banishedIps",{ip:sT({length:45}).primaryKey(),reason:sT({length:2048}).notNull(),banishedAt:y0({withTimezone:!0}).notNull().defaultNow(),banishedUntil:y0({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(nH.resolve(__dirname,"notify_update.sql"));let T=[vT(fF),vT(g1),vT(EJ)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(F)=>{let _=F.split(","),W=_[0],J=_[1],$=`${W}("${J}")`;if(this.observers.has($))this.observers.get($).next($)})}constructor(T=!1,F={host:q0.POSTGRES_HOST,port:q0.POSTGRES_PORT,user:q0.POSTGRES_USER,password:q0.POSTGRES_PASSWORD,database:q0.POSTGRES_DATABASE}){this.options=F,this.sql=Z_(F),this.drizzle=p1(this.sql,{schema:RJ,logger:T})}observe(T,F){if(!this.observers.has(T))this.observers.set(T,new ZT);this.observers.get(T).subscribe("SINGLETON",F)}}var m1={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function rH(T){return Number.parseInt(T,10)}var sH=J0(m1),aH=sH.keyof().pipe((T)=>rH(T)),mA=J0([aH,"string"]);var VJ=new K4,{logger:X0}=VJ;Object.assign(console,X0,{log:X0.info});X0.info("ready");var KJ=uA(import.meta.dir,"..","app"),HP=new wJ({logQuery(T,F){X0.info("\uD83D\uDCDD query",T,F)}});FO({hostname:"0.0.0.0",port:q0.FRONTEND_PORT??3333,...J1??void 0,async fetch(T){try{let F=new Date,_=new URL(T.url);if(X0.info(T.method,_.pathname),_.pathname==="/")return new Response(Bun.file(uA(KJ,"index.html")));if(_.pathname==="/index.html")return Response.redirect("/");let W=eH(KJ,_.pathname),J=TO(W);if(!J.startsWith(KJ))throw[403,"Access Denied"];if(!await oA(J).exists())return Response.redirect("/");return new Response(oA(J))}catch(F){let _=mA(F);if(_ instanceof J0.errors===!1){let[W,J]=_,Y=`${m1[W]}. ${J}`;return X0.info(`\u274C ${W}: ${Y}`),new Response(Y,{status:W})}if(F instanceof Error)X0.error(F.message);else{let W=HY(F);X0.error("frontend server threw",W)}return new Response(m1[500],{status:500})}}});function o1(){X0.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{X0.info("\u2757 received SIGINT; exiting gracefully"),o1()});process.on("SIGTERM",()=>{X0.info("\u2757 received SIGTERM; exiting gracefully"),o1()});process.on("exit",()=>{X0.info("\u2757 received exit; exiting gracefully"),o1()});VJ.on("timeToStop",()=>{X0.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),o1()});X0.info(`\uD83D\uDEEB frontend server running at http://localhost:${q0.FRONTEND_PORT}/`);VJ.emit("alive");